gcc41 removal: Part 1 of 2: makefiles
[dragonfly.git] / contrib / gcc-4.1 / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.
56    The TREE_PURPOSE of each entry is either a DECL (for a function or
57    static data member), or a TYPE (for a class) indicating what we are
58    hoping to instantiate.  The TREE_VALUE is not used.  */
59 static GTY(()) tree pending_templates;
60 static GTY(()) tree last_pending_template;
61
62 int processing_template_parmlist;
63 static int template_header_count;
64
65 static GTY(()) tree saved_trees;
66 static GTY(()) varray_type inline_parm_levels;
67 static size_t inline_parm_levels_used;
68
69 static GTY(()) tree current_tinst_level;
70
71 static GTY(()) tree saved_access_scope;
72
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77
78 /* A map from local variable declarations in the body of the template
79    presently being instantiated to the corresponding instantiated
80    local variables.  */
81 static htab_t local_specializations;
82
83 #define UNIFY_ALLOW_NONE 0
84 #define UNIFY_ALLOW_MORE_CV_QUAL 1
85 #define UNIFY_ALLOW_LESS_CV_QUAL 2
86 #define UNIFY_ALLOW_DERIVED 4
87 #define UNIFY_ALLOW_INTEGER 8
88 #define UNIFY_ALLOW_OUTER_LEVEL 16
89 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
90 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
91
92 static void push_access_scope (tree);
93 static void pop_access_scope (tree);
94 static int resolve_overloaded_unification (tree, tree, tree, tree,
95                                            unification_kind_t, int);
96 static int try_one_overload (tree, tree, tree, tree, tree,
97                              unification_kind_t, int, bool);
98 static int unify (tree, tree, tree, tree, int);
99 static void add_pending_template (tree);
100 static void reopen_tinst_level (tree);
101 static tree classtype_mangled_name (tree);
102 static char* mangle_class_name_for_template (const char *, tree, tree);
103 static tree tsubst_initializer_list (tree, tree);
104 static tree get_class_bindings (tree, tree, tree);
105 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t, int);
106 static void tsubst_enum (tree, tree, tree);
107 static tree add_to_template_args (tree, tree);
108 static tree add_outermost_template_args (tree, tree);
109 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
110 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*);
111 static int  type_unification_real (tree, tree, tree, tree,
112                                    int, unification_kind_t, int);
113 static void note_template_header (int);
114 static tree convert_nontype_argument_function (tree, tree);
115 static tree convert_nontype_argument (tree, tree);
116 static tree convert_template_argument (tree, tree, tree,
117                                        tsubst_flags_t, int, tree);
118 static int for_each_template_parm (tree, tree_fn_t, void*,
119                                    struct pointer_set_t*);
120 static tree build_template_parm_index (int, int, int, tree, tree);
121 static int inline_needs_template_parms (tree);
122 static void push_inline_template_parms_recursive (tree, int);
123 static tree retrieve_local_specialization (tree);
124 static void register_local_specialization (tree, tree);
125 static tree reduce_template_parm_level (tree, tree, int);
126 static int mark_template_parm (tree, void *);
127 static int template_parm_this_level_p (tree, void *);
128 static tree tsubst_friend_function (tree, tree);
129 static tree tsubst_friend_class (tree, tree);
130 static int can_complete_type_without_circularity (tree);
131 static tree get_bindings (tree, tree, tree, bool);
132 static int template_decl_level (tree);
133 static int check_cv_quals_for_unify (int, tree, tree);
134 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
135 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
136 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
137 static void regenerate_decl_from_template (tree, tree);
138 static tree most_specialized (tree, tree, tree);
139 static tree most_specialized_class (tree, tree);
140 static int template_class_depth_real (tree, int);
141 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
142 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
143 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
144 static void check_specialization_scope (void);
145 static tree process_partial_specialization (tree);
146 static void set_current_access_from_decl (tree);
147 static void check_default_tmpl_args (tree, tree, int, int);
148 static tree tsubst_call_declarator_parms (tree, tree, tsubst_flags_t, tree);
149 static tree get_template_base (tree, tree, tree, tree);
150 static tree try_class_unification (tree, tree, tree, tree);
151 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
152                                            tree, tree);
153 static int template_args_equal (tree, tree);
154 static void tsubst_default_arguments (tree);
155 static tree for_each_template_parm_r (tree *, int *, void *);
156 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
157 static void copy_default_args_to_explicit_spec (tree);
158 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
159 static int eq_local_specializations (const void *, const void *);
160 static bool dependent_type_p_r (tree);
161 static tree tsubst (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
164
165 /* Make the current scope suitable for access checking when we are
166    processing T.  T can be FUNCTION_DECL for instantiated function
167    template, or VAR_DECL for static member variable (need by
168    instantiate_decl).  */
169
170 static void
171 push_access_scope (tree t)
172 {
173   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
174               || TREE_CODE (t) == VAR_DECL);
175
176   if (DECL_FRIEND_CONTEXT (t))
177     push_nested_class (DECL_FRIEND_CONTEXT (t));
178   else if (DECL_CLASS_SCOPE_P (t))
179     push_nested_class (DECL_CONTEXT (t));
180   else
181     push_to_top_level ();
182
183   if (TREE_CODE (t) == FUNCTION_DECL)
184     {
185       saved_access_scope = tree_cons
186         (NULL_TREE, current_function_decl, saved_access_scope);
187       current_function_decl = t;
188     }
189 }
190
191 /* Restore the scope set up by push_access_scope.  T is the node we
192    are processing.  */
193
194 static void
195 pop_access_scope (tree t)
196 {
197   if (TREE_CODE (t) == FUNCTION_DECL)
198     {
199       current_function_decl = TREE_VALUE (saved_access_scope);
200       saved_access_scope = TREE_CHAIN (saved_access_scope);
201     }
202
203   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
204     pop_nested_class ();
205   else
206     pop_from_top_level ();
207 }
208
209 /* Do any processing required when DECL (a member template
210    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
211    to DECL, unless it is a specialization, in which case the DECL
212    itself is returned.  */
213
214 tree
215 finish_member_template_decl (tree decl)
216 {
217   if (decl == error_mark_node)
218     return error_mark_node;
219
220   gcc_assert (DECL_P (decl));
221
222   if (TREE_CODE (decl) == TYPE_DECL)
223     {
224       tree type;
225
226       type = TREE_TYPE (decl);
227       if (IS_AGGR_TYPE (type)
228           && CLASSTYPE_TEMPLATE_INFO (type)
229           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
230         {
231           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
232           check_member_template (tmpl);
233           return tmpl;
234         }
235       return NULL_TREE;
236     }
237   else if (TREE_CODE (decl) == FIELD_DECL)
238     error ("data member %qD cannot be a member template", decl);
239   else if (DECL_TEMPLATE_INFO (decl))
240     {
241       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
242         {
243           check_member_template (DECL_TI_TEMPLATE (decl));
244           return DECL_TI_TEMPLATE (decl);
245         }
246       else
247         return decl;
248     }
249   else
250     error ("invalid member template declaration %qD", decl);
251
252   return error_mark_node;
253 }
254
255 /* Returns the template nesting level of the indicated class TYPE.
256
257    For example, in:
258      template <class T>
259      struct A
260      {
261        template <class U>
262        struct B {};
263      };
264
265    A<T>::B<U> has depth two, while A<T> has depth one.
266    Both A<T>::B<int> and A<int>::B<U> have depth one, if
267    COUNT_SPECIALIZATIONS is 0 or if they are instantiations, not
268    specializations.
269
270    This function is guaranteed to return 0 if passed NULL_TREE so
271    that, for example, `template_class_depth (current_class_type)' is
272    always safe.  */
273
274 static int
275 template_class_depth_real (tree type, int count_specializations)
276 {
277   int depth;
278
279   for (depth = 0;
280        type && TREE_CODE (type) != NAMESPACE_DECL;
281        type = (TREE_CODE (type) == FUNCTION_DECL)
282          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
283     {
284       if (TREE_CODE (type) != FUNCTION_DECL)
285         {
286           if (CLASSTYPE_TEMPLATE_INFO (type)
287               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
288               && ((count_specializations
289                    && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
290                   || uses_template_parms (CLASSTYPE_TI_ARGS (type))))
291             ++depth;
292         }
293       else
294         {
295           if (DECL_TEMPLATE_INFO (type)
296               && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
297               && ((count_specializations
298                    && DECL_TEMPLATE_SPECIALIZATION (type))
299                   || uses_template_parms (DECL_TI_ARGS (type))))
300             ++depth;
301         }
302     }
303
304   return depth;
305 }
306
307 /* Returns the template nesting level of the indicated class TYPE.
308    Like template_class_depth_real, but instantiations do not count in
309    the depth.  */
310
311 int
312 template_class_depth (tree type)
313 {
314   return template_class_depth_real (type, /*count_specializations=*/0);
315 }
316
317 /* Returns 1 if processing DECL as part of do_pending_inlines
318    needs us to push template parms.  */
319
320 static int
321 inline_needs_template_parms (tree decl)
322 {
323   if (! DECL_TEMPLATE_INFO (decl))
324     return 0;
325
326   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
327           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
328 }
329
330 /* Subroutine of maybe_begin_member_template_processing.
331    Push the template parms in PARMS, starting from LEVELS steps into the
332    chain, and ending at the beginning, since template parms are listed
333    innermost first.  */
334
335 static void
336 push_inline_template_parms_recursive (tree parmlist, int levels)
337 {
338   tree parms = TREE_VALUE (parmlist);
339   int i;
340
341   if (levels > 1)
342     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
343
344   ++processing_template_decl;
345   current_template_parms
346     = tree_cons (size_int (processing_template_decl),
347                  parms, current_template_parms);
348   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
349
350   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
351                NULL);
352   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
353     {
354       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
355       gcc_assert (DECL_P (parm));
356
357       switch (TREE_CODE (parm))
358         {
359         case TYPE_DECL:
360         case TEMPLATE_DECL:
361           pushdecl (parm);
362           break;
363
364         case PARM_DECL:
365           {
366             /* Make a CONST_DECL as is done in process_template_parm.
367                It is ugly that we recreate this here; the original
368                version built in process_template_parm is no longer
369                available.  */
370             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
371                                     TREE_TYPE (parm));
372             DECL_ARTIFICIAL (decl) = 1;
373             TREE_CONSTANT (decl) = 1;
374             TREE_INVARIANT (decl) = 1;
375             TREE_READONLY (decl) = 1;
376             DECL_INITIAL (decl) = DECL_INITIAL (parm);
377             SET_DECL_TEMPLATE_PARM_P (decl);
378             pushdecl (decl);
379           }
380           break;
381
382         default:
383           gcc_unreachable ();
384         }
385     }
386 }
387
388 /* Restore the template parameter context for a member template or
389    a friend template defined in a class definition.  */
390
391 void
392 maybe_begin_member_template_processing (tree decl)
393 {
394   tree parms;
395   int levels = 0;
396
397   if (inline_needs_template_parms (decl))
398     {
399       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
400       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
401
402       if (DECL_TEMPLATE_SPECIALIZATION (decl))
403         {
404           --levels;
405           parms = TREE_CHAIN (parms);
406         }
407
408       push_inline_template_parms_recursive (parms, levels);
409     }
410
411   /* Remember how many levels of template parameters we pushed so that
412      we can pop them later.  */
413   if (!inline_parm_levels)
414     VARRAY_INT_INIT (inline_parm_levels, 4, "inline_parm_levels");
415   if (inline_parm_levels_used == inline_parm_levels->num_elements)
416     VARRAY_GROW (inline_parm_levels, 2 * inline_parm_levels_used);
417   VARRAY_INT (inline_parm_levels, inline_parm_levels_used) = levels;
418   ++inline_parm_levels_used;
419 }
420
421 /* Undo the effects of maybe_begin_member_template_processing.  */
422
423 void
424 maybe_end_member_template_processing (void)
425 {
426   int i;
427
428   if (!inline_parm_levels_used)
429     return;
430
431   --inline_parm_levels_used;
432   for (i = 0;
433        i < VARRAY_INT (inline_parm_levels, inline_parm_levels_used);
434        ++i)
435     {
436       --processing_template_decl;
437       current_template_parms = TREE_CHAIN (current_template_parms);
438       poplevel (0, 0, 0);
439     }
440 }
441
442 /* Return a new template argument vector which contains all of ARGS,
443    but has as its innermost set of arguments the EXTRA_ARGS.  */
444
445 static tree
446 add_to_template_args (tree args, tree extra_args)
447 {
448   tree new_args;
449   int extra_depth;
450   int i;
451   int j;
452
453   extra_depth = TMPL_ARGS_DEPTH (extra_args);
454   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
455
456   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
457     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
458
459   for (j = 1; j <= extra_depth; ++j, ++i)
460     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
461
462   return new_args;
463 }
464
465 /* Like add_to_template_args, but only the outermost ARGS are added to
466    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
467    (EXTRA_ARGS) levels are added.  This function is used to combine
468    the template arguments from a partial instantiation with the
469    template arguments used to attain the full instantiation from the
470    partial instantiation.  */
471
472 static tree
473 add_outermost_template_args (tree args, tree extra_args)
474 {
475   tree new_args;
476
477   /* If there are more levels of EXTRA_ARGS than there are ARGS,
478      something very fishy is going on.  */
479   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
480
481   /* If *all* the new arguments will be the EXTRA_ARGS, just return
482      them.  */
483   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
484     return extra_args;
485
486   /* For the moment, we make ARGS look like it contains fewer levels.  */
487   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
488
489   new_args = add_to_template_args (args, extra_args);
490
491   /* Now, we restore ARGS to its full dimensions.  */
492   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
493
494   return new_args;
495 }
496
497 /* Return the N levels of innermost template arguments from the ARGS.  */
498
499 tree
500 get_innermost_template_args (tree args, int n)
501 {
502   tree new_args;
503   int extra_levels;
504   int i;
505
506   gcc_assert (n >= 0);
507
508   /* If N is 1, just return the innermost set of template arguments.  */
509   if (n == 1)
510     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
511
512   /* If we're not removing anything, just return the arguments we were
513      given.  */
514   extra_levels = TMPL_ARGS_DEPTH (args) - n;
515   gcc_assert (extra_levels >= 0);
516   if (extra_levels == 0)
517     return args;
518
519   /* Make a new set of arguments, not containing the outer arguments.  */
520   new_args = make_tree_vec (n);
521   for (i = 1; i <= n; ++i)
522     SET_TMPL_ARGS_LEVEL (new_args, i,
523                          TMPL_ARGS_LEVEL (args, i + extra_levels));
524
525   return new_args;
526 }
527
528 /* We've got a template header coming up; push to a new level for storing
529    the parms.  */
530
531 void
532 begin_template_parm_list (void)
533 {
534   /* We use a non-tag-transparent scope here, which causes pushtag to
535      put tags in this scope, rather than in the enclosing class or
536      namespace scope.  This is the right thing, since we want
537      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
538      global template class, push_template_decl handles putting the
539      TEMPLATE_DECL into top-level scope.  For a nested template class,
540      e.g.:
541
542        template <class T> struct S1 {
543          template <class T> struct S2 {};
544        };
545
546      pushtag contains special code to call pushdecl_with_scope on the
547      TEMPLATE_DECL for S2.  */
548   begin_scope (sk_template_parms, NULL);
549   ++processing_template_decl;
550   ++processing_template_parmlist;
551   note_template_header (0);
552 }
553
554 /* This routine is called when a specialization is declared.  If it is
555    invalid to declare a specialization here, an error is reported.  */
556
557 static void
558 check_specialization_scope (void)
559 {
560   tree scope = current_scope ();
561
562   /* [temp.expl.spec]
563
564      An explicit specialization shall be declared in the namespace of
565      which the template is a member, or, for member templates, in the
566      namespace of which the enclosing class or enclosing class
567      template is a member.  An explicit specialization of a member
568      function, member class or static data member of a class template
569      shall be declared in the namespace of which the class template
570      is a member.  */
571   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
572     error ("explicit specialization in non-namespace scope %qD", scope);
573
574   /* [temp.expl.spec]
575
576      In an explicit specialization declaration for a member of a class
577      template or a member template that appears in namespace scope,
578      the member template and some of its enclosing class templates may
579      remain unspecialized, except that the declaration shall not
580      explicitly specialize a class member template if its enclosing
581      class templates are not explicitly specialized as well.  */
582   if (current_template_parms)
583     error ("enclosing class templates are not explicitly specialized");
584 }
585
586 /* We've just seen template <>.  */
587
588 void
589 begin_specialization (void)
590 {
591   begin_scope (sk_template_spec, NULL);
592   note_template_header (1);
593   check_specialization_scope ();
594 }
595
596 /* Called at then end of processing a declaration preceded by
597    template<>.  */
598
599 void
600 end_specialization (void)
601 {
602   finish_scope ();
603   reset_specialization ();
604 }
605
606 /* Any template <>'s that we have seen thus far are not referring to a
607    function specialization.  */
608
609 void
610 reset_specialization (void)
611 {
612   processing_specialization = 0;
613   template_header_count = 0;
614 }
615
616 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
617    it was of the form template <>.  */
618
619 static void
620 note_template_header (int specialization)
621 {
622   processing_specialization = specialization;
623   template_header_count++;
624 }
625
626 /* We're beginning an explicit instantiation.  */
627
628 void
629 begin_explicit_instantiation (void)
630 {
631   gcc_assert (!processing_explicit_instantiation);
632   processing_explicit_instantiation = true;
633 }
634
635
636 void
637 end_explicit_instantiation (void)
638 {
639   gcc_assert (processing_explicit_instantiation);
640   processing_explicit_instantiation = false;
641 }
642
643 /* An explicit specialization or partial specialization TMPL is being
644    declared.  Check that the namespace in which the specialization is
645    occurring is permissible.  Returns false iff it is invalid to
646    specialize TMPL in the current namespace.  */
647
648 static bool
649 check_specialization_namespace (tree tmpl)
650 {
651   tree tpl_ns = decl_namespace_context (tmpl);
652
653   /* [tmpl.expl.spec]
654
655      An explicit specialization shall be declared in the namespace of
656      which the template is a member, or, for member templates, in the
657      namespace of which the enclosing class or enclosing class
658      template is a member.  An explicit specialization of a member
659      function, member class or static data member of a class template
660      shall be declared in the namespace of which the class template is
661      a member.  */
662   if (is_associated_namespace (current_namespace, tpl_ns))
663     /* Same or super-using namespace.  */
664     return true;
665   else
666     {
667       pedwarn ("specialization of %qD in different namespace", tmpl);
668       pedwarn ("  from definition of %q+#D", tmpl);
669       return false;
670     }
671 }
672
673 /* SPEC is an explicit instantiation.  Check that it is valid to
674    perform this explicit instantiation in the current namespace.  */
675
676 static void
677 check_explicit_instantiation_namespace (tree spec)
678 {
679   tree ns;
680
681   /* DR 275: An explicit instantiation shall appear in an enclosing
682      namespace of its template.  */ 
683   ns = decl_namespace_context (spec);
684   if (!is_ancestor (current_namespace, ns))
685     pedwarn ("explicit instantiation of %qD in namespace %qD "
686              "(which does not enclose namespace %qD)",
687              spec, current_namespace, ns);
688 }
689
690 /* The TYPE is being declared.  If it is a template type, that means it
691    is a partial specialization.  Do appropriate error-checking.  */
692
693 tree
694 maybe_process_partial_specialization (tree type)
695 {
696   tree context;
697
698   if (type == error_mark_node)
699     return error_mark_node;
700
701   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
702     {
703       error ("name of class shadows template template parameter %qD",
704              TYPE_NAME (type));
705       return error_mark_node;
706     }
707
708   context = TYPE_CONTEXT (type);
709
710   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
711     {
712       /* This is for ordinary explicit specialization and partial
713          specialization of a template class such as:
714
715            template <> class C<int>;
716
717          or:
718
719            template <class T> class C<T*>;
720
721          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
722
723       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
724           && !COMPLETE_TYPE_P (type))
725         {
726           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
727           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
728           if (processing_template_decl)
729             push_template_decl (TYPE_MAIN_DECL (type));
730         }
731       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
732         error ("specialization of %qT after instantiation", type);
733     }
734   else if (CLASS_TYPE_P (type)
735            && !CLASSTYPE_USE_TEMPLATE (type)
736            && CLASSTYPE_TEMPLATE_INFO (type)
737            && context && CLASS_TYPE_P (context)
738            && CLASSTYPE_TEMPLATE_INFO (context))
739     {
740       /* This is for an explicit specialization of member class
741          template according to [temp.expl.spec/18]:
742
743            template <> template <class U> class C<int>::D;
744
745          The context `C<int>' must be an implicit instantiation.
746          Otherwise this is just a member class template declared
747          earlier like:
748
749            template <> class C<int> { template <class U> class D; };
750            template <> template <class U> class C<int>::D;
751
752          In the first case, `C<int>::D' is a specialization of `C<T>::D'
753          while in the second case, `C<int>::D' is a primary template
754          and `C<T>::D' may not exist.  */
755
756       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
757           && !COMPLETE_TYPE_P (type))
758         {
759           tree t;
760
761           if (current_namespace
762               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
763             {
764               pedwarn ("specializing %q#T in different namespace", type);
765               pedwarn ("  from definition of %q+#D",
766                        CLASSTYPE_TI_TEMPLATE (type));
767             }
768
769           /* Check for invalid specialization after instantiation:
770
771                template <> template <> class C<int>::D<int>;
772                template <> template <class U> class C<int>::D;  */
773
774           for (t = DECL_TEMPLATE_INSTANTIATIONS
775                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
776                t; t = TREE_CHAIN (t))
777             if (TREE_VALUE (t) != type
778                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
779               error ("specialization %qT after instantiation %qT",
780                      type, TREE_VALUE (t));
781
782           /* Mark TYPE as a specialization.  And as a result, we only
783              have one level of template argument for the innermost
784              class template.  */
785           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
786           CLASSTYPE_TI_ARGS (type)
787             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
788         }
789     }
790   else if (processing_specialization)
791     {
792       error ("explicit specialization of non-template %qT", type);
793       return error_mark_node;
794     }
795
796   return type;
797 }
798
799 /* Returns nonzero if we can optimize the retrieval of specializations
800    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
801    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
802
803 static inline bool
804 optimize_specialization_lookup_p (tree tmpl)
805 {
806   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
807           && DECL_CLASS_SCOPE_P (tmpl)
808           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
809              parameter.  */
810           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
811           /* The optimized lookup depends on the fact that the
812              template arguments for the member function template apply
813              purely to the containing class, which is not true if the
814              containing class is an explicit or partial
815              specialization.  */
816           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
817           && !DECL_MEMBER_TEMPLATE_P (tmpl)
818           && !DECL_CONV_FN_P (tmpl)
819           /* It is possible to have a template that is not a member
820              template and is not a member of a template class:
821
822              template <typename T>
823              struct S { friend A::f(); };
824
825              Here, the friend function is a template, but the context does
826              not have template information.  The optimized lookup relies
827              on having ARGS be the template arguments for both the class
828              and the function template.  */
829           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
830 }
831
832 /* Retrieve the specialization (in the sense of [temp.spec] - a
833    specialization is either an instantiation or an explicit
834    specialization) of TMPL for the given template ARGS.  If there is
835    no such specialization, return NULL_TREE.  The ARGS are a vector of
836    arguments, or a vector of vectors of arguments, in the case of
837    templates with more than one level of parameters.
838
839    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
840    then we search for a partial specialization matching ARGS.  This
841    parameter is ignored if TMPL is not a class template.  */
842
843 static tree
844 retrieve_specialization (tree tmpl, tree args,
845                          bool class_specializations_p)
846 {
847   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
848
849   /* There should be as many levels of arguments as there are
850      levels of parameters.  */
851   gcc_assert (TMPL_ARGS_DEPTH (args)
852               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
853
854   if (optimize_specialization_lookup_p (tmpl))
855     {
856       tree class_template;
857       tree class_specialization;
858       VEC(tree,gc) *methods;
859       tree fns;
860       int idx;
861
862       /* The template arguments actually apply to the containing
863          class.  Find the class specialization with those
864          arguments.  */
865       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
866       class_specialization
867         = retrieve_specialization (class_template, args,
868                                    /*class_specializations_p=*/false);
869       if (!class_specialization)
870         return NULL_TREE;
871       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
872          for the specialization.  */
873       idx = class_method_index_for_fn (class_specialization, tmpl);
874       if (idx == -1)
875         return NULL_TREE;
876       /* Iterate through the methods with the indicated name, looking
877          for the one that has an instance of TMPL.  */
878       methods = CLASSTYPE_METHOD_VEC (class_specialization);
879       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
880         {
881           tree fn = OVL_CURRENT (fns);
882           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
883             return fn;
884         }
885       return NULL_TREE;
886     }
887   else
888     {
889       tree *sp;
890       tree *head;
891
892       /* Class templates store their instantiations on the
893          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
894          DECL_TEMPLATE_SPECIALIZATIONS list.  */
895       if (!class_specializations_p
896           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL)
897         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
898       else
899         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
900       head = sp;
901       /* Iterate through the list until we find a matching template.  */
902       while (*sp != NULL_TREE)
903         {
904           tree spec = *sp;
905
906           if (comp_template_args (TREE_PURPOSE (spec), args))
907             {
908               /* Use the move-to-front heuristic to speed up future
909                  searches.  */
910               if (spec != *head)
911                 {
912                   *sp = TREE_CHAIN (*sp);
913                   TREE_CHAIN (spec) = *head;
914                   *head = spec;
915                 }
916               return TREE_VALUE (spec);
917             }
918           sp = &TREE_CHAIN (spec);
919         }
920     }
921
922   return NULL_TREE;
923 }
924
925 /* Like retrieve_specialization, but for local declarations.  */
926
927 static tree
928 retrieve_local_specialization (tree tmpl)
929 {
930   tree spec = htab_find_with_hash (local_specializations, tmpl,
931                                    htab_hash_pointer (tmpl));
932   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
933 }
934
935 /* Returns nonzero iff DECL is a specialization of TMPL.  */
936
937 int
938 is_specialization_of (tree decl, tree tmpl)
939 {
940   tree t;
941
942   if (TREE_CODE (decl) == FUNCTION_DECL)
943     {
944       for (t = decl;
945            t != NULL_TREE;
946            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
947         if (t == tmpl)
948           return 1;
949     }
950   else
951     {
952       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
953
954       for (t = TREE_TYPE (decl);
955            t != NULL_TREE;
956            t = CLASSTYPE_USE_TEMPLATE (t)
957              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
958         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
959           return 1;
960     }
961
962   return 0;
963 }
964
965 /* Returns nonzero iff DECL is a specialization of friend declaration
966    FRIEND according to [temp.friend].  */
967
968 bool
969 is_specialization_of_friend (tree decl, tree friend)
970 {
971   bool need_template = true;
972   int template_depth;
973
974   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
975               || TREE_CODE (decl) == TYPE_DECL);
976
977   /* For [temp.friend/6] when FRIEND is an ordinary member function
978      of a template class, we want to check if DECL is a specialization
979      if this.  */
980   if (TREE_CODE (friend) == FUNCTION_DECL
981       && DECL_TEMPLATE_INFO (friend)
982       && !DECL_USE_TEMPLATE (friend))
983     {
984       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
985       friend = DECL_TI_TEMPLATE (friend);
986       need_template = false;
987     }
988   else if (TREE_CODE (friend) == TEMPLATE_DECL
989            && !PRIMARY_TEMPLATE_P (friend))
990     need_template = false;
991
992   /* There is nothing to do if this is not a template friend.  */
993   if (TREE_CODE (friend) != TEMPLATE_DECL)
994     return false;
995
996   if (is_specialization_of (decl, friend))
997     return true;
998
999   /* [temp.friend/6]
1000      A member of a class template may be declared to be a friend of a
1001      non-template class.  In this case, the corresponding member of
1002      every specialization of the class template is a friend of the
1003      class granting friendship.
1004
1005      For example, given a template friend declaration
1006
1007        template <class T> friend void A<T>::f();
1008
1009      the member function below is considered a friend
1010
1011        template <> struct A<int> {
1012          void f();
1013        };
1014
1015      For this type of template friend, TEMPLATE_DEPTH below will be
1016      nonzero.  To determine if DECL is a friend of FRIEND, we first
1017      check if the enclosing class is a specialization of another.  */
1018
1019   template_depth = template_class_depth (DECL_CONTEXT (friend));
1020   if (template_depth
1021       && DECL_CLASS_SCOPE_P (decl)
1022       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1023                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1024     {
1025       /* Next, we check the members themselves.  In order to handle
1026          a few tricky cases, such as when FRIEND's are
1027
1028            template <class T> friend void A<T>::g(T t);
1029            template <class T> template <T t> friend void A<T>::h();
1030
1031          and DECL's are
1032
1033            void A<int>::g(int);
1034            template <int> void A<int>::h();
1035
1036          we need to figure out ARGS, the template arguments from
1037          the context of DECL.  This is required for template substitution
1038          of `T' in the function parameter of `g' and template parameter
1039          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1040
1041       tree context = DECL_CONTEXT (decl);
1042       tree args = NULL_TREE;
1043       int current_depth = 0;
1044
1045       while (current_depth < template_depth)
1046         {
1047           if (CLASSTYPE_TEMPLATE_INFO (context))
1048             {
1049               if (current_depth == 0)
1050                 args = TYPE_TI_ARGS (context);
1051               else
1052                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1053               current_depth++;
1054             }
1055           context = TYPE_CONTEXT (context);
1056         }
1057
1058       if (TREE_CODE (decl) == FUNCTION_DECL)
1059         {
1060           bool is_template;
1061           tree friend_type;
1062           tree decl_type;
1063           tree friend_args_type;
1064           tree decl_args_type;
1065
1066           /* Make sure that both DECL and FRIEND are templates or
1067              non-templates.  */
1068           is_template = DECL_TEMPLATE_INFO (decl)
1069                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1070           if (need_template ^ is_template)
1071             return false;
1072           else if (is_template)
1073             {
1074               /* If both are templates, check template parameter list.  */
1075               tree friend_parms
1076                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1077                                          args, tf_none);
1078               if (!comp_template_parms
1079                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1080                       friend_parms))
1081                 return false;
1082
1083               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1084             }
1085           else
1086             decl_type = TREE_TYPE (decl);
1087
1088           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1089                                               tf_none, NULL_TREE);
1090           if (friend_type == error_mark_node)
1091             return false;
1092
1093           /* Check if return types match.  */
1094           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1095             return false;
1096
1097           /* Check if function parameter types match, ignoring the
1098              `this' parameter.  */
1099           friend_args_type = TYPE_ARG_TYPES (friend_type);
1100           decl_args_type = TYPE_ARG_TYPES (decl_type);
1101           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1102             friend_args_type = TREE_CHAIN (friend_args_type);
1103           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1104             decl_args_type = TREE_CHAIN (decl_args_type);
1105
1106           return compparms (decl_args_type, friend_args_type);
1107         }
1108       else
1109         {
1110           /* DECL is a TYPE_DECL */
1111           bool is_template;
1112           tree decl_type = TREE_TYPE (decl);
1113
1114           /* Make sure that both DECL and FRIEND are templates or
1115              non-templates.  */
1116           is_template
1117             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1118               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1119
1120           if (need_template ^ is_template)
1121             return false;
1122           else if (is_template)
1123             {
1124               tree friend_parms;
1125               /* If both are templates, check the name of the two
1126                  TEMPLATE_DECL's first because is_friend didn't.  */
1127               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1128                   != DECL_NAME (friend))
1129                 return false;
1130
1131               /* Now check template parameter list.  */
1132               friend_parms
1133                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1134                                          args, tf_none);
1135               return comp_template_parms
1136                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1137                  friend_parms);
1138             }
1139           else
1140             return (DECL_NAME (decl)
1141                     == DECL_NAME (friend));
1142         }
1143     }
1144   return false;
1145 }
1146
1147 /* Register the specialization SPEC as a specialization of TMPL with
1148    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1149    is actually just a friend declaration.  Returns SPEC, or an
1150    equivalent prior declaration, if available.  */
1151
1152 static tree
1153 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1154 {
1155   tree fn;
1156
1157   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1158
1159   if (TREE_CODE (spec) == FUNCTION_DECL
1160       && uses_template_parms (DECL_TI_ARGS (spec)))
1161     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1162        register it; we want the corresponding TEMPLATE_DECL instead.
1163        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1164        the more obvious `uses_template_parms (spec)' to avoid problems
1165        with default function arguments.  In particular, given
1166        something like this:
1167
1168           template <class T> void f(T t1, T t = T())
1169
1170        the default argument expression is not substituted for in an
1171        instantiation unless and until it is actually needed.  */
1172     return spec;
1173
1174   fn = retrieve_specialization (tmpl, args,
1175                                 /*class_specializations_p=*/false);
1176   /* We can sometimes try to re-register a specialization that we've
1177      already got.  In particular, regenerate_decl_from_template calls
1178      duplicate_decls which will update the specialization list.  But,
1179      we'll still get called again here anyhow.  It's more convenient
1180      to simply allow this than to try to prevent it.  */
1181   if (fn == spec)
1182     return spec;
1183   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1184     {
1185       if (DECL_TEMPLATE_INSTANTIATION (fn))
1186         {
1187           if (TREE_USED (fn)
1188               || DECL_EXPLICIT_INSTANTIATION (fn))
1189             {
1190               error ("specialization of %qD after instantiation",
1191                      fn);
1192               return error_mark_node;
1193             }
1194           else
1195             {
1196               tree clone;
1197               /* This situation should occur only if the first
1198                  specialization is an implicit instantiation, the
1199                  second is an explicit specialization, and the
1200                  implicit instantiation has not yet been used.  That
1201                  situation can occur if we have implicitly
1202                  instantiated a member function and then specialized
1203                  it later.
1204
1205                  We can also wind up here if a friend declaration that
1206                  looked like an instantiation turns out to be a
1207                  specialization:
1208
1209                    template <class T> void foo(T);
1210                    class S { friend void foo<>(int) };
1211                    template <> void foo(int);
1212
1213                  We transform the existing DECL in place so that any
1214                  pointers to it become pointers to the updated
1215                  declaration.
1216
1217                  If there was a definition for the template, but not
1218                  for the specialization, we want this to look as if
1219                  there were no definition, and vice versa.  */
1220               DECL_INITIAL (fn) = NULL_TREE;
1221               duplicate_decls (spec, fn, is_friend);
1222               /* The call to duplicate_decls will have applied
1223                  [temp.expl.spec]: 
1224
1225                    An explicit specialization of a function template
1226                    is inline only if it is explicitly declared to be,
1227                    and independently of whether its function tempalte
1228                    is.
1229
1230                 to the primary function; now copy the inline bits to
1231                 the various clones.  */   
1232               FOR_EACH_CLONE (clone, fn)
1233                 {
1234                   DECL_DECLARED_INLINE_P (clone)
1235                     = DECL_DECLARED_INLINE_P (fn);
1236                   DECL_INLINE (clone)
1237                     = DECL_INLINE (fn);
1238                 }
1239               check_specialization_namespace (fn);
1240
1241               return fn;
1242             }
1243         }
1244       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1245         {
1246           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1247             /* Dup decl failed, but this is a new definition. Set the
1248                line number so any errors match this new
1249                definition.  */
1250             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1251
1252           return fn;
1253         }
1254     }
1255
1256   /* A specialization must be declared in the same namespace as the
1257      template it is specializing.  */
1258   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1259       && !check_specialization_namespace (tmpl))
1260     DECL_CONTEXT (spec) = decl_namespace_context (tmpl);
1261
1262   if (!optimize_specialization_lookup_p (tmpl))
1263     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1264       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1265
1266   return spec;
1267 }
1268
1269 /* Unregister the specialization SPEC as a specialization of TMPL.
1270    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1271    if the SPEC was listed as a specialization of TMPL.  */
1272
1273 bool
1274 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1275 {
1276   tree* s;
1277
1278   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1279        *s != NULL_TREE;
1280        s = &TREE_CHAIN (*s))
1281     if (TREE_VALUE (*s) == spec)
1282       {
1283         if (!new_spec)
1284           *s = TREE_CHAIN (*s);
1285         else
1286           TREE_VALUE (*s) = new_spec;
1287         return 1;
1288       }
1289
1290   return 0;
1291 }
1292
1293 /* Compare an entry in the local specializations hash table P1 (which
1294    is really a pointer to a TREE_LIST) with P2 (which is really a
1295    DECL).  */
1296
1297 static int
1298 eq_local_specializations (const void *p1, const void *p2)
1299 {
1300   return TREE_VALUE ((tree) p1) == (tree) p2;
1301 }
1302
1303 /* Hash P1, an entry in the local specializations table.  */
1304
1305 static hashval_t
1306 hash_local_specialization (const void* p1)
1307 {
1308   return htab_hash_pointer (TREE_VALUE ((tree) p1));
1309 }
1310
1311 /* Like register_specialization, but for local declarations.  We are
1312    registering SPEC, an instantiation of TMPL.  */
1313
1314 static void
1315 register_local_specialization (tree spec, tree tmpl)
1316 {
1317   void **slot;
1318
1319   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1320                                    htab_hash_pointer (tmpl), INSERT);
1321   *slot = build_tree_list (spec, tmpl);
1322 }
1323
1324 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1325    specialized class.  */
1326
1327 bool
1328 explicit_class_specialization_p (tree type)
1329 {
1330   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1331     return false;
1332   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1333 }
1334
1335 /* Print the list of candidate FNS in an error message.  */
1336
1337 void
1338 print_candidates (tree fns)
1339 {
1340   tree fn;
1341
1342   const char *str = "candidates are:";
1343
1344   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1345     {
1346       tree f;
1347
1348       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1349         error ("%s %+#D", str, OVL_CURRENT (f));
1350       str = "               ";
1351     }
1352 }
1353
1354 /* Returns the template (one of the functions given by TEMPLATE_ID)
1355    which can be specialized to match the indicated DECL with the
1356    explicit template args given in TEMPLATE_ID.  The DECL may be
1357    NULL_TREE if none is available.  In that case, the functions in
1358    TEMPLATE_ID are non-members.
1359
1360    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1361    specialization of a member template.
1362
1363    The TEMPLATE_COUNT is the number of references to qualifying
1364    template classes that appeared in the name of the function. See
1365    check_explicit_specialization for a more accurate description.
1366
1367    TSK indicates what kind of template declaration (if any) is being
1368    declared.  TSK_TEMPLATE indicates that the declaration given by
1369    DECL, though a FUNCTION_DECL, has template parameters, and is
1370    therefore a template function.
1371
1372    The template args (those explicitly specified and those deduced)
1373    are output in a newly created vector *TARGS_OUT.
1374
1375    If it is impossible to determine the result, an error message is
1376    issued.  The error_mark_node is returned to indicate failure.  */
1377
1378 static tree
1379 determine_specialization (tree template_id,
1380                           tree decl,
1381                           tree* targs_out,
1382                           int need_member_template,
1383                           int template_count,
1384                           tmpl_spec_kind tsk)
1385 {
1386   tree fns;
1387   tree targs;
1388   tree explicit_targs;
1389   tree candidates = NULL_TREE;
1390   tree templates = NULL_TREE;
1391   int header_count;
1392   struct cp_binding_level *b;
1393
1394   *targs_out = NULL_TREE;
1395
1396   if (template_id == error_mark_node)
1397     return error_mark_node;
1398
1399   fns = TREE_OPERAND (template_id, 0);
1400   explicit_targs = TREE_OPERAND (template_id, 1);
1401
1402   if (fns == error_mark_node)
1403     return error_mark_node;
1404
1405   /* Check for baselinks.  */
1406   if (BASELINK_P (fns))
1407     fns = BASELINK_FUNCTIONS (fns);
1408
1409   if (!is_overloaded_fn (fns))
1410     {
1411       error ("%qD is not a function template", fns);
1412       return error_mark_node;
1413     }
1414
1415   /* Count the number of template headers specified for this
1416      specialization.  */
1417   header_count = 0;
1418   for (b = current_binding_level;
1419        b->kind == sk_template_parms;
1420        b = b->level_chain)
1421     ++header_count;
1422
1423   for (; fns; fns = OVL_NEXT (fns))
1424     {
1425       tree fn = OVL_CURRENT (fns);
1426
1427       if (TREE_CODE (fn) == TEMPLATE_DECL)
1428         {
1429           tree decl_arg_types;
1430           tree fn_arg_types;
1431
1432           /* DECL might be a specialization of FN.  */
1433
1434           /* Adjust the type of DECL in case FN is a static member.  */
1435           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1436           if (DECL_STATIC_FUNCTION_P (fn)
1437               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1438             decl_arg_types = TREE_CHAIN (decl_arg_types);
1439
1440           /* Check that the number of function parameters matches.
1441              For example,
1442                template <class T> void f(int i = 0);
1443                template <> void f<int>();
1444              The specialization f<int> is invalid but is not caught
1445              by get_bindings below.  */
1446
1447           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1448           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1449             continue;
1450
1451           /* For a non-static member function, we need to make sure that
1452              the const qualification is the same. This can be done by
1453              checking the 'this' in the argument list.  */
1454           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1455               && !same_type_p (TREE_VALUE (fn_arg_types),
1456                                TREE_VALUE (decl_arg_types)))
1457             continue;
1458
1459           /* In case of explicit specialization, we need to check if
1460              the number of template headers appearing in the specialization
1461              is correct. This is usually done in check_explicit_specialization,
1462              but the check done there cannot be exhaustive when specializing
1463              member functions. Consider the following code:
1464
1465              template <> void A<int>::f(int);
1466              template <> template <> void A<int>::f(int);
1467
1468              Assuming that A<int> is not itself an explicit specialization
1469              already, the first line specializes "f" which is a non-template
1470              member function, whilst the second line specializes "f" which
1471              is a template member function. So both lines are syntactically
1472              correct, and check_explicit_specialization does not reject
1473              them.
1474
1475              Here, we can do better, as we are matching the specialization
1476              against the declarations. We count the number of template
1477              headers, and we check if they match TEMPLATE_COUNT + 1
1478              (TEMPLATE_COUNT is the number of qualifying template classes,
1479              plus there must be another header for the member template
1480              itself).
1481
1482              Notice that if header_count is zero, this is not a
1483              specialization but rather a template instantiation, so there
1484              is no check we can perform here.  */
1485           if (header_count && header_count != template_count + 1)
1486             continue;
1487
1488           /* Check that the number of template arguments at the
1489              innermost level for DECL is the same as for FN.  */
1490           if (current_binding_level->kind == sk_template_parms
1491               && !current_binding_level->explicit_spec_p
1492               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1493                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS 
1494                                       (current_template_parms))))
1495             continue;
1496
1497           /* Function templates cannot be specializations; there are
1498              no partial specializations of functions.  Therefore, if
1499              the type of DECL does not match FN, there is no
1500              match.  */
1501           if (tsk == tsk_template)
1502             {
1503               if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1504                              decl_arg_types))
1505                 candidates = tree_cons (NULL_TREE, fn, candidates);
1506               continue;
1507             }
1508
1509           /* See whether this function might be a specialization of this
1510              template.  */
1511           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1512
1513           if (!targs)
1514             /* We cannot deduce template arguments that when used to
1515                specialize TMPL will produce DECL.  */
1516             continue;
1517
1518           /* Save this template, and the arguments deduced.  */
1519           templates = tree_cons (targs, fn, templates);
1520         }
1521       else if (need_member_template)
1522         /* FN is an ordinary member function, and we need a
1523            specialization of a member template.  */
1524         ;
1525       else if (TREE_CODE (fn) != FUNCTION_DECL)
1526         /* We can get IDENTIFIER_NODEs here in certain erroneous
1527            cases.  */
1528         ;
1529       else if (!DECL_FUNCTION_MEMBER_P (fn))
1530         /* This is just an ordinary non-member function.  Nothing can
1531            be a specialization of that.  */
1532         ;
1533       else if (DECL_ARTIFICIAL (fn))
1534         /* Cannot specialize functions that are created implicitly.  */
1535         ;
1536       else
1537         {
1538           tree decl_arg_types;
1539
1540           /* This is an ordinary member function.  However, since
1541              we're here, we can assume it's enclosing class is a
1542              template class.  For example,
1543
1544                template <typename T> struct S { void f(); };
1545                template <> void S<int>::f() {}
1546
1547              Here, S<int>::f is a non-template, but S<int> is a
1548              template class.  If FN has the same type as DECL, we
1549              might be in business.  */
1550
1551           if (!DECL_TEMPLATE_INFO (fn))
1552             /* Its enclosing class is an explicit specialization
1553                of a template class.  This is not a candidate.  */
1554             continue;
1555
1556           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1557                             TREE_TYPE (TREE_TYPE (fn))))
1558             /* The return types differ.  */
1559             continue;
1560
1561           /* Adjust the type of DECL in case FN is a static member.  */
1562           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1563           if (DECL_STATIC_FUNCTION_P (fn)
1564               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1565             decl_arg_types = TREE_CHAIN (decl_arg_types);
1566
1567           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1568                          decl_arg_types))
1569             /* They match!  */
1570             candidates = tree_cons (NULL_TREE, fn, candidates);
1571         }
1572     }
1573
1574   if (templates && TREE_CHAIN (templates))
1575     {
1576       /* We have:
1577
1578            [temp.expl.spec]
1579
1580            It is possible for a specialization with a given function
1581            signature to be instantiated from more than one function
1582            template.  In such cases, explicit specification of the
1583            template arguments must be used to uniquely identify the
1584            function template specialization being specialized.
1585
1586          Note that here, there's no suggestion that we're supposed to
1587          determine which of the candidate templates is most
1588          specialized.  However, we, also have:
1589
1590            [temp.func.order]
1591
1592            Partial ordering of overloaded function template
1593            declarations is used in the following contexts to select
1594            the function template to which a function template
1595            specialization refers:
1596
1597            -- when an explicit specialization refers to a function
1598               template.
1599
1600          So, we do use the partial ordering rules, at least for now.
1601          This extension can only serve to make invalid programs valid,
1602          so it's safe.  And, there is strong anecdotal evidence that
1603          the committee intended the partial ordering rules to apply;
1604          the EDG front-end has that behavior, and John Spicer claims
1605          that the committee simply forgot to delete the wording in
1606          [temp.expl.spec].  */
1607      tree tmpl = most_specialized (templates, decl, explicit_targs);
1608      if (tmpl && tmpl != error_mark_node)
1609        {
1610          targs = get_bindings (tmpl, decl, explicit_targs, /*check_ret=*/true);
1611          templates = tree_cons (targs, tmpl, NULL_TREE);
1612        }
1613     }
1614
1615   if (templates == NULL_TREE && candidates == NULL_TREE)
1616     {
1617       error ("template-id %qD for %q+D does not match any template "
1618              "declaration", template_id, decl);
1619       return error_mark_node;
1620     }
1621   else if ((templates && TREE_CHAIN (templates))
1622            || (candidates && TREE_CHAIN (candidates))
1623            || (templates && candidates))
1624     {
1625       error ("ambiguous template specialization %qD for %q+D",
1626              template_id, decl);
1627       chainon (candidates, templates);
1628       print_candidates (candidates);
1629       return error_mark_node;
1630     }
1631
1632   /* We have one, and exactly one, match.  */
1633   if (candidates)
1634     {
1635       tree fn = TREE_VALUE (candidates);
1636       /* DECL is a re-declaration of a template function.  */
1637       if (TREE_CODE (fn) == TEMPLATE_DECL)
1638         return fn;
1639       /* It was a specialization of an ordinary member function in a
1640          template class.  */
1641       *targs_out = copy_node (DECL_TI_ARGS (fn));
1642       return DECL_TI_TEMPLATE (fn);
1643     }
1644
1645   /* It was a specialization of a template.  */
1646   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1647   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1648     {
1649       *targs_out = copy_node (targs);
1650       SET_TMPL_ARGS_LEVEL (*targs_out,
1651                            TMPL_ARGS_DEPTH (*targs_out),
1652                            TREE_PURPOSE (templates));
1653     }
1654   else
1655     *targs_out = TREE_PURPOSE (templates);
1656   return TREE_VALUE (templates);
1657 }
1658
1659 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1660    but with the default argument values filled in from those in the
1661    TMPL_TYPES.  */
1662
1663 static tree
1664 copy_default_args_to_explicit_spec_1 (tree spec_types,
1665                                       tree tmpl_types)
1666 {
1667   tree new_spec_types;
1668
1669   if (!spec_types)
1670     return NULL_TREE;
1671
1672   if (spec_types == void_list_node)
1673     return void_list_node;
1674
1675   /* Substitute into the rest of the list.  */
1676   new_spec_types =
1677     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1678                                           TREE_CHAIN (tmpl_types));
1679
1680   /* Add the default argument for this parameter.  */
1681   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1682                          TREE_VALUE (spec_types),
1683                          new_spec_types);
1684 }
1685
1686 /* DECL is an explicit specialization.  Replicate default arguments
1687    from the template it specializes.  (That way, code like:
1688
1689      template <class T> void f(T = 3);
1690      template <> void f(double);
1691      void g () { f (); }
1692
1693    works, as required.)  An alternative approach would be to look up
1694    the correct default arguments at the call-site, but this approach
1695    is consistent with how implicit instantiations are handled.  */
1696
1697 static void
1698 copy_default_args_to_explicit_spec (tree decl)
1699 {
1700   tree tmpl;
1701   tree spec_types;
1702   tree tmpl_types;
1703   tree new_spec_types;
1704   tree old_type;
1705   tree new_type;
1706   tree t;
1707   tree object_type = NULL_TREE;
1708   tree in_charge = NULL_TREE;
1709   tree vtt = NULL_TREE;
1710
1711   /* See if there's anything we need to do.  */
1712   tmpl = DECL_TI_TEMPLATE (decl);
1713   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1714   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1715     if (TREE_PURPOSE (t))
1716       break;
1717   if (!t)
1718     return;
1719
1720   old_type = TREE_TYPE (decl);
1721   spec_types = TYPE_ARG_TYPES (old_type);
1722
1723   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1724     {
1725       /* Remove the this pointer, but remember the object's type for
1726          CV quals.  */
1727       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1728       spec_types = TREE_CHAIN (spec_types);
1729       tmpl_types = TREE_CHAIN (tmpl_types);
1730
1731       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1732         {
1733           /* DECL may contain more parameters than TMPL due to the extra
1734              in-charge parameter in constructors and destructors.  */
1735           in_charge = spec_types;
1736           spec_types = TREE_CHAIN (spec_types);
1737         }
1738       if (DECL_HAS_VTT_PARM_P (decl))
1739         {
1740           vtt = spec_types;
1741           spec_types = TREE_CHAIN (spec_types);
1742         }
1743     }
1744
1745   /* Compute the merged default arguments.  */
1746   new_spec_types =
1747     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1748
1749   /* Compute the new FUNCTION_TYPE.  */
1750   if (object_type)
1751     {
1752       if (vtt)
1753         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1754                                          TREE_VALUE (vtt),
1755                                          new_spec_types);
1756
1757       if (in_charge)
1758         /* Put the in-charge parameter back.  */
1759         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1760                                          TREE_VALUE (in_charge),
1761                                          new_spec_types);
1762
1763       new_type = build_method_type_directly (object_type,
1764                                              TREE_TYPE (old_type),
1765                                              new_spec_types);
1766     }
1767   else
1768     new_type = build_function_type (TREE_TYPE (old_type),
1769                                     new_spec_types);
1770   new_type = cp_build_type_attribute_variant (new_type,
1771                                               TYPE_ATTRIBUTES (old_type));
1772   new_type = build_exception_variant (new_type,
1773                                       TYPE_RAISES_EXCEPTIONS (old_type));
1774   TREE_TYPE (decl) = new_type;
1775 }
1776
1777 /* Check to see if the function just declared, as indicated in
1778    DECLARATOR, and in DECL, is a specialization of a function
1779    template.  We may also discover that the declaration is an explicit
1780    instantiation at this point.
1781
1782    Returns DECL, or an equivalent declaration that should be used
1783    instead if all goes well.  Issues an error message if something is
1784    amiss.  Returns error_mark_node if the error is not easily
1785    recoverable.
1786
1787    FLAGS is a bitmask consisting of the following flags:
1788
1789    2: The function has a definition.
1790    4: The function is a friend.
1791
1792    The TEMPLATE_COUNT is the number of references to qualifying
1793    template classes that appeared in the name of the function.  For
1794    example, in
1795
1796      template <class T> struct S { void f(); };
1797      void S<int>::f();
1798
1799    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1800    classes are not counted in the TEMPLATE_COUNT, so that in
1801
1802      template <class T> struct S {};
1803      template <> struct S<int> { void f(); }
1804      template <> void S<int>::f();
1805
1806    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1807    invalid; there should be no template <>.)
1808
1809    If the function is a specialization, it is marked as such via
1810    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1811    is set up correctly, and it is added to the list of specializations
1812    for that template.  */
1813
1814 tree
1815 check_explicit_specialization (tree declarator,
1816                                tree decl,
1817                                int template_count,
1818                                int flags)
1819 {
1820   int have_def = flags & 2;
1821   int is_friend = flags & 4;
1822   int specialization = 0;
1823   int explicit_instantiation = 0;
1824   int member_specialization = 0;
1825   tree ctype = DECL_CLASS_CONTEXT (decl);
1826   tree dname = DECL_NAME (decl);
1827   tmpl_spec_kind tsk;
1828
1829   if (is_friend)
1830     {
1831       if (!processing_specialization)
1832         tsk = tsk_none;
1833       else
1834         tsk = tsk_excessive_parms;
1835     }
1836   else
1837     tsk = current_tmpl_spec_kind (template_count);
1838
1839   switch (tsk)
1840     {
1841     case tsk_none:
1842       if (processing_specialization)
1843         {
1844           specialization = 1;
1845           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1846         }
1847       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1848         {
1849           if (is_friend)
1850             /* This could be something like:
1851
1852                template <class T> void f(T);
1853                class S { friend void f<>(int); }  */
1854             specialization = 1;
1855           else
1856             {
1857               /* This case handles bogus declarations like template <>
1858                  template <class T> void f<int>(); */
1859
1860               error ("template-id %qD in declaration of primary template",
1861                      declarator);
1862               return decl;
1863             }
1864         }
1865       break;
1866
1867     case tsk_invalid_member_spec:
1868       /* The error has already been reported in
1869          check_specialization_scope.  */
1870       return error_mark_node;
1871
1872     case tsk_invalid_expl_inst:
1873       error ("template parameter list used in explicit instantiation");
1874
1875       /* Fall through.  */
1876
1877     case tsk_expl_inst:
1878       if (have_def)
1879         error ("definition provided for explicit instantiation");
1880
1881       explicit_instantiation = 1;
1882       break;
1883
1884     case tsk_excessive_parms:
1885     case tsk_insufficient_parms:
1886       if (tsk == tsk_excessive_parms)
1887         error ("too many template parameter lists in declaration of %qD",
1888                decl);
1889       else if (template_header_count)
1890         error("too few template parameter lists in declaration of %qD", decl);
1891       else
1892         error("explicit specialization of %qD must be introduced by "
1893               "%<template <>%>", decl);
1894
1895       /* Fall through.  */
1896     case tsk_expl_spec:
1897       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1898       if (ctype)
1899         member_specialization = 1;
1900       else
1901         specialization = 1;
1902       break;
1903
1904     case tsk_template:
1905       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1906         {
1907           /* This case handles bogus declarations like template <>
1908              template <class T> void f<int>(); */
1909
1910           if (uses_template_parms (declarator))
1911             error ("function template partial specialization %qD "
1912                    "is not allowed", declarator);
1913           else
1914             error ("template-id %qD in declaration of primary template",
1915                    declarator);
1916           return decl;
1917         }
1918
1919       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1920         /* This is a specialization of a member template, without
1921            specialization the containing class.  Something like:
1922
1923              template <class T> struct S {
1924                template <class U> void f (U);
1925              };
1926              template <> template <class U> void S<int>::f(U) {}
1927
1928            That's a specialization -- but of the entire template.  */
1929         specialization = 1;
1930       break;
1931
1932     default:
1933       gcc_unreachable ();
1934     }
1935
1936   if (specialization || member_specialization)
1937     {
1938       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1939       for (; t; t = TREE_CHAIN (t))
1940         if (TREE_PURPOSE (t))
1941           {
1942             pedwarn
1943               ("default argument specified in explicit specialization");
1944             break;
1945           }
1946     }
1947
1948   if (specialization || member_specialization || explicit_instantiation)
1949     {
1950       tree tmpl = NULL_TREE;
1951       tree targs = NULL_TREE;
1952
1953       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1954       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
1955         {
1956           tree fns;
1957
1958           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
1959           if (ctype)
1960             fns = dname;
1961           else
1962             {
1963               /* If there is no class context, the explicit instantiation
1964                  must be at namespace scope.  */
1965               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
1966
1967               /* Find the namespace binding, using the declaration
1968                  context.  */
1969               fns = namespace_binding (dname, CP_DECL_CONTEXT (decl));
1970               if (!fns || !is_overloaded_fn (fns))
1971                 {
1972                   error ("%qD is not a template function", dname);
1973                   fns = error_mark_node;
1974                 }
1975             }
1976
1977           declarator = lookup_template_function (fns, NULL_TREE);
1978         }
1979
1980       if (declarator == error_mark_node)
1981         return error_mark_node;
1982
1983       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
1984         {
1985           if (!explicit_instantiation)
1986             /* A specialization in class scope.  This is invalid,
1987                but the error will already have been flagged by
1988                check_specialization_scope.  */
1989             return error_mark_node;
1990           else
1991             {
1992               /* It's not valid to write an explicit instantiation in
1993                  class scope, e.g.:
1994
1995                    class C { template void f(); }
1996
1997                    This case is caught by the parser.  However, on
1998                    something like:
1999
2000                    template class C { void f(); };
2001
2002                    (which is invalid) we can get here.  The error will be
2003                    issued later.  */
2004               ;
2005             }
2006
2007           return decl;
2008         }
2009       else if (ctype != NULL_TREE
2010                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2011                    IDENTIFIER_NODE))
2012         {
2013           /* Find the list of functions in ctype that have the same
2014              name as the declared function.  */
2015           tree name = TREE_OPERAND (declarator, 0);
2016           tree fns = NULL_TREE;
2017           int idx;
2018
2019           if (constructor_name_p (name, ctype))
2020             {
2021               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2022
2023               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
2024                   : !CLASSTYPE_DESTRUCTORS (ctype))
2025                 {
2026                   /* From [temp.expl.spec]:
2027
2028                      If such an explicit specialization for the member
2029                      of a class template names an implicitly-declared
2030                      special member function (clause _special_), the
2031                      program is ill-formed.
2032
2033                      Similar language is found in [temp.explicit].  */
2034                   error ("specialization of implicitly-declared special member function");
2035                   return error_mark_node;
2036                 }
2037
2038               name = is_constructor ? ctor_identifier : dtor_identifier;
2039             }
2040
2041           if (!DECL_CONV_FN_P (decl))
2042             {
2043               idx = lookup_fnfields_1 (ctype, name);
2044               if (idx >= 0)
2045                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2046             }
2047           else
2048             {
2049               VEC(tree,gc) *methods;
2050               tree ovl;
2051
2052               /* For a type-conversion operator, we cannot do a
2053                  name-based lookup.  We might be looking for `operator
2054                  int' which will be a specialization of `operator T'.
2055                  So, we find *all* the conversion operators, and then
2056                  select from them.  */
2057               fns = NULL_TREE;
2058
2059               methods = CLASSTYPE_METHOD_VEC (ctype);
2060               if (methods)
2061                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2062                      VEC_iterate (tree, methods, idx, ovl);
2063                      ++idx)
2064                   {
2065                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2066                       /* There are no more conversion functions.  */
2067                       break;
2068
2069                     /* Glue all these conversion functions together
2070                        with those we already have.  */
2071                     for (; ovl; ovl = OVL_NEXT (ovl))
2072                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2073                   }
2074             }
2075
2076           if (fns == NULL_TREE)
2077             {
2078               error ("no member function %qD declared in %qT", name, ctype);
2079               return error_mark_node;
2080             }
2081           else
2082             TREE_OPERAND (declarator, 0) = fns;
2083         }
2084
2085       /* Figure out what exactly is being specialized at this point.
2086          Note that for an explicit instantiation, even one for a
2087          member function, we cannot tell apriori whether the
2088          instantiation is for a member template, or just a member
2089          function of a template class.  Even if a member template is
2090          being instantiated, the member template arguments may be
2091          elided if they can be deduced from the rest of the
2092          declaration.  */
2093       tmpl = determine_specialization (declarator, decl,
2094                                        &targs,
2095                                        member_specialization,
2096                                        template_count,
2097                                        tsk);
2098
2099       if (!tmpl || tmpl == error_mark_node)
2100         /* We couldn't figure out what this declaration was
2101            specializing.  */
2102         return error_mark_node;
2103       else
2104         {
2105           tree gen_tmpl = most_general_template (tmpl);
2106
2107           if (explicit_instantiation)
2108             {
2109               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2110                  is done by do_decl_instantiation later.  */
2111
2112               int arg_depth = TMPL_ARGS_DEPTH (targs);
2113               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2114
2115               if (arg_depth > parm_depth)
2116                 {
2117                   /* If TMPL is not the most general template (for
2118                      example, if TMPL is a friend template that is
2119                      injected into namespace scope), then there will
2120                      be too many levels of TARGS.  Remove some of them
2121                      here.  */
2122                   int i;
2123                   tree new_targs;
2124
2125                   new_targs = make_tree_vec (parm_depth);
2126                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2127                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2128                       = TREE_VEC_ELT (targs, i);
2129                   targs = new_targs;
2130                 }
2131
2132               return instantiate_template (tmpl, targs, tf_error);
2133             }
2134
2135           /* If we thought that the DECL was a member function, but it
2136              turns out to be specializing a static member function,
2137              make DECL a static member function as well.  */
2138           if (DECL_STATIC_FUNCTION_P (tmpl)
2139               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2140             revert_static_member_fn (decl);
2141
2142           /* If this is a specialization of a member template of a
2143              template class, we want to return the TEMPLATE_DECL, not
2144              the specialization of it.  */
2145           if (tsk == tsk_template)
2146             {
2147               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2148               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2149               if (have_def)
2150                 {
2151                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2152                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2153                     = DECL_SOURCE_LOCATION (decl);
2154                   /* We want to use the argument list specified in the
2155                      definition, not in the original declaration.  */
2156                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2157                     = DECL_ARGUMENTS (decl);
2158                 }
2159               return tmpl;
2160             }
2161
2162           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2163           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2164
2165           /* Inherit default function arguments from the template
2166              DECL is specializing.  */
2167           copy_default_args_to_explicit_spec (decl);
2168
2169           /* This specialization has the same protection as the
2170              template it specializes.  */
2171           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2172           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2173           /* The specialization has the same visibility as the
2174              template it specializes.  */
2175           if (DECL_VISIBILITY_SPECIFIED (gen_tmpl))
2176             {
2177               DECL_VISIBILITY_SPECIFIED (decl) = 1;
2178               DECL_VISIBILITY (decl) = DECL_VISIBILITY (gen_tmpl);
2179             }
2180           /* If DECL is a friend declaration, declared using an
2181              unqualified name, the namespace associated with DECL may
2182              have been set incorrectly.  For example, in:
2183              
2184                template <typename T> void f(T); 
2185                namespace N {
2186                  struct S { friend void f<int>(int); }
2187                }
2188
2189              we will have set the DECL_CONTEXT for the friend
2190              declaration to N, rather than to the global namespace.  */
2191           if (DECL_NAMESPACE_SCOPE_P (decl))
2192             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2193
2194           if (is_friend && !have_def)
2195             /* This is not really a declaration of a specialization.
2196                It's just the name of an instantiation.  But, it's not
2197                a request for an instantiation, either.  */
2198             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2199           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2200             /* This is indeed a specialization.  In case of constructors
2201                and destructors, we need in-charge and not-in-charge
2202                versions in V3 ABI.  */
2203             clone_function_decl (decl, /*update_method_vec_p=*/0);
2204
2205           /* Register this specialization so that we can find it
2206              again.  */
2207           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2208         }
2209     }
2210
2211   return decl;
2212 }
2213
2214 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2215    parameters.  These are represented in the same format used for
2216    DECL_TEMPLATE_PARMS.  */
2217
2218 int
2219 comp_template_parms (tree parms1, tree parms2)
2220 {
2221   tree p1;
2222   tree p2;
2223
2224   if (parms1 == parms2)
2225     return 1;
2226
2227   for (p1 = parms1, p2 = parms2;
2228        p1 != NULL_TREE && p2 != NULL_TREE;
2229        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2230     {
2231       tree t1 = TREE_VALUE (p1);
2232       tree t2 = TREE_VALUE (p2);
2233       int i;
2234
2235       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2236       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2237
2238       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2239         return 0;
2240
2241       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2242         {
2243           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2244           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2245
2246           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2247             return 0;
2248
2249           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM)
2250             continue;
2251           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2252             return 0;
2253         }
2254     }
2255
2256   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2257     /* One set of parameters has more parameters lists than the
2258        other.  */
2259     return 0;
2260
2261   return 1;
2262 }
2263
2264 /* Complain if DECL shadows a template parameter.
2265
2266    [temp.local]: A template-parameter shall not be redeclared within its
2267    scope (including nested scopes).  */
2268
2269 void
2270 check_template_shadow (tree decl)
2271 {
2272   tree olddecl;
2273
2274   /* If we're not in a template, we can't possibly shadow a template
2275      parameter.  */
2276   if (!current_template_parms)
2277     return;
2278
2279   /* Figure out what we're shadowing.  */
2280   if (TREE_CODE (decl) == OVERLOAD)
2281     decl = OVL_CURRENT (decl);
2282   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2283
2284   /* If there's no previous binding for this name, we're not shadowing
2285      anything, let alone a template parameter.  */
2286   if (!olddecl)
2287     return;
2288
2289   /* If we're not shadowing a template parameter, we're done.  Note
2290      that OLDDECL might be an OVERLOAD (or perhaps even an
2291      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2292      node.  */
2293   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2294     return;
2295
2296   /* We check for decl != olddecl to avoid bogus errors for using a
2297      name inside a class.  We check TPFI to avoid duplicate errors for
2298      inline member templates.  */
2299   if (decl == olddecl
2300       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2301     return;
2302
2303   error ("declaration of %q+#D", decl);
2304   error (" shadows template parm %q+#D", olddecl);
2305 }
2306
2307 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2308    ORIG_LEVEL, DECL, and TYPE.  */
2309
2310 static tree
2311 build_template_parm_index (int index,
2312                            int level,
2313                            int orig_level,
2314                            tree decl,
2315                            tree type)
2316 {
2317   tree t = make_node (TEMPLATE_PARM_INDEX);
2318   TEMPLATE_PARM_IDX (t) = index;
2319   TEMPLATE_PARM_LEVEL (t) = level;
2320   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2321   TEMPLATE_PARM_DECL (t) = decl;
2322   TREE_TYPE (t) = type;
2323   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2324   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2325   TREE_READONLY (t) = TREE_READONLY (decl);
2326
2327   return t;
2328 }
2329
2330 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2331    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2332    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2333    new one is created.  */
2334
2335 static tree
2336 reduce_template_parm_level (tree index, tree type, int levels)
2337 {
2338   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2339       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2340           != TEMPLATE_PARM_LEVEL (index) - levels))
2341     {
2342       tree orig_decl = TEMPLATE_PARM_DECL (index);
2343       tree decl, t;
2344
2345       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2346       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2347       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2348       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2349       DECL_ARTIFICIAL (decl) = 1;
2350       SET_DECL_TEMPLATE_PARM_P (decl);
2351
2352       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2353                                      TEMPLATE_PARM_LEVEL (index) - levels,
2354                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2355                                      decl, type);
2356       TEMPLATE_PARM_DESCENDANTS (index) = t;
2357
2358         /* Template template parameters need this.  */
2359       if (TREE_CODE (decl) != CONST_DECL)
2360         DECL_TEMPLATE_PARMS (decl)
2361           = DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
2362     }
2363
2364   return TEMPLATE_PARM_DESCENDANTS (index);
2365 }
2366
2367 /* Process information from new template parameter NEXT and append it to the
2368    LIST being built.  This new parameter is a non-type parameter iff
2369    IS_NON_TYPE is true.  */
2370
2371 tree
2372 process_template_parm (tree list, tree next, bool is_non_type)
2373 {
2374   tree parm;
2375   tree decl = 0;
2376   tree defval;
2377   int idx;
2378
2379   parm = next;
2380   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2381   defval = TREE_PURPOSE (parm);
2382
2383   if (list)
2384     {
2385       tree p = TREE_VALUE (tree_last (list));
2386
2387       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2388         idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2389       else
2390         idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2391       ++idx;
2392     }
2393   else
2394     idx = 0;
2395
2396   if (is_non_type)
2397     {
2398       parm = TREE_VALUE (parm);
2399
2400       SET_DECL_TEMPLATE_PARM_P (parm);
2401
2402       /* [temp.param]
2403
2404          The top-level cv-qualifiers on the template-parameter are
2405          ignored when determining its type.  */
2406       TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
2407
2408       /* A template parameter is not modifiable.  */
2409       TREE_CONSTANT (parm) = 1;
2410       TREE_INVARIANT (parm) = 1;
2411       TREE_READONLY (parm) = 1;
2412       if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
2413         TREE_TYPE (parm) = void_type_node;
2414       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
2415       TREE_CONSTANT (decl) = 1;
2416       TREE_INVARIANT (decl) = 1;
2417       TREE_READONLY (decl) = 1;
2418       DECL_INITIAL (parm) = DECL_INITIAL (decl)
2419         = build_template_parm_index (idx, processing_template_decl,
2420                                      processing_template_decl,
2421                                      decl, TREE_TYPE (parm));
2422     }
2423   else
2424     {
2425       tree t;
2426       parm = TREE_VALUE (TREE_VALUE (parm));
2427
2428       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
2429         {
2430           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
2431           /* This is for distinguishing between real templates and template
2432              template parameters */
2433           TREE_TYPE (parm) = t;
2434           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
2435           decl = parm;
2436         }
2437       else
2438         {
2439           t = make_aggr_type (TEMPLATE_TYPE_PARM);
2440           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
2441           decl = build_decl (TYPE_DECL, parm, t);
2442         }
2443
2444       TYPE_NAME (t) = decl;
2445       TYPE_STUB_DECL (t) = decl;
2446       parm = decl;
2447       TEMPLATE_TYPE_PARM_INDEX (t)
2448         = build_template_parm_index (idx, processing_template_decl,
2449                                      processing_template_decl,
2450                                      decl, TREE_TYPE (parm));
2451     }
2452   DECL_ARTIFICIAL (decl) = 1;
2453   SET_DECL_TEMPLATE_PARM_P (decl);
2454   pushdecl (decl);
2455   parm = build_tree_list (defval, parm);
2456   return chainon (list, parm);
2457 }
2458
2459 /* The end of a template parameter list has been reached.  Process the
2460    tree list into a parameter vector, converting each parameter into a more
2461    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
2462    as PARM_DECLs.  */
2463
2464 tree
2465 end_template_parm_list (tree parms)
2466 {
2467   int nparms;
2468   tree parm, next;
2469   tree saved_parmlist = make_tree_vec (list_length (parms));
2470
2471   current_template_parms
2472     = tree_cons (size_int (processing_template_decl),
2473                  saved_parmlist, current_template_parms);
2474
2475   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
2476     {
2477       next = TREE_CHAIN (parm);
2478       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
2479       TREE_CHAIN (parm) = NULL_TREE;
2480     }
2481
2482   --processing_template_parmlist;
2483
2484   return saved_parmlist;
2485 }
2486
2487 /* end_template_decl is called after a template declaration is seen.  */
2488
2489 void
2490 end_template_decl (void)
2491 {
2492   reset_specialization ();
2493
2494   if (! processing_template_decl)
2495     return;
2496
2497   /* This matches the pushlevel in begin_template_parm_list.  */
2498   finish_scope ();
2499
2500   --processing_template_decl;
2501   current_template_parms = TREE_CHAIN (current_template_parms);
2502 }
2503
2504 /* Given a template argument vector containing the template PARMS.
2505    The innermost PARMS are given first.  */
2506
2507 tree
2508 current_template_args (void)
2509 {
2510   tree header;
2511   tree args = NULL_TREE;
2512   int length = TMPL_PARMS_DEPTH (current_template_parms);
2513   int l = length;
2514
2515   /* If there is only one level of template parameters, we do not
2516      create a TREE_VEC of TREE_VECs.  Instead, we return a single
2517      TREE_VEC containing the arguments.  */
2518   if (length > 1)
2519     args = make_tree_vec (length);
2520
2521   for (header = current_template_parms; header; header = TREE_CHAIN (header))
2522     {
2523       tree a = copy_node (TREE_VALUE (header));
2524       int i;
2525
2526       TREE_TYPE (a) = NULL_TREE;
2527       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
2528         {
2529           tree t = TREE_VEC_ELT (a, i);
2530
2531           /* T will be a list if we are called from within a
2532              begin/end_template_parm_list pair, but a vector directly
2533              if within a begin/end_member_template_processing pair.  */
2534           if (TREE_CODE (t) == TREE_LIST)
2535             {
2536               t = TREE_VALUE (t);
2537
2538               if (TREE_CODE (t) == TYPE_DECL
2539                   || TREE_CODE (t) == TEMPLATE_DECL)
2540                 t = TREE_TYPE (t);
2541               else
2542                 t = DECL_INITIAL (t);
2543               TREE_VEC_ELT (a, i) = t;
2544             }
2545         }
2546
2547       if (length > 1)
2548         TREE_VEC_ELT (args, --l) = a;
2549       else
2550         args = a;
2551     }
2552
2553   return args;
2554 }
2555
2556 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
2557    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
2558    a member template.  Used by push_template_decl below.  */
2559
2560 static tree
2561 build_template_decl (tree decl, tree parms, bool member_template_p)
2562 {
2563   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
2564   DECL_TEMPLATE_PARMS (tmpl) = parms;
2565   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
2566   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
2567   if (DECL_LANG_SPECIFIC (decl))
2568     {
2569       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
2570       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
2571       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
2572       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
2573       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
2574       if (DECL_OVERLOADED_OPERATOR_P (decl))
2575         SET_OVERLOADED_OPERATOR_CODE (tmpl,
2576                                       DECL_OVERLOADED_OPERATOR_P (decl));
2577     }
2578
2579   return tmpl;
2580 }
2581
2582 struct template_parm_data
2583 {
2584   /* The level of the template parameters we are currently
2585      processing.  */
2586   int level;
2587
2588   /* The index of the specialization argument we are currently
2589      processing.  */
2590   int current_arg;
2591
2592   /* An array whose size is the number of template parameters.  The
2593      elements are nonzero if the parameter has been used in any one
2594      of the arguments processed so far.  */
2595   int* parms;
2596
2597   /* An array whose size is the number of template arguments.  The
2598      elements are nonzero if the argument makes use of template
2599      parameters of this level.  */
2600   int* arg_uses_template_parms;
2601 };
2602
2603 /* Subroutine of push_template_decl used to see if each template
2604    parameter in a partial specialization is used in the explicit
2605    argument list.  If T is of the LEVEL given in DATA (which is
2606    treated as a template_parm_data*), then DATA->PARMS is marked
2607    appropriately.  */
2608
2609 static int
2610 mark_template_parm (tree t, void* data)
2611 {
2612   int level;
2613   int idx;
2614   struct template_parm_data* tpd = (struct template_parm_data*) data;
2615
2616   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2617     {
2618       level = TEMPLATE_PARM_LEVEL (t);
2619       idx = TEMPLATE_PARM_IDX (t);
2620     }
2621   else
2622     {
2623       level = TEMPLATE_TYPE_LEVEL (t);
2624       idx = TEMPLATE_TYPE_IDX (t);
2625     }
2626
2627   if (level == tpd->level)
2628     {
2629       tpd->parms[idx] = 1;
2630       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
2631     }
2632
2633   /* Return zero so that for_each_template_parm will continue the
2634      traversal of the tree; we want to mark *every* template parm.  */
2635   return 0;
2636 }
2637
2638 /* Process the partial specialization DECL.  */
2639
2640 static tree
2641 process_partial_specialization (tree decl)
2642 {
2643   tree type = TREE_TYPE (decl);
2644   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
2645   tree specargs = CLASSTYPE_TI_ARGS (type);
2646   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
2647   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
2648   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
2649   int nargs = TREE_VEC_LENGTH (inner_args);
2650   int ntparms = TREE_VEC_LENGTH (inner_parms);
2651   int  i;
2652   int did_error_intro = 0;
2653   struct template_parm_data tpd;
2654   struct template_parm_data tpd2;
2655
2656   /* We check that each of the template parameters given in the
2657      partial specialization is used in the argument list to the
2658      specialization.  For example:
2659
2660        template <class T> struct S;
2661        template <class T> struct S<T*>;
2662
2663      The second declaration is OK because `T*' uses the template
2664      parameter T, whereas
2665
2666        template <class T> struct S<int>;
2667
2668      is no good.  Even trickier is:
2669
2670        template <class T>
2671        struct S1
2672        {
2673           template <class U>
2674           struct S2;
2675           template <class U>
2676           struct S2<T>;
2677        };
2678
2679      The S2<T> declaration is actually invalid; it is a
2680      full-specialization.  Of course,
2681
2682           template <class U>
2683           struct S2<T (*)(U)>;
2684
2685      or some such would have been OK.  */
2686   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
2687   tpd.parms = alloca (sizeof (int) * ntparms);
2688   memset (tpd.parms, 0, sizeof (int) * ntparms);
2689
2690   tpd.arg_uses_template_parms = alloca (sizeof (int) * nargs);
2691   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
2692   for (i = 0; i < nargs; ++i)
2693     {
2694       tpd.current_arg = i;
2695       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
2696                               &mark_template_parm,
2697                               &tpd,
2698                               NULL);
2699     }
2700   for (i = 0; i < ntparms; ++i)
2701     if (tpd.parms[i] == 0)
2702       {
2703         /* One of the template parms was not used in the
2704            specialization.  */
2705         if (!did_error_intro)
2706           {
2707             error ("template parameters not used in partial specialization:");
2708             did_error_intro = 1;
2709           }
2710
2711         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
2712       }
2713
2714   /* [temp.class.spec]
2715
2716      The argument list of the specialization shall not be identical to
2717      the implicit argument list of the primary template.  */
2718   if (comp_template_args
2719       (inner_args,
2720        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
2721                                                    (maintmpl)))))
2722     error ("partial specialization %qT does not specialize any template arguments", type);
2723
2724   /* [temp.class.spec]
2725
2726      A partially specialized non-type argument expression shall not
2727      involve template parameters of the partial specialization except
2728      when the argument expression is a simple identifier.
2729
2730      The type of a template parameter corresponding to a specialized
2731      non-type argument shall not be dependent on a parameter of the
2732      specialization.  */
2733   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
2734   tpd2.parms = 0;
2735   for (i = 0; i < nargs; ++i)
2736     {
2737       tree arg = TREE_VEC_ELT (inner_args, i);
2738       if (/* These first two lines are the `non-type' bit.  */
2739           !TYPE_P (arg)
2740           && TREE_CODE (arg) != TEMPLATE_DECL
2741           /* This next line is the `argument expression is not just a
2742              simple identifier' condition and also the `specialized
2743              non-type argument' bit.  */
2744           && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
2745         {
2746           if (tpd.arg_uses_template_parms[i])
2747             error ("template argument %qE involves template parameter(s)", arg);
2748           else
2749             {
2750               /* Look at the corresponding template parameter,
2751                  marking which template parameters its type depends
2752                  upon.  */
2753               tree type =
2754                 TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (main_inner_parms,
2755                                                      i)));
2756
2757               if (!tpd2.parms)
2758                 {
2759                   /* We haven't yet initialized TPD2.  Do so now.  */
2760                   tpd2.arg_uses_template_parms
2761                     = alloca (sizeof (int) * nargs);
2762                   /* The number of parameters here is the number in the
2763                      main template, which, as checked in the assertion
2764                      above, is NARGS.  */
2765                   tpd2.parms = alloca (sizeof (int) * nargs);
2766                   tpd2.level =
2767                     TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
2768                 }
2769
2770               /* Mark the template parameters.  But this time, we're
2771                  looking for the template parameters of the main
2772                  template, not in the specialization.  */
2773               tpd2.current_arg = i;
2774               tpd2.arg_uses_template_parms[i] = 0;
2775               memset (tpd2.parms, 0, sizeof (int) * nargs);
2776               for_each_template_parm (type,
2777                                       &mark_template_parm,
2778                                       &tpd2,
2779                                       NULL);
2780
2781               if (tpd2.arg_uses_template_parms [i])
2782                 {
2783                   /* The type depended on some template parameters.
2784                      If they are fully specialized in the
2785                      specialization, that's OK.  */
2786                   int j;
2787                   for (j = 0; j < nargs; ++j)
2788                     if (tpd2.parms[j] != 0
2789                         && tpd.arg_uses_template_parms [j])
2790                       {
2791                         error ("type %qT of template argument %qE depends "
2792                                "on template parameter(s)",
2793                                type,
2794                                arg);
2795                         break;
2796                       }
2797                 }
2798             }
2799         }
2800     }
2801
2802   if (retrieve_specialization (maintmpl, specargs,
2803                                /*class_specializations_p=*/true))
2804     /* We've already got this specialization.  */
2805     return decl;
2806
2807   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
2808     = tree_cons (specargs, inner_parms,
2809                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
2810   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
2811   return decl;
2812 }
2813
2814 /* Check that a template declaration's use of default arguments is not
2815    invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
2816    nonzero if DECL is the thing declared by a primary template.
2817    IS_PARTIAL is nonzero if DECL is a partial specialization.  */
2818
2819 static void
2820 check_default_tmpl_args (tree decl, tree parms, int is_primary, int is_partial)
2821 {
2822   const char *msg;
2823   int last_level_to_check;
2824   tree parm_level;
2825
2826   /* [temp.param]
2827
2828      A default template-argument shall not be specified in a
2829      function template declaration or a function template definition, nor
2830      in the template-parameter-list of the definition of a member of a
2831      class template.  */
2832
2833   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
2834     /* You can't have a function template declaration in a local
2835        scope, nor you can you define a member of a class template in a
2836        local scope.  */
2837     return;
2838
2839   if (current_class_type
2840       && !TYPE_BEING_DEFINED (current_class_type)
2841       && DECL_LANG_SPECIFIC (decl)
2842       /* If this is either a friend defined in the scope of the class
2843          or a member function.  */
2844       && (DECL_FUNCTION_MEMBER_P (decl)
2845           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
2846           : DECL_FRIEND_CONTEXT (decl)
2847           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
2848           : false)
2849       /* And, if it was a member function, it really was defined in
2850          the scope of the class.  */
2851       && (!DECL_FUNCTION_MEMBER_P (decl)
2852           || DECL_INITIALIZED_IN_CLASS_P (decl)))
2853     /* We already checked these parameters when the template was
2854        declared, so there's no need to do it again now.  This function
2855        was defined in class scope, but we're processing it's body now
2856        that the class is complete.  */
2857     return;
2858
2859   /* [temp.param]
2860
2861      If a template-parameter has a default template-argument, all
2862      subsequent template-parameters shall have a default
2863      template-argument supplied.  */
2864   for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
2865     {
2866       tree inner_parms = TREE_VALUE (parm_level);
2867       int ntparms = TREE_VEC_LENGTH (inner_parms);
2868       int seen_def_arg_p = 0;
2869       int i;
2870
2871       for (i = 0; i < ntparms; ++i)
2872         {
2873           tree parm = TREE_VEC_ELT (inner_parms, i);
2874
2875           if (TREE_PURPOSE (parm))
2876             seen_def_arg_p = 1;
2877           else if (seen_def_arg_p)
2878             {
2879               error ("no default argument for %qD", TREE_VALUE (parm));
2880               /* For better subsequent error-recovery, we indicate that
2881                  there should have been a default argument.  */
2882               TREE_PURPOSE (parm) = error_mark_node;
2883             }
2884         }
2885     }
2886
2887   if (TREE_CODE (decl) != TYPE_DECL || is_partial || !is_primary)
2888     /* For an ordinary class template, default template arguments are
2889        allowed at the innermost level, e.g.:
2890          template <class T = int>
2891          struct S {};
2892        but, in a partial specialization, they're not allowed even
2893        there, as we have in [temp.class.spec]:
2894
2895          The template parameter list of a specialization shall not
2896          contain default template argument values.
2897
2898        So, for a partial specialization, or for a function template,
2899        we look at all of them.  */
2900     ;
2901   else
2902     /* But, for a primary class template that is not a partial
2903        specialization we look at all template parameters except the
2904        innermost ones.  */
2905     parms = TREE_CHAIN (parms);
2906
2907   /* Figure out what error message to issue.  */
2908   if (TREE_CODE (decl) == FUNCTION_DECL)
2909     msg = "default template arguments may not be used in function templates";
2910   else if (is_partial)
2911     msg = "default template arguments may not be used in partial specializations";
2912   else
2913     msg = "default argument for template parameter for class enclosing %qD";
2914
2915   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
2916     /* If we're inside a class definition, there's no need to
2917        examine the parameters to the class itself.  On the one
2918        hand, they will be checked when the class is defined, and,
2919        on the other, default arguments are valid in things like:
2920          template <class T = double>
2921          struct S { template <class U> void f(U); };
2922        Here the default argument for `S' has no bearing on the
2923        declaration of `f'.  */
2924     last_level_to_check = template_class_depth (current_class_type) + 1;
2925   else
2926     /* Check everything.  */
2927     last_level_to_check = 0;
2928
2929   for (parm_level = parms;
2930        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
2931        parm_level = TREE_CHAIN (parm_level))
2932     {
2933       tree inner_parms = TREE_VALUE (parm_level);
2934       int i;
2935       int ntparms;
2936
2937       ntparms = TREE_VEC_LENGTH (inner_parms);
2938       for (i = 0; i < ntparms; ++i)
2939         {
2940           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
2941             {
2942               if (msg)
2943                 {
2944                   error (msg, decl);
2945                   msg = 0;
2946                 }
2947
2948               /* Clear out the default argument so that we are not
2949                  confused later.  */
2950               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
2951             }
2952         }
2953
2954       /* At this point, if we're still interested in issuing messages,
2955          they must apply to classes surrounding the object declared.  */
2956       if (msg)
2957         msg = "default argument for template parameter for class enclosing %qD";
2958     }
2959 }
2960
2961 /* Worker for push_template_decl_real, called via
2962    for_each_template_parm.  DATA is really an int, indicating the
2963    level of the parameters we are interested in.  If T is a template
2964    parameter of that level, return nonzero.  */
2965
2966 static int
2967 template_parm_this_level_p (tree t, void* data)
2968 {
2969   int this_level = *(int *)data;
2970   int level;
2971
2972   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2973     level = TEMPLATE_PARM_LEVEL (t);
2974   else
2975     level = TEMPLATE_TYPE_LEVEL (t);
2976   return level == this_level;
2977 }
2978
2979 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
2980    parameters given by current_template_args, or reuses a
2981    previously existing one, if appropriate.  Returns the DECL, or an
2982    equivalent one, if it is replaced via a call to duplicate_decls.
2983
2984    If IS_FRIEND is true, DECL is a friend declaration.  */
2985
2986 tree
2987 push_template_decl_real (tree decl, bool is_friend)
2988 {
2989   tree tmpl;
2990   tree args;
2991   tree info;
2992   tree ctx;
2993   int primary;
2994   int is_partial;
2995   int new_template_p = 0;
2996   /* True if the template is a member template, in the sense of
2997      [temp.mem].  */
2998   bool member_template_p = false;
2999
3000   if (decl == error_mark_node)
3001     return decl;
3002
3003   /* See if this is a partial specialization.  */
3004   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3005                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3006                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3007
3008   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3009     is_friend = true;
3010
3011   if (is_friend)
3012     /* For a friend, we want the context of the friend function, not
3013        the type of which it is a friend.  */
3014     ctx = DECL_CONTEXT (decl);
3015   else if (CP_DECL_CONTEXT (decl)
3016            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3017     /* In the case of a virtual function, we want the class in which
3018        it is defined.  */
3019     ctx = CP_DECL_CONTEXT (decl);
3020   else
3021     /* Otherwise, if we're currently defining some class, the DECL
3022        is assumed to be a member of the class.  */
3023     ctx = current_scope ();
3024
3025   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3026     ctx = NULL_TREE;
3027
3028   if (!DECL_CONTEXT (decl))
3029     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3030
3031   /* See if this is a primary template.  */
3032   if (is_friend && ctx)
3033     /* A friend template that specifies a class context, i.e.
3034          template <typename T> friend void A<T>::f();
3035        is not primary.  */
3036     primary = 0;
3037   else
3038     primary = template_parm_scope_p ();
3039
3040   if (primary)
3041     {
3042       if (DECL_CLASS_SCOPE_P (decl))
3043         member_template_p = true;
3044       if (TREE_CODE (decl) == TYPE_DECL
3045           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3046         error ("template class without a name");
3047       else if (TREE_CODE (decl) == FUNCTION_DECL)
3048         {
3049           if (DECL_DESTRUCTOR_P (decl))
3050             {
3051               /* [temp.mem]
3052
3053                  A destructor shall not be a member template.  */
3054               error ("destructor %qD declared as member template", decl);
3055               return error_mark_node;
3056             }
3057           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3058               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3059                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3060                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3061                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3062                       == void_list_node)))
3063             {
3064               /* [basic.stc.dynamic.allocation]
3065
3066                  An allocation function can be a function
3067                  template. ... Template allocation functions shall
3068                  have two or more parameters.  */
3069               error ("invalid template declaration of %qD", decl);
3070               return error_mark_node;
3071             }
3072         }
3073       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3074                && CLASS_TYPE_P (TREE_TYPE (decl)))
3075         /* OK */;
3076       else
3077         {
3078           error ("template declaration of %q#D", decl);
3079           return error_mark_node;
3080         }
3081     }
3082
3083   /* Check to see that the rules regarding the use of default
3084      arguments are not being violated.  */
3085   check_default_tmpl_args (decl, current_template_parms,
3086                            primary, is_partial);
3087
3088   if (is_partial)
3089     return process_partial_specialization (decl);
3090
3091   args = current_template_args ();
3092
3093   if (!ctx
3094       || TREE_CODE (ctx) == FUNCTION_DECL
3095       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3096       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3097     {
3098       if (DECL_LANG_SPECIFIC (decl)
3099           && DECL_TEMPLATE_INFO (decl)
3100           && DECL_TI_TEMPLATE (decl))
3101         tmpl = DECL_TI_TEMPLATE (decl);
3102       /* If DECL is a TYPE_DECL for a class-template, then there won't
3103          be DECL_LANG_SPECIFIC.  The information equivalent to
3104          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3105       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3106                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3107                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3108         {
3109           /* Since a template declaration already existed for this
3110              class-type, we must be redeclaring it here.  Make sure
3111              that the redeclaration is valid.  */
3112           redeclare_class_template (TREE_TYPE (decl),
3113                                     current_template_parms);
3114           /* We don't need to create a new TEMPLATE_DECL; just use the
3115              one we already had.  */
3116           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3117         }
3118       else
3119         {
3120           tmpl = build_template_decl (decl, current_template_parms,
3121                                       member_template_p);
3122           new_template_p = 1;
3123
3124           if (DECL_LANG_SPECIFIC (decl)
3125               && DECL_TEMPLATE_SPECIALIZATION (decl))
3126             {
3127               /* A specialization of a member template of a template
3128                  class.  */
3129               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3130               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3131               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3132             }
3133         }
3134     }
3135   else
3136     {
3137       tree a, t, current, parms;
3138       int i;
3139
3140       if (TREE_CODE (decl) == TYPE_DECL)
3141         {
3142           if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
3143                || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
3144               && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3145               && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3146             tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3147           else
3148             {
3149               error ("%qD does not declare a template type", decl);
3150               return decl;
3151             }
3152         }
3153       else if (!DECL_LANG_SPECIFIC (decl) || !DECL_TEMPLATE_INFO (decl))
3154         {
3155           error ("template definition of non-template %q#D", decl);
3156           return decl;
3157         }
3158       else
3159         tmpl = DECL_TI_TEMPLATE (decl);
3160
3161       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3162           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3163           && DECL_TEMPLATE_SPECIALIZATION (decl)
3164           && DECL_MEMBER_TEMPLATE_P (tmpl))
3165         {
3166           tree new_tmpl;
3167
3168           /* The declaration is a specialization of a member
3169              template, declared outside the class.  Therefore, the
3170              innermost template arguments will be NULL, so we
3171              replace them with the arguments determined by the
3172              earlier call to check_explicit_specialization.  */
3173           args = DECL_TI_ARGS (decl);
3174
3175           new_tmpl
3176             = build_template_decl (decl, current_template_parms,
3177                                    member_template_p);
3178           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3179           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3180           DECL_TI_TEMPLATE (decl) = new_tmpl;
3181           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3182           DECL_TEMPLATE_INFO (new_tmpl)
3183             = tree_cons (tmpl, args, NULL_TREE);
3184
3185           register_specialization (new_tmpl,
3186                                    most_general_template (tmpl),
3187                                    args,
3188                                    is_friend);
3189           return decl;
3190         }
3191
3192       /* Make sure the template headers we got make sense.  */
3193
3194       parms = DECL_TEMPLATE_PARMS (tmpl);
3195       i = TMPL_PARMS_DEPTH (parms);
3196       if (TMPL_ARGS_DEPTH (args) != i)
3197         {
3198           error ("expected %d levels of template parms for %q#D, got %d",
3199                  i, decl, TMPL_ARGS_DEPTH (args));
3200         }
3201       else
3202         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3203           {
3204             a = TMPL_ARGS_LEVEL (args, i);
3205             t = INNERMOST_TEMPLATE_PARMS (parms);
3206
3207             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3208               {
3209                 if (current == decl)
3210                   error ("got %d template parameters for %q#D",
3211                          TREE_VEC_LENGTH (a), decl);
3212                 else
3213                   error ("got %d template parameters for %q#T",
3214                          TREE_VEC_LENGTH (a), current);
3215                 error ("  but %d required", TREE_VEC_LENGTH (t));
3216                 return error_mark_node;
3217               }
3218
3219             /* Perhaps we should also check that the parms are used in the
3220                appropriate qualifying scopes in the declarator?  */
3221
3222             if (current == decl)
3223               current = ctx;
3224             else
3225               current = TYPE_CONTEXT (current);
3226           }
3227     }
3228
3229   DECL_TEMPLATE_RESULT (tmpl) = decl;
3230   TREE_TYPE (tmpl) = TREE_TYPE (decl);
3231
3232   /* Push template declarations for global functions and types.  Note
3233      that we do not try to push a global template friend declared in a
3234      template class; such a thing may well depend on the template
3235      parameters of the class.  */
3236   if (new_template_p && !ctx
3237       && !(is_friend && template_class_depth (current_class_type) > 0))
3238     {
3239       tmpl = pushdecl_namespace_level (tmpl, is_friend);
3240       if (tmpl == error_mark_node)
3241         return error_mark_node;
3242
3243       /* Hide template friend classes that haven't been declared yet.  */
3244       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
3245         {
3246           DECL_ANTICIPATED (tmpl) = 1;
3247           DECL_FRIEND_P (tmpl) = 1;
3248         }
3249     }
3250
3251   if (primary)
3252     {
3253       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
3254       if (DECL_CONV_FN_P (tmpl))
3255         {
3256           int depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3257
3258           /* It is a conversion operator. See if the type converted to
3259              depends on innermost template operands.  */
3260
3261           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
3262                                          depth))
3263             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
3264         }
3265     }
3266
3267   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
3268      back to its most general template.  If TMPL is a specialization,
3269      ARGS may only have the innermost set of arguments.  Add the missing
3270      argument levels if necessary.  */
3271   if (DECL_TEMPLATE_INFO (tmpl))
3272     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
3273
3274   info = tree_cons (tmpl, args, NULL_TREE);
3275
3276   if (DECL_IMPLICIT_TYPEDEF_P (decl))
3277     {
3278       SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
3279       if ((!ctx || TREE_CODE (ctx) != FUNCTION_DECL)
3280           && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3281           /* Don't change the name if we've already set it up.  */
3282           && !IDENTIFIER_TEMPLATE (DECL_NAME (decl)))
3283         DECL_NAME (decl) = classtype_mangled_name (TREE_TYPE (decl));
3284     }
3285   else if (DECL_LANG_SPECIFIC (decl))
3286     DECL_TEMPLATE_INFO (decl) = info;
3287
3288   return DECL_TEMPLATE_RESULT (tmpl);
3289 }
3290
3291 tree
3292 push_template_decl (tree decl)
3293 {
3294   return push_template_decl_real (decl, false);
3295 }
3296
3297 /* Called when a class template TYPE is redeclared with the indicated
3298    template PARMS, e.g.:
3299
3300      template <class T> struct S;
3301      template <class T> struct S {};  */
3302
3303 void
3304 redeclare_class_template (tree type, tree parms)
3305 {
3306   tree tmpl;
3307   tree tmpl_parms;
3308   int i;
3309
3310   if (!TYPE_TEMPLATE_INFO (type))
3311     {
3312       error ("%qT is not a template type", type);
3313       return;
3314     }
3315
3316   tmpl = TYPE_TI_TEMPLATE (type);
3317   if (!PRIMARY_TEMPLATE_P (tmpl))
3318     /* The type is nested in some template class.  Nothing to worry
3319        about here; there are no new template parameters for the nested
3320        type.  */
3321     return;
3322
3323   if (!parms)
3324     {
3325       error ("template specifiers not specified in declaration of %qD",
3326              tmpl);
3327       return;
3328     }
3329
3330   parms = INNERMOST_TEMPLATE_PARMS (parms);
3331   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
3332
3333   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
3334     {
3335       error ("previous declaration %q+D", tmpl);
3336       error ("used %d template parameter(s) instead of %d",
3337              TREE_VEC_LENGTH (tmpl_parms),
3338              TREE_VEC_LENGTH (parms));
3339       return;
3340     }
3341
3342   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
3343     {
3344       tree tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
3345       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
3346       tree tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
3347       tree parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
3348
3349       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
3350          TEMPLATE_DECL.  */
3351       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
3352           || (TREE_CODE (tmpl_parm) != TYPE_DECL
3353               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm))))
3354         {
3355           error ("template parameter %q+#D", tmpl_parm);
3356           error ("redeclared here as %q#D", parm);
3357           return;
3358         }
3359
3360       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
3361         {
3362           /* We have in [temp.param]:
3363
3364              A template-parameter may not be given default arguments
3365              by two different declarations in the same scope.  */
3366           error ("redefinition of default argument for %q#D", parm);
3367           error ("%J  original definition appeared here", tmpl_parm);
3368           return;
3369         }
3370
3371       if (parm_default != NULL_TREE)
3372         /* Update the previous template parameters (which are the ones
3373            that will really count) with the new default value.  */
3374         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
3375       else if (tmpl_default != NULL_TREE)
3376         /* Update the new parameters, too; they'll be used as the
3377            parameters for any members.  */
3378         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
3379     }
3380 }
3381
3382 /* Simplify EXPR if it is a non-dependent expression.  Returns the
3383    (possibly simplified) expression.  */
3384
3385 tree
3386 fold_non_dependent_expr (tree expr)
3387 {
3388   if (expr == NULL_TREE)
3389     return NULL_TREE;
3390
3391   /* If we're in a template, but EXPR isn't value dependent, simplify
3392      it.  We're supposed to treat:
3393
3394        template <typename T> void f(T[1 + 1]);
3395        template <typename T> void f(T[2]);
3396
3397      as two declarations of the same function, for example.  */
3398   if (processing_template_decl
3399       && !type_dependent_expression_p (expr)
3400       && !value_dependent_expression_p (expr))
3401     {
3402       HOST_WIDE_INT saved_processing_template_decl;
3403
3404       saved_processing_template_decl = processing_template_decl;
3405       processing_template_decl = 0;
3406       expr = tsubst_copy_and_build (expr,
3407                                     /*args=*/NULL_TREE,
3408                                     tf_error,
3409                                     /*in_decl=*/NULL_TREE,
3410                                     /*function_p=*/false);
3411       processing_template_decl = saved_processing_template_decl;
3412     }
3413   return expr;
3414 }
3415
3416 /* EXPR is an expression which is used in a constant-expression context.
3417    For instance, it could be a VAR_DECL with a constant initializer.
3418    Extract the innest constant expression.
3419
3420    This is basically a more powerful version of
3421    integral_constant_value, which can be used also in templates where
3422    initializers can maintain a syntactic rather than semantic form
3423    (even if they are non-dependent, for access-checking purposes).  */
3424
3425 tree
3426 fold_decl_constant_value (tree expr)
3427 {
3428   tree const_expr = expr;
3429   do
3430     {
3431       expr = fold_non_dependent_expr (const_expr);
3432       const_expr = integral_constant_value (expr);
3433     }
3434   while (expr != const_expr);
3435
3436   return expr;
3437 }
3438
3439 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
3440    must be a function or a pointer-to-function type, as specified
3441    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
3442    and check that the resulting function has external linkage.  */
3443
3444 static tree
3445 convert_nontype_argument_function (tree type, tree expr)
3446 {
3447   tree fns = expr;
3448   tree fn, fn_no_ptr;
3449
3450   fn = instantiate_type (type, fns, tf_none);
3451   if (fn == error_mark_node)
3452     return error_mark_node;
3453
3454   fn_no_ptr = fn;
3455   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
3456     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
3457
3458   /* [temp.arg.nontype]/1
3459
3460      A template-argument for a non-type, non-template template-parameter
3461      shall be one of:
3462      [...]
3463      -- the address of an object or function with external linkage.  */
3464   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
3465     {
3466       error ("%qE is not a valid template argument for type %qT "
3467              "because function %qD has not external linkage",
3468              expr, type, fn_no_ptr);
3469       return NULL_TREE;
3470     }
3471
3472   return fn;
3473 }
3474
3475 /* Attempt to convert the non-type template parameter EXPR to the
3476    indicated TYPE.  If the conversion is successful, return the
3477    converted value.  If the conversion is unsuccessful, return
3478    NULL_TREE if we issued an error message, or error_mark_node if we
3479    did not.  We issue error messages for out-and-out bad template
3480    parameters, but not simply because the conversion failed, since we
3481    might be just trying to do argument deduction.  Both TYPE and EXPR
3482    must be non-dependent.
3483
3484    The conversion follows the special rules described in
3485    [temp.arg.nontype], and it is much more strict than an implicit
3486    conversion.
3487
3488    This function is called twice for each template argument (see
3489    lookup_template_class for a more accurate description of this
3490    problem). This means that we need to handle expressions which
3491    are not valid in a C++ source, but can be created from the
3492    first call (for instance, casts to perform conversions). These
3493    hacks can go away after we fix the double coercion problem.  */
3494
3495 static tree
3496 convert_nontype_argument (tree type, tree expr)
3497 {
3498   tree expr_type;
3499
3500   /* Detect immediately string literals as invalid non-type argument.
3501      This special-case is not needed for correctness (we would easily
3502      catch this later), but only to provide better diagnostic for this
3503      common user mistake. As suggested by DR 100, we do not mention
3504      linkage issues in the diagnostic as this is not the point.  */
3505   if (TREE_CODE (expr) == STRING_CST)
3506     {
3507       error ("%qE is not a valid template argument for type %qT "
3508              "because string literals can never be used in this context",
3509              expr, type);
3510       return NULL_TREE;
3511     }
3512
3513   /* If we are in a template, EXPR may be non-dependent, but still
3514      have a syntactic, rather than semantic, form.  For example, EXPR
3515      might be a SCOPE_REF, rather than the VAR_DECL to which the
3516      SCOPE_REF refers.  Preserving the qualifying scope is necessary
3517      so that access checking can be performed when the template is
3518      instantiated -- but here we need the resolved form so that we can
3519      convert the argument.  */
3520   expr = fold_non_dependent_expr (expr);
3521   if (error_operand_p (expr))
3522     return error_mark_node;
3523   expr_type = TREE_TYPE (expr);
3524
3525   /* HACK: Due to double coercion, we can get a
3526      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
3527      which is the tree that we built on the first call (see
3528      below when coercing to reference to object or to reference to
3529      function). We just strip everything and get to the arg.
3530      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
3531      for examples.  */
3532   if (TREE_CODE (expr) == NOP_EXPR)
3533     {
3534       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
3535         {
3536           /* ??? Maybe we could use convert_from_reference here, but we
3537              would need to relax its constraints because the NOP_EXPR
3538              could actually change the type to something more cv-qualified,
3539              and this is not folded by convert_from_reference.  */
3540           tree addr = TREE_OPERAND (expr, 0);
3541           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
3542           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
3543           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
3544           gcc_assert (same_type_ignoring_top_level_qualifiers_p
3545                       (TREE_TYPE (expr_type),
3546                        TREE_TYPE (TREE_TYPE (addr))));
3547
3548           expr = TREE_OPERAND (addr, 0);
3549           expr_type = TREE_TYPE (expr);
3550         }
3551
3552       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
3553          parameter is a pointer to object, through decay and
3554          qualification conversion. Let's strip everything.  */
3555       else if (TYPE_PTROBV_P (type))
3556         {
3557           STRIP_NOPS (expr);
3558           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
3559           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
3560           /* Skip the ADDR_EXPR only if it is part of the decay for
3561              an array. Otherwise, it is part of the original argument
3562              in the source code.  */
3563           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
3564             expr = TREE_OPERAND (expr, 0);
3565           expr_type = TREE_TYPE (expr);
3566         }
3567     }
3568
3569   /* [temp.arg.nontype]/5, bullet 1
3570
3571      For a non-type template-parameter of integral or enumeration type,
3572      integral promotions (_conv.prom_) and integral conversions
3573      (_conv.integral_) are applied.  */
3574   if (INTEGRAL_TYPE_P (type))
3575     {
3576       if (!INTEGRAL_TYPE_P (expr_type))
3577         return error_mark_node;
3578
3579       expr = fold_decl_constant_value (expr);
3580       /* Notice that there are constant expressions like '4 % 0' which
3581          do not fold into integer constants.  */
3582       if (TREE_CODE (expr) != INTEGER_CST)
3583         {
3584           error ("%qE is not a valid template argument for type %qT "
3585                  "because it is a non-constant expression", expr, type);
3586           return NULL_TREE;
3587         }
3588
3589       /* At this point, an implicit conversion does what we want,
3590          because we already know that the expression is of integral
3591          type.  */
3592       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
3593       if (expr == error_mark_node)
3594         return error_mark_node;
3595
3596       /* Conversion was allowed: fold it to a bare integer constant.  */
3597       expr = fold (expr);
3598     }
3599   /* [temp.arg.nontype]/5, bullet 2
3600
3601      For a non-type template-parameter of type pointer to object,
3602      qualification conversions (_conv.qual_) and the array-to-pointer
3603      conversion (_conv.array_) are applied.  */
3604   else if (TYPE_PTROBV_P (type))
3605     {
3606       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
3607
3608          A template-argument for a non-type, non-template template-parameter
3609          shall be one of: [...]
3610
3611          -- the name of a non-type template-parameter;
3612          -- the address of an object or function with external linkage, [...]
3613             expressed as "& id-expression" where the & is optional if the name
3614             refers to a function or array, or if the corresponding
3615             template-parameter is a reference.
3616
3617         Here, we do not care about functions, as they are invalid anyway
3618         for a parameter of type pointer-to-object.  */
3619       bool constant_address_p =
3620         (TREE_CODE (expr) == ADDR_EXPR
3621          || TREE_CODE (expr_type) == ARRAY_TYPE
3622          || (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr)));
3623
3624       expr = decay_conversion (expr);
3625       if (expr == error_mark_node)
3626         return error_mark_node;
3627
3628       expr = perform_qualification_conversions (type, expr);
3629       if (expr == error_mark_node)
3630         return error_mark_node;
3631
3632       if (!constant_address_p)
3633         {
3634             error ("%qE is not a valid template argument for type %qT "
3635                   "because it is not a constant pointer", expr, type);
3636             return NULL_TREE;
3637         }
3638     }
3639   /* [temp.arg.nontype]/5, bullet 3
3640
3641      For a non-type template-parameter of type reference to object, no
3642      conversions apply. The type referred to by the reference may be more
3643      cv-qualified than the (otherwise identical) type of the
3644      template-argument. The template-parameter is bound directly to the
3645      template-argument, which must be an lvalue.  */
3646   else if (TYPE_REF_OBJ_P (type))
3647     {
3648       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
3649                                                       expr_type))
3650         return error_mark_node;
3651
3652       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
3653         {
3654           error ("%qE is not a valid template argument for type %qT "
3655                  "because of conflicts in cv-qualification", expr, type);
3656           return NULL_TREE;
3657         }
3658
3659       if (!real_lvalue_p (expr))
3660         {
3661           error ("%qE is not a valid template argument for type %qT "
3662                  "because it is not a lvalue", expr, type);
3663           return NULL_TREE;
3664         }
3665
3666       /* [temp.arg.nontype]/1
3667
3668          A template-argument for a non-type, non-template template-parameter
3669          shall be one of: [...]
3670
3671          -- the address of an object or function with external linkage.  */
3672       if (!DECL_EXTERNAL_LINKAGE_P (expr))
3673         {
3674           error ("%qE is not a valid template argument for type %qT "
3675                  "because object %qD has not external linkage",
3676                  expr, type, expr);
3677           return NULL_TREE;
3678         }
3679
3680       expr = build_nop (type, build_address (expr));
3681     }
3682   /* [temp.arg.nontype]/5, bullet 4
3683
3684      For a non-type template-parameter of type pointer to function, only
3685      the function-to-pointer conversion (_conv.func_) is applied. If the
3686      template-argument represents a set of overloaded functions (or a
3687      pointer to such), the matching function is selected from the set
3688      (_over.over_).  */
3689   else if (TYPE_PTRFN_P (type))
3690     {
3691       /* If the argument is a template-id, we might not have enough
3692          context information to decay the pointer.  */
3693       if (!type_unknown_p (expr_type))
3694         {
3695           expr = decay_conversion (expr);
3696           if (expr == error_mark_node)
3697             return error_mark_node;
3698         }
3699
3700       expr = convert_nontype_argument_function (type, expr);
3701       if (!expr || expr == error_mark_node)
3702         return expr;
3703     }
3704   /* [temp.arg.nontype]/5, bullet 5
3705
3706      For a non-type template-parameter of type reference to function, no
3707      conversions apply. If the template-argument represents a set of
3708      overloaded functions, the matching function is selected from the set
3709      (_over.over_).  */
3710   else if (TYPE_REFFN_P (type))
3711     {
3712       if (TREE_CODE (expr) == ADDR_EXPR)
3713         {
3714           error ("%qE is not a valid template argument for type %qT "
3715                  "because it is a pointer", expr, type);
3716           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
3717           return NULL_TREE;
3718         }
3719
3720       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
3721       if (!expr || expr == error_mark_node)
3722         return expr;
3723
3724       expr = build_nop (type, build_address (expr));
3725     }
3726   /* [temp.arg.nontype]/5, bullet 6
3727
3728      For a non-type template-parameter of type pointer to member function,
3729      no conversions apply. If the template-argument represents a set of
3730      overloaded member functions, the matching member function is selected
3731      from the set (_over.over_).  */
3732   else if (TYPE_PTRMEMFUNC_P (type))
3733     {
3734       expr = instantiate_type (type, expr, tf_none);
3735       if (expr == error_mark_node)
3736         return error_mark_node;
3737
3738       /* There is no way to disable standard conversions in
3739          resolve_address_of_overloaded_function (called by
3740          instantiate_type). It is possible that the call succeeded by
3741          converting &B::I to &D::I (where B is a base of D), so we need
3742          to reject this conversion here.
3743
3744          Actually, even if there was a way to disable standard conversions,
3745          it would still be better to reject them here so that we can
3746          provide a superior diagnostic.  */
3747       if (!same_type_p (TREE_TYPE (expr), type))
3748         {
3749           /* Make sure we are just one standard conversion off.  */
3750           gcc_assert (can_convert (type, TREE_TYPE (expr)));
3751           error ("%qE is not a valid template argument for type %qT "
3752                  "because it is of type %qT", expr, type,
3753                  TREE_TYPE (expr));
3754           inform ("standard conversions are not allowed in this context");
3755           return NULL_TREE;
3756         }
3757     }
3758   /* [temp.arg.nontype]/5, bullet 7
3759
3760      For a non-type template-parameter of type pointer to data member,
3761      qualification conversions (_conv.qual_) are applied.  */
3762   else if (TYPE_PTRMEM_P (type))
3763     {
3764       expr = perform_qualification_conversions (type, expr);
3765       if (expr == error_mark_node)
3766         return expr;
3767     }
3768   /* A template non-type parameter must be one of the above.  */
3769   else
3770     gcc_unreachable ();
3771
3772   /* Sanity check: did we actually convert the argument to the
3773      right type?  */
3774   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
3775   return expr;
3776 }
3777
3778
3779 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
3780    template template parameters.  Both PARM_PARMS and ARG_PARMS are
3781    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
3782    or PARM_DECL.
3783
3784    ARG_PARMS may contain more parameters than PARM_PARMS.  If this is
3785    the case, then extra parameters must have default arguments.
3786
3787    Consider the example:
3788      template <class T, class Allocator = allocator> class vector;
3789      template<template <class U> class TT> class C;
3790
3791    C<vector> is a valid instantiation.  PARM_PARMS for the above code
3792    contains a TYPE_DECL (for U),  ARG_PARMS contains two TYPE_DECLs (for
3793    T and Allocator) and OUTER_ARGS contains the argument that is used to
3794    substitute the TT parameter.  */
3795
3796 static int
3797 coerce_template_template_parms (tree parm_parms,
3798                                 tree arg_parms,
3799                                 tsubst_flags_t complain,
3800                                 tree in_decl,
3801                                 tree outer_args)
3802 {
3803   int nparms, nargs, i;
3804   tree parm, arg;
3805
3806   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
3807   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
3808
3809   nparms = TREE_VEC_LENGTH (parm_parms);
3810   nargs = TREE_VEC_LENGTH (arg_parms);
3811
3812   /* The rule here is opposite of coerce_template_parms.  */
3813   if (nargs < nparms
3814       || (nargs > nparms
3815           && TREE_PURPOSE (TREE_VEC_ELT (arg_parms, nparms)) == NULL_TREE))
3816     return 0;
3817
3818   for (i = 0; i < nparms; ++i)
3819     {
3820       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
3821       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
3822
3823       if (arg == NULL_TREE || arg == error_mark_node
3824           || parm == NULL_TREE || parm == error_mark_node)
3825         return 0;
3826
3827       if (TREE_CODE (arg) != TREE_CODE (parm))
3828         return 0;
3829
3830       switch (TREE_CODE (parm))
3831         {
3832         case TYPE_DECL:
3833           break;
3834
3835         case TEMPLATE_DECL:
3836           /* We encounter instantiations of templates like
3837                template <template <template <class> class> class TT>
3838                class C;  */
3839           {
3840             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3841             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3842
3843             if (!coerce_template_template_parms
3844                 (parmparm, argparm, complain, in_decl, outer_args))
3845               return 0;
3846           }
3847           break;
3848
3849         case PARM_DECL:
3850           /* The tsubst call is used to handle cases such as
3851
3852                template <int> class C {};
3853                template <class T, template <T> class TT> class D {};
3854                D<int, C> d;
3855
3856              i.e. the parameter list of TT depends on earlier parameters.  */
3857           if (!dependent_type_p (TREE_TYPE (arg))
3858               && !same_type_p
3859                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
3860                              TREE_TYPE (arg)))
3861             return 0;
3862           break;
3863
3864         default:
3865           gcc_unreachable ();
3866         }
3867     }
3868   return 1;
3869 }
3870
3871 /* Convert the indicated template ARG as necessary to match the
3872    indicated template PARM.  Returns the converted ARG, or
3873    error_mark_node if the conversion was unsuccessful.  Error and
3874    warning messages are issued under control of COMPLAIN.  This
3875    conversion is for the Ith parameter in the parameter list.  ARGS is
3876    the full set of template arguments deduced so far.  */
3877
3878 static tree
3879 convert_template_argument (tree parm,
3880                            tree arg,
3881                            tree args,
3882                            tsubst_flags_t complain,
3883                            int i,
3884                            tree in_decl)
3885 {
3886   tree val;
3887   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
3888
3889   if (TREE_CODE (arg) == TREE_LIST
3890       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
3891     {
3892       /* The template argument was the name of some
3893          member function.  That's usually
3894          invalid, but static members are OK.  In any
3895          case, grab the underlying fields/functions
3896          and issue an error later if required.  */
3897       arg = TREE_VALUE (arg);
3898       TREE_TYPE (arg) = unknown_type_node;
3899     }
3900
3901   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
3902   requires_type = (TREE_CODE (parm) == TYPE_DECL
3903                    || requires_tmpl_type);
3904
3905   is_tmpl_type = ((TREE_CODE (arg) == TEMPLATE_DECL
3906                    && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
3907                   || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3908                   || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
3909
3910   if (is_tmpl_type
3911       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3912           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
3913     arg = TYPE_STUB_DECL (arg);
3914
3915   is_type = TYPE_P (arg) || is_tmpl_type;
3916
3917   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
3918       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
3919     {
3920       pedwarn ("to refer to a type member of a template parameter, "
3921                "use %<typename %E%>", arg);
3922
3923       arg = make_typename_type (TREE_OPERAND (arg, 0),
3924                                 TREE_OPERAND (arg, 1),
3925                                 typename_type,
3926                                 complain & tf_error);
3927       is_type = 1;
3928     }
3929   if (is_type != requires_type)
3930     {
3931       if (in_decl)
3932         {
3933           if (complain & tf_error)
3934             {
3935               error ("type/value mismatch at argument %d in template "
3936                      "parameter list for %qD",
3937                      i + 1, in_decl);
3938               if (is_type)
3939                 error ("  expected a constant of type %qT, got %qT",
3940                        TREE_TYPE (parm),
3941                        (is_tmpl_type ? DECL_NAME (arg) : arg));
3942               else if (requires_tmpl_type)
3943                 error ("  expected a class template, got %qE", arg);
3944               else
3945                 error ("  expected a type, got %qE", arg);
3946             }
3947         }
3948       return error_mark_node;
3949     }
3950   if (is_tmpl_type ^ requires_tmpl_type)
3951     {
3952       if (in_decl && (complain & tf_error))
3953         {
3954           error ("type/value mismatch at argument %d in template "
3955                  "parameter list for %qD",
3956                  i + 1, in_decl);
3957           if (is_tmpl_type)
3958             error ("  expected a type, got %qT", DECL_NAME (arg));
3959           else
3960             error ("  expected a class template, got %qT", arg);
3961         }
3962       return error_mark_node;
3963     }
3964
3965   if (is_type)
3966     {
3967       if (requires_tmpl_type)
3968         {
3969           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
3970             /* The number of argument required is not known yet.
3971                Just accept it for now.  */
3972             val = TREE_TYPE (arg);
3973           else
3974             {
3975               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3976               tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3977
3978               if (coerce_template_template_parms (parmparm, argparm,
3979                                                   complain, in_decl,
3980                                                   args))
3981                 {
3982                   val = arg;
3983
3984                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
3985                      TEMPLATE_DECL.  */
3986                   if (val != error_mark_node
3987                       && DECL_TEMPLATE_TEMPLATE_PARM_P (val))
3988                     val = TREE_TYPE (val);
3989                 }
3990               else
3991                 {
3992                   if (in_decl && (complain & tf_error))
3993                     {
3994                       error ("type/value mismatch at argument %d in "
3995                              "template parameter list for %qD",
3996                              i + 1, in_decl);
3997                       error ("  expected a template of type %qD, got %qD",
3998                              parm, arg);
3999                     }
4000
4001                   val = error_mark_node;
4002                 }
4003             }
4004         }
4005       else
4006         val = arg;
4007       /* We only form one instance of each template specialization.
4008          Therefore, if we use a non-canonical variant (i.e., a
4009          typedef), any future messages referring to the type will use 
4010          the typedef, which is confusing if those future uses do not
4011          themselves also use the typedef.  */
4012       if (TYPE_P (val))
4013         val = canonical_type_variant (val);
4014     }
4015   else
4016     {
4017       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
4018
4019       if (invalid_nontype_parm_type_p (t, complain))
4020         return error_mark_node;
4021
4022       if (!uses_template_parms (arg) && !uses_template_parms (t))
4023         /* We used to call digest_init here.  However, digest_init
4024            will report errors, which we don't want when complain
4025            is zero.  More importantly, digest_init will try too
4026            hard to convert things: for example, `0' should not be
4027            converted to pointer type at this point according to
4028            the standard.  Accepting this is not merely an
4029            extension, since deciding whether or not these
4030            conversions can occur is part of determining which
4031            function template to call, or whether a given explicit
4032            argument specification is valid.  */
4033         val = convert_nontype_argument (t, arg);
4034       else
4035         val = arg;
4036
4037       if (val == NULL_TREE)
4038         val = error_mark_node;
4039       else if (val == error_mark_node && (complain & tf_error))
4040         error ("could not convert template argument %qE to %qT",  arg, t);
4041     }
4042
4043   return val;
4044 }
4045
4046 /* Convert all template arguments to their appropriate types, and
4047    return a vector containing the innermost resulting template
4048    arguments.  If any error occurs, return error_mark_node. Error and
4049    warning messages are issued under control of COMPLAIN.
4050
4051    If REQUIRE_ALL_ARGUMENTS is nonzero, all arguments must be
4052    provided in ARGLIST, or else trailing parameters must have default
4053    values.  If REQUIRE_ALL_ARGUMENTS is zero, we will attempt argument
4054    deduction for any unspecified trailing arguments.  */
4055
4056 static tree
4057 coerce_template_parms (tree parms,
4058                        tree args,
4059                        tree in_decl,
4060                        tsubst_flags_t complain,
4061                        int require_all_arguments)
4062 {
4063   int nparms, nargs, i, lost = 0;
4064   tree inner_args;
4065   tree new_args;
4066   tree new_inner_args;
4067   bool saved_skip_evaluation;
4068
4069   inner_args = INNERMOST_TEMPLATE_ARGS (args);
4070   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4071   nparms = TREE_VEC_LENGTH (parms);
4072
4073   if (nargs > nparms
4074       || (nargs < nparms
4075           && require_all_arguments
4076           && TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)) == NULL_TREE))
4077     {
4078       if (complain & tf_error)
4079         {
4080           error ("wrong number of template arguments (%d, should be %d)",
4081                  nargs, nparms);
4082
4083           if (in_decl)
4084             error ("provided for %q+D", in_decl);
4085         }
4086
4087       return error_mark_node;
4088     }
4089
4090   /* We need to evaluate the template arguments, even though this
4091      template-id may be nested within a "sizeof".  */
4092   saved_skip_evaluation = skip_evaluation;
4093   skip_evaluation = false;
4094   new_inner_args = make_tree_vec (nparms);
4095   new_args = add_outermost_template_args (args, new_inner_args);
4096   for (i = 0; i < nparms; i++)
4097     {
4098       tree arg;
4099       tree parm;
4100
4101       /* Get the Ith template parameter.  */
4102       parm = TREE_VEC_ELT (parms, i);
4103
4104       /* Calculate the Ith argument.  */
4105       if (i < nargs)
4106         arg = TREE_VEC_ELT (inner_args, i);
4107       else if (require_all_arguments)
4108         /* There must be a default arg in this case.  */
4109         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
4110                                    complain, in_decl);
4111       else
4112         break;
4113
4114       gcc_assert (arg);
4115       if (arg == error_mark_node)
4116         {
4117           if (complain & tf_error)
4118             error ("template argument %d is invalid", i + 1);
4119         }
4120       else
4121         arg = convert_template_argument (TREE_VALUE (parm),
4122                                          arg, new_args, complain, i,
4123                                          in_decl);
4124
4125       if (arg == error_mark_node)
4126         lost++;
4127       TREE_VEC_ELT (new_inner_args, i) = arg;
4128     }
4129   skip_evaluation = saved_skip_evaluation;
4130
4131   if (lost)
4132     return error_mark_node;
4133
4134   return new_inner_args;
4135 }
4136
4137 /* Returns 1 if template args OT and NT are equivalent.  */
4138
4139 static int
4140 template_args_equal (tree ot, tree nt)
4141 {
4142   if (nt == ot)
4143     return 1;
4144
4145   if (TREE_CODE (nt) == TREE_VEC)
4146     /* For member templates */
4147     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
4148   else if (TYPE_P (nt))
4149     return TYPE_P (ot) && same_type_p (ot, nt);
4150   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
4151     return 0;
4152   else
4153     return cp_tree_equal (ot, nt);
4154 }
4155
4156 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
4157    of template arguments.  Returns 0 otherwise.  */
4158
4159 int
4160 comp_template_args (tree oldargs, tree newargs)
4161 {
4162   int i;
4163
4164   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
4165     return 0;
4166
4167   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
4168     {
4169       tree nt = TREE_VEC_ELT (newargs, i);
4170       tree ot = TREE_VEC_ELT (oldargs, i);
4171
4172       if (! template_args_equal (ot, nt))
4173         return 0;
4174     }
4175   return 1;
4176 }
4177
4178 /* Given class template name and parameter list, produce a user-friendly name
4179    for the instantiation.  */
4180
4181 static char *
4182 mangle_class_name_for_template (const char* name, tree parms, tree arglist)
4183 {
4184   static struct obstack scratch_obstack;
4185   static char *scratch_firstobj;
4186   int i, nparms;
4187
4188   if (!scratch_firstobj)
4189     gcc_obstack_init (&scratch_obstack);
4190   else
4191     obstack_free (&scratch_obstack, scratch_firstobj);
4192   scratch_firstobj = obstack_alloc (&scratch_obstack, 1);
4193
4194 #define ccat(C) obstack_1grow (&scratch_obstack, (C));
4195 #define cat(S)  obstack_grow (&scratch_obstack, (S), strlen (S))
4196
4197   cat (name);
4198   ccat ('<');
4199   nparms = TREE_VEC_LENGTH (parms);
4200   arglist = INNERMOST_TEMPLATE_ARGS (arglist);
4201   gcc_assert (nparms == TREE_VEC_LENGTH (arglist));
4202   for (i = 0; i < nparms; i++)
4203     {
4204       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4205       tree arg = TREE_VEC_ELT (arglist, i);
4206
4207       if (i)
4208         ccat (',');
4209
4210       if (TREE_CODE (parm) == TYPE_DECL)
4211         {
4212           cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
4213           continue;
4214         }
4215       else if (TREE_CODE (parm) == TEMPLATE_DECL)
4216         {
4217           if (TREE_CODE (arg) == TEMPLATE_DECL)
4218             {
4219               /* Already substituted with real template.  Just output
4220                  the template name here */
4221               tree context = DECL_CONTEXT (arg);
4222               if (context)
4223                 {
4224                   /* The template may be defined in a namespace, or
4225                      may be a member template.  */
4226                   gcc_assert (TREE_CODE (context) == NAMESPACE_DECL
4227                               || CLASS_TYPE_P (context));
4228                   cat (decl_as_string (DECL_CONTEXT (arg),
4229                                       TFF_PLAIN_IDENTIFIER));
4230                   cat ("::");
4231                 }
4232               cat (IDENTIFIER_POINTER (DECL_NAME (arg)));
4233             }
4234           else
4235             /* Output the parameter declaration.  */
4236             cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
4237           continue;
4238         }
4239       else
4240         gcc_assert (TREE_CODE (parm) == PARM_DECL);
4241
4242       /* No need to check arglist against parmlist here; we did that
4243          in coerce_template_parms, called from lookup_template_class.  */
4244       cat (expr_as_string (arg, TFF_PLAIN_IDENTIFIER));
4245     }
4246   {
4247     char *bufp = obstack_next_free (&scratch_obstack);
4248     int offset = 0;
4249     while (bufp[offset - 1] == ' ')
4250       offset--;
4251     obstack_blank_fast (&scratch_obstack, offset);
4252
4253     /* B<C<char> >, not B<C<char>> */
4254     if (bufp[offset - 1] == '>')
4255       ccat (' ');
4256   }
4257   ccat ('>');
4258   ccat ('\0');
4259   return (char *) obstack_base (&scratch_obstack);
4260 }
4261
4262 static tree
4263 classtype_mangled_name (tree t)
4264 {
4265   if (CLASSTYPE_TEMPLATE_INFO (t)
4266       /* Specializations have already had their names set up in
4267          lookup_template_class.  */
4268       && !CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
4269     {
4270       tree tmpl = most_general_template (CLASSTYPE_TI_TEMPLATE (t));
4271
4272       /* For non-primary templates, the template parameters are
4273          implicit from their surrounding context.  */
4274       if (PRIMARY_TEMPLATE_P (tmpl))
4275         {
4276           tree name = DECL_NAME (tmpl);
4277           char *mangled_name = mangle_class_name_for_template
4278             (IDENTIFIER_POINTER (name),
4279              DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
4280              CLASSTYPE_TI_ARGS (t));
4281           tree id = get_identifier (mangled_name);
4282           IDENTIFIER_TEMPLATE (id) = name;
4283           return id;
4284         }
4285     }
4286
4287   return TYPE_IDENTIFIER (t);
4288 }
4289
4290 static void
4291 add_pending_template (tree d)
4292 {
4293   tree ti = (TYPE_P (d)
4294              ? CLASSTYPE_TEMPLATE_INFO (d)
4295              : DECL_TEMPLATE_INFO (d));
4296   tree pt;
4297   int level;
4298
4299   if (TI_PENDING_TEMPLATE_FLAG (ti))
4300     return;
4301
4302   /* We are called both from instantiate_decl, where we've already had a
4303      tinst_level pushed, and instantiate_template, where we haven't.
4304      Compensate.  */
4305   level = !(current_tinst_level && TINST_DECL (current_tinst_level) == d);
4306
4307   if (level)
4308     push_tinst_level (d);
4309
4310   pt = tree_cons (current_tinst_level, d, NULL_TREE);
4311   if (last_pending_template)
4312     TREE_CHAIN (last_pending_template) = pt;
4313   else
4314     pending_templates = pt;
4315
4316   last_pending_template = pt;
4317
4318   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
4319
4320   if (level)
4321     pop_tinst_level ();
4322 }
4323
4324
4325 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
4326    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
4327    documentation for TEMPLATE_ID_EXPR.  */
4328
4329 tree
4330 lookup_template_function (tree fns, tree arglist)
4331 {
4332   tree type;
4333
4334   if (fns == error_mark_node || arglist == error_mark_node)
4335     return error_mark_node;
4336
4337   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
4338   gcc_assert (fns && (is_overloaded_fn (fns)
4339                       || TREE_CODE (fns) == IDENTIFIER_NODE));
4340
4341   if (BASELINK_P (fns))
4342     {
4343       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
4344                                          unknown_type_node,
4345                                          BASELINK_FUNCTIONS (fns),
4346                                          arglist);
4347       return fns;
4348     }
4349
4350   type = TREE_TYPE (fns);
4351   if (TREE_CODE (fns) == OVERLOAD || !type)
4352     type = unknown_type_node;
4353
4354   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
4355 }
4356
4357 /* Within the scope of a template class S<T>, the name S gets bound
4358    (in build_self_reference) to a TYPE_DECL for the class, not a
4359    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
4360    or one of its enclosing classes, and that type is a template,
4361    return the associated TEMPLATE_DECL.  Otherwise, the original
4362    DECL is returned.  */
4363
4364 tree
4365 maybe_get_template_decl_from_type_decl (tree decl)
4366 {
4367   return (decl != NULL_TREE
4368           && TREE_CODE (decl) == TYPE_DECL
4369           && DECL_ARTIFICIAL (decl)
4370           && CLASS_TYPE_P (TREE_TYPE (decl))
4371           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
4372     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
4373 }
4374
4375 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
4376    parameters, find the desired type.
4377
4378    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
4379
4380    IN_DECL, if non-NULL, is the template declaration we are trying to
4381    instantiate.
4382
4383    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
4384    the class we are looking up.
4385
4386    Issue error and warning messages under control of COMPLAIN.
4387
4388    If the template class is really a local class in a template
4389    function, then the FUNCTION_CONTEXT is the function in which it is
4390    being instantiated.
4391
4392    ??? Note that this function is currently called *twice* for each
4393    template-id: the first time from the parser, while creating the
4394    incomplete type (finish_template_type), and the second type during the
4395    real instantiation (instantiate_template_class). This is surely something
4396    that we want to avoid. It also causes some problems with argument
4397    coercion (see convert_nontype_argument for more information on this).  */
4398
4399 tree
4400 lookup_template_class (tree d1,
4401                        tree arglist,
4402                        tree in_decl,
4403                        tree context,
4404                        int entering_scope,
4405                        tsubst_flags_t complain)
4406 {
4407   tree template = NULL_TREE, parmlist;
4408   tree t;
4409
4410   timevar_push (TV_NAME_LOOKUP);
4411
4412   if (TREE_CODE (d1) == IDENTIFIER_NODE)
4413     {
4414       tree value = innermost_non_namespace_value (d1);
4415       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
4416         template = value;
4417       else
4418         {
4419           if (context)
4420             push_decl_namespace (context);
4421           template = lookup_name (d1, /*prefer_type=*/0);
4422           template = maybe_get_template_decl_from_type_decl (template);
4423           if (context)
4424             pop_decl_namespace ();
4425         }
4426       if (template)
4427         context = DECL_CONTEXT (template);
4428     }
4429   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
4430     {
4431       tree type = TREE_TYPE (d1);
4432
4433       /* If we are declaring a constructor, say A<T>::A<T>, we will get
4434          an implicit typename for the second A.  Deal with it.  */
4435       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
4436         type = TREE_TYPE (type);
4437
4438       if (CLASSTYPE_TEMPLATE_INFO (type))
4439         {
4440           template = CLASSTYPE_TI_TEMPLATE (type);
4441           d1 = DECL_NAME (template);
4442         }
4443     }
4444   else if (TREE_CODE (d1) == ENUMERAL_TYPE
4445            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
4446     {
4447       template = TYPE_TI_TEMPLATE (d1);
4448       d1 = DECL_NAME (template);
4449     }
4450   else if (TREE_CODE (d1) == TEMPLATE_DECL
4451            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
4452     {
4453       template = d1;
4454       d1 = DECL_NAME (template);
4455       context = DECL_CONTEXT (template);
4456     }
4457
4458   /* Issue an error message if we didn't find a template.  */
4459   if (! template)
4460     {
4461       if (complain & tf_error)
4462         error ("%qT is not a template", d1);
4463       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4464     }
4465
4466   if (TREE_CODE (template) != TEMPLATE_DECL
4467          /* Make sure it's a user visible template, if it was named by
4468             the user.  */
4469       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
4470           && !PRIMARY_TEMPLATE_P (template)))
4471     {
4472       if (complain & tf_error)
4473         {
4474           error ("non-template type %qT used as a template", d1);
4475           if (in_decl)
4476             error ("for template declaration %q+D", in_decl);
4477         }
4478       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4479     }
4480
4481   complain &= ~tf_user;
4482
4483   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
4484     {
4485       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
4486          template arguments */
4487
4488       tree parm;
4489       tree arglist2;
4490
4491       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
4492
4493       /* Consider an example where a template template parameter declared as
4494
4495            template <class T, class U = std::allocator<T> > class TT
4496
4497          The template parameter level of T and U are one level larger than
4498          of TT.  To proper process the default argument of U, say when an
4499          instantiation `TT<int>' is seen, we need to build the full
4500          arguments containing {int} as the innermost level.  Outer levels,
4501          available when not appearing as default template argument, can be
4502          obtained from `current_template_args ()'.
4503
4504          Suppose that TT is later substituted with std::vector.  The above
4505          instantiation is `TT<int, std::allocator<T> >' with TT at
4506          level 1, and T at level 2, while the template arguments at level 1
4507          becomes {std::vector} and the inner level 2 is {int}.  */
4508
4509       if (current_template_parms)
4510         arglist = add_to_template_args (current_template_args (), arglist);
4511
4512       arglist2 = coerce_template_parms (parmlist, arglist, template,
4513                                         complain, /*require_all_args=*/1);
4514       if (arglist2 == error_mark_node
4515           || (!uses_template_parms (arglist2)
4516               && check_instantiated_args (template, arglist2, complain)))
4517         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4518
4519       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
4520       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
4521     }
4522   else
4523     {
4524       tree template_type = TREE_TYPE (template);
4525       tree gen_tmpl;
4526       tree type_decl;
4527       tree found = NULL_TREE;
4528       int arg_depth;
4529       int parm_depth;
4530       int is_partial_instantiation;
4531
4532       gen_tmpl = most_general_template (template);
4533       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
4534       parm_depth = TMPL_PARMS_DEPTH (parmlist);
4535       arg_depth = TMPL_ARGS_DEPTH (arglist);
4536
4537       if (arg_depth == 1 && parm_depth > 1)
4538         {
4539           /* We've been given an incomplete set of template arguments.
4540              For example, given:
4541
4542                template <class T> struct S1 {
4543                  template <class U> struct S2 {};
4544                  template <class U> struct S2<U*> {};
4545                 };
4546
4547              we will be called with an ARGLIST of `U*', but the
4548              TEMPLATE will be `template <class T> template
4549              <class U> struct S1<T>::S2'.  We must fill in the missing
4550              arguments.  */
4551           arglist
4552             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
4553                                            arglist);
4554           arg_depth = TMPL_ARGS_DEPTH (arglist);
4555         }
4556
4557       /* Now we should have enough arguments.  */
4558       gcc_assert (parm_depth == arg_depth);
4559
4560       /* From here on, we're only interested in the most general
4561          template.  */
4562       template = gen_tmpl;
4563
4564       /* Calculate the BOUND_ARGS.  These will be the args that are
4565          actually tsubst'd into the definition to create the
4566          instantiation.  */
4567       if (parm_depth > 1)
4568         {
4569           /* We have multiple levels of arguments to coerce, at once.  */
4570           int i;
4571           int saved_depth = TMPL_ARGS_DEPTH (arglist);
4572
4573           tree bound_args = make_tree_vec (parm_depth);
4574
4575           for (i = saved_depth,
4576                  t = DECL_TEMPLATE_PARMS (template);
4577                i > 0 && t != NULL_TREE;
4578                --i, t = TREE_CHAIN (t))
4579             {
4580               tree a = coerce_template_parms (TREE_VALUE (t),
4581                                               arglist, template,
4582                                               complain, /*require_all_args=*/1);
4583
4584               /* Don't process further if one of the levels fails.  */
4585               if (a == error_mark_node)
4586                 {
4587                   /* Restore the ARGLIST to its full size.  */
4588                   TREE_VEC_LENGTH (arglist) = saved_depth;
4589                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4590                 }
4591
4592               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
4593
4594               /* We temporarily reduce the length of the ARGLIST so
4595                  that coerce_template_parms will see only the arguments
4596                  corresponding to the template parameters it is
4597                  examining.  */
4598               TREE_VEC_LENGTH (arglist)--;
4599             }
4600
4601           /* Restore the ARGLIST to its full size.  */
4602           TREE_VEC_LENGTH (arglist) = saved_depth;
4603
4604           arglist = bound_args;
4605         }
4606       else
4607         arglist
4608           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
4609                                    INNERMOST_TEMPLATE_ARGS (arglist),
4610                                    template,
4611                                    complain, /*require_all_args=*/1);
4612
4613       if (arglist == error_mark_node)
4614         /* We were unable to bind the arguments.  */
4615         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4616
4617       /* In the scope of a template class, explicit references to the
4618          template class refer to the type of the template, not any
4619          instantiation of it.  For example, in:
4620
4621            template <class T> class C { void f(C<T>); }
4622
4623          the `C<T>' is just the same as `C'.  Outside of the
4624          class, however, such a reference is an instantiation.  */
4625       if (comp_template_args (TYPE_TI_ARGS (template_type),
4626                               arglist))
4627         {
4628           found = template_type;
4629
4630           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
4631             {
4632               tree ctx;
4633
4634               for (ctx = current_class_type;
4635                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
4636                    ctx = (TYPE_P (ctx)
4637                           ? TYPE_CONTEXT (ctx)
4638                           : DECL_CONTEXT (ctx)))
4639                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
4640                   goto found_ctx;
4641
4642               /* We're not in the scope of the class, so the
4643                  TEMPLATE_TYPE is not the type we want after all.  */
4644               found = NULL_TREE;
4645             found_ctx:;
4646             }
4647         }
4648       if (found)
4649         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4650
4651       /* If we already have this specialization, return it.  */
4652       found = retrieve_specialization (template, arglist,
4653                                        /*class_specializations_p=*/false);
4654       if (found)
4655         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4656
4657       /* This type is a "partial instantiation" if any of the template
4658          arguments still involve template parameters.  Note that we set
4659          IS_PARTIAL_INSTANTIATION for partial specializations as
4660          well.  */
4661       is_partial_instantiation = uses_template_parms (arglist);
4662
4663       /* If the deduced arguments are invalid, then the binding
4664          failed.  */
4665       if (!is_partial_instantiation
4666           && check_instantiated_args (template,
4667                                       INNERMOST_TEMPLATE_ARGS (arglist),
4668                                       complain))
4669         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4670
4671       if (!is_partial_instantiation
4672           && !PRIMARY_TEMPLATE_P (template)
4673           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
4674         {
4675           found = xref_tag_from_type (TREE_TYPE (template),
4676                                       DECL_NAME (template),
4677                                       /*tag_scope=*/ts_global);
4678           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4679         }
4680
4681       context = tsubst (DECL_CONTEXT (template), arglist,
4682                         complain, in_decl);
4683       if (!context)
4684         context = global_namespace;
4685
4686       /* Create the type.  */
4687       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
4688         {
4689           if (!is_partial_instantiation)
4690             {
4691               set_current_access_from_decl (TYPE_NAME (template_type));
4692               t = start_enum (TYPE_IDENTIFIER (template_type));
4693             }
4694           else
4695             /* We don't want to call start_enum for this type, since
4696                the values for the enumeration constants may involve
4697                template parameters.  And, no one should be interested
4698                in the enumeration constants for such a type.  */
4699             t = make_node (ENUMERAL_TYPE);
4700         }
4701       else
4702         {
4703           t = make_aggr_type (TREE_CODE (template_type));
4704           CLASSTYPE_DECLARED_CLASS (t)
4705             = CLASSTYPE_DECLARED_CLASS (template_type);
4706           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
4707           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
4708
4709           /* A local class.  Make sure the decl gets registered properly.  */
4710           if (context == current_function_decl)
4711             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
4712         }
4713
4714       /* If we called start_enum or pushtag above, this information
4715          will already be set up.  */
4716       if (!TYPE_NAME (t))
4717         {
4718           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4719
4720           type_decl = create_implicit_typedef (DECL_NAME (template), t);
4721           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
4722           TYPE_STUB_DECL (t) = type_decl;
4723           DECL_SOURCE_LOCATION (type_decl)
4724             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
4725         }
4726       else
4727         type_decl = TYPE_NAME (t);
4728
4729       TREE_PRIVATE (type_decl)
4730         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
4731       TREE_PROTECTED (type_decl)
4732         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
4733       DECL_IN_SYSTEM_HEADER (type_decl)
4734         = DECL_IN_SYSTEM_HEADER (template);
4735       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
4736         {
4737           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
4738           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
4739         }
4740
4741       /* Set up the template information.  We have to figure out which
4742          template is the immediate parent if this is a full
4743          instantiation.  */
4744       if (parm_depth == 1 || is_partial_instantiation
4745           || !PRIMARY_TEMPLATE_P (template))
4746         /* This case is easy; there are no member templates involved.  */
4747         found = template;
4748       else
4749         {
4750           /* This is a full instantiation of a member template.  Look
4751              for a partial instantiation of which this is an instance.  */
4752
4753           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
4754                found; found = TREE_CHAIN (found))
4755             {
4756               int success;
4757               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
4758
4759               /* We only want partial instantiations, here, not
4760                  specializations or full instantiations.  */
4761               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
4762                   || !uses_template_parms (TREE_VALUE (found)))
4763                 continue;
4764
4765               /* Temporarily reduce by one the number of levels in the
4766                  ARGLIST and in FOUND so as to avoid comparing the
4767                  last set of arguments.  */
4768               TREE_VEC_LENGTH (arglist)--;
4769               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
4770
4771               /* See if the arguments match.  If they do, then TMPL is
4772                  the partial instantiation we want.  */
4773               success = comp_template_args (TREE_PURPOSE (found), arglist);
4774
4775               /* Restore the argument vectors to their full size.  */
4776               TREE_VEC_LENGTH (arglist)++;
4777               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
4778
4779               if (success)
4780                 {
4781                   found = tmpl;
4782                   break;
4783                 }
4784             }
4785
4786           if (!found)
4787             {
4788               /* There was no partial instantiation. This happens
4789                  where C<T> is a member template of A<T> and it's used
4790                  in something like
4791
4792                   template <typename T> struct B { A<T>::C<int> m; };
4793                   B<float>;
4794
4795                  Create the partial instantiation.
4796                */
4797               TREE_VEC_LENGTH (arglist)--;
4798               found = tsubst (template, arglist, complain, NULL_TREE);
4799               TREE_VEC_LENGTH (arglist)++;
4800             }
4801         }
4802
4803       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
4804       DECL_TEMPLATE_INSTANTIATIONS (template)
4805         = tree_cons (arglist, t,
4806                      DECL_TEMPLATE_INSTANTIATIONS (template));
4807
4808       if (TREE_CODE (t) == ENUMERAL_TYPE
4809           && !is_partial_instantiation)
4810         /* Now that the type has been registered on the instantiations
4811            list, we set up the enumerators.  Because the enumeration
4812            constants may involve the enumeration type itself, we make
4813            sure to register the type first, and then create the
4814            constants.  That way, doing tsubst_expr for the enumeration
4815            constants won't result in recursive calls here; we'll find
4816            the instantiation and exit above.  */
4817         tsubst_enum (template_type, t, arglist);
4818
4819       /* Reset the name of the type, now that CLASSTYPE_TEMPLATE_INFO
4820          is set up.  */
4821       if (TREE_CODE (t) != ENUMERAL_TYPE)
4822         DECL_NAME (type_decl) = classtype_mangled_name (t);
4823       if (is_partial_instantiation)
4824         /* If the type makes use of template parameters, the
4825            code that generates debugging information will crash.  */
4826         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
4827
4828       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4829     }
4830   timevar_pop (TV_NAME_LOOKUP);
4831 }
4832 \f
4833 struct pair_fn_data
4834 {
4835   tree_fn_t fn;
4836   void *data;
4837   struct pointer_set_t *visited;
4838 };
4839
4840 /* Called from for_each_template_parm via walk_tree.  */
4841
4842 static tree
4843 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
4844 {
4845   tree t = *tp;
4846   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
4847   tree_fn_t fn = pfd->fn;
4848   void *data = pfd->data;
4849
4850   if (TYPE_P (t)
4851       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited))
4852     return error_mark_node;
4853
4854   switch (TREE_CODE (t))
4855     {
4856     case RECORD_TYPE:
4857       if (TYPE_PTRMEMFUNC_P (t))
4858         break;
4859       /* Fall through.  */
4860
4861     case UNION_TYPE:
4862     case ENUMERAL_TYPE:
4863       if (!TYPE_TEMPLATE_INFO (t))
4864         *walk_subtrees = 0;
4865       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
4866                                        fn, data, pfd->visited))
4867         return error_mark_node;
4868       break;
4869
4870     case METHOD_TYPE:
4871       /* Since we're not going to walk subtrees, we have to do this
4872          explicitly here.  */
4873       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
4874                                   pfd->visited))
4875         return error_mark_node;
4876       /* Fall through.  */
4877
4878     case FUNCTION_TYPE:
4879       /* Check the return type.  */
4880       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
4881         return error_mark_node;
4882
4883       /* Check the parameter types.  Since default arguments are not
4884          instantiated until they are needed, the TYPE_ARG_TYPES may
4885          contain expressions that involve template parameters.  But,
4886          no-one should be looking at them yet.  And, once they're
4887          instantiated, they don't contain template parameters, so
4888          there's no point in looking at them then, either.  */
4889       {
4890         tree parm;
4891
4892         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
4893           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
4894                                       pfd->visited))
4895             return error_mark_node;
4896
4897         /* Since we've already handled the TYPE_ARG_TYPES, we don't
4898            want walk_tree walking into them itself.  */
4899         *walk_subtrees = 0;
4900       }
4901       break;
4902
4903     case TYPEOF_TYPE:
4904       if (for_each_template_parm (TYPE_FIELDS (t), fn, data,
4905                                   pfd->visited))
4906         return error_mark_node;
4907       break;
4908
4909     case FUNCTION_DECL:
4910     case VAR_DECL:
4911       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
4912           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
4913                                      pfd->visited))
4914         return error_mark_node;
4915       /* Fall through.  */
4916
4917     case PARM_DECL:
4918     case CONST_DECL:
4919       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
4920           && for_each_template_parm (DECL_INITIAL (t), fn, data,
4921                                      pfd->visited))
4922         return error_mark_node;
4923       if (DECL_CONTEXT (t)
4924           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
4925                                      pfd->visited))
4926         return error_mark_node;
4927       break;
4928
4929     case BOUND_TEMPLATE_TEMPLATE_PARM:
4930       /* Record template parameters such as `T' inside `TT<T>'.  */
4931       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited))
4932         return error_mark_node;
4933       /* Fall through.  */
4934
4935     case TEMPLATE_TEMPLATE_PARM:
4936     case TEMPLATE_TYPE_PARM:
4937     case TEMPLATE_PARM_INDEX:
4938       if (fn && (*fn)(t, data))
4939         return error_mark_node;
4940       else if (!fn)
4941         return error_mark_node;
4942       break;
4943
4944     case TEMPLATE_DECL:
4945       /* A template template parameter is encountered.  */
4946       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
4947           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
4948         return error_mark_node;
4949
4950       /* Already substituted template template parameter */
4951       *walk_subtrees = 0;
4952       break;
4953
4954     case TYPENAME_TYPE:
4955       if (!fn
4956           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
4957                                      data, pfd->visited))
4958         return error_mark_node;
4959       break;
4960
4961     case CONSTRUCTOR:
4962       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
4963           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
4964                                      (TREE_TYPE (t)), fn, data,
4965                                      pfd->visited))
4966         return error_mark_node;
4967       break;
4968
4969     case INDIRECT_REF:
4970     case COMPONENT_REF:
4971       /* If there's no type, then this thing must be some expression
4972          involving template parameters.  */
4973       if (!fn && !TREE_TYPE (t))
4974         return error_mark_node;
4975       break;
4976
4977     case MODOP_EXPR:
4978     case CAST_EXPR:
4979     case REINTERPRET_CAST_EXPR:
4980     case CONST_CAST_EXPR:
4981     case STATIC_CAST_EXPR:
4982     case DYNAMIC_CAST_EXPR:
4983     case ARROW_EXPR:
4984     case DOTSTAR_EXPR:
4985     case TYPEID_EXPR:
4986     case PSEUDO_DTOR_EXPR:
4987       if (!fn)
4988         return error_mark_node;
4989       break;
4990
4991     case BASELINK:
4992       /* If we do not handle this case specially, we end up walking
4993          the BINFO hierarchy, which is circular, and therefore
4994          confuses walk_tree.  */
4995       *walk_subtrees = 0;
4996       if (for_each_template_parm (BASELINK_FUNCTIONS (*tp), fn, data,
4997                                   pfd->visited))
4998         return error_mark_node;
4999       break;
5000
5001     default:
5002       break;
5003     }
5004
5005   /* We didn't find any template parameters we liked.  */
5006   return NULL_TREE;
5007 }
5008
5009 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
5010    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
5011    call FN with the parameter and the DATA.
5012    If FN returns nonzero, the iteration is terminated, and
5013    for_each_template_parm returns 1.  Otherwise, the iteration
5014    continues.  If FN never returns a nonzero value, the value
5015    returned by for_each_template_parm is 0.  If FN is NULL, it is
5016    considered to be the function which always returns 1.  */
5017
5018 static int
5019 for_each_template_parm (tree t, tree_fn_t fn, void* data,
5020                         struct pointer_set_t *visited)
5021 {
5022   struct pair_fn_data pfd;
5023   int result;
5024
5025   /* Set up.  */
5026   pfd.fn = fn;
5027   pfd.data = data;
5028
5029   /* Walk the tree.  (Conceptually, we would like to walk without
5030      duplicates, but for_each_template_parm_r recursively calls
5031      for_each_template_parm, so we would need to reorganize a fair
5032      bit to use walk_tree_without_duplicates, so we keep our own
5033      visited list.)  */
5034   if (visited)
5035     pfd.visited = visited;
5036   else
5037     pfd.visited = pointer_set_create ();
5038   result = walk_tree (&t,
5039                       for_each_template_parm_r,
5040                       &pfd,
5041                       pfd.visited) != NULL_TREE;
5042
5043   /* Clean up.  */
5044   if (!visited)
5045     {
5046       pointer_set_destroy (pfd.visited);
5047       pfd.visited = 0;
5048     }
5049
5050   return result;
5051 }
5052
5053 /* Returns true if T depends on any template parameter.  */
5054
5055 int
5056 uses_template_parms (tree t)
5057 {
5058   bool dependent_p;
5059   int saved_processing_template_decl;
5060
5061   saved_processing_template_decl = processing_template_decl;
5062   if (!saved_processing_template_decl)
5063     processing_template_decl = 1;
5064   if (TYPE_P (t))
5065     dependent_p = dependent_type_p (t);
5066   else if (TREE_CODE (t) == TREE_VEC)
5067     dependent_p = any_dependent_template_arguments_p (t);
5068   else if (TREE_CODE (t) == TREE_LIST)
5069     dependent_p = (uses_template_parms (TREE_VALUE (t))
5070                    || uses_template_parms (TREE_CHAIN (t)));
5071   else if (TREE_CODE (t) == TYPE_DECL)
5072     dependent_p = dependent_type_p (TREE_TYPE (t));
5073   else if (DECL_P (t)
5074            || EXPR_P (t)
5075            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
5076            || TREE_CODE (t) == OVERLOAD
5077            || TREE_CODE (t) == BASELINK
5078            || TREE_CODE (t) == IDENTIFIER_NODE
5079            || CONSTANT_CLASS_P (t))
5080     dependent_p = (type_dependent_expression_p (t)
5081                    || value_dependent_expression_p (t));
5082   else
5083     {
5084       gcc_assert (t == error_mark_node);
5085       dependent_p = false;
5086     }
5087
5088   processing_template_decl = saved_processing_template_decl;
5089
5090   return dependent_p;
5091 }
5092
5093 /* Returns true if T depends on any template parameter with level LEVEL.  */
5094
5095 int
5096 uses_template_parms_level (tree t, int level)
5097 {
5098   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL);
5099 }
5100
5101 static int tinst_depth;
5102 extern int max_tinst_depth;
5103 #ifdef GATHER_STATISTICS
5104 int depth_reached;
5105 #endif
5106 static int tinst_level_tick;
5107 static int last_template_error_tick;
5108
5109 /* We're starting to instantiate D; record the template instantiation context
5110    for diagnostics and to restore it later.  */
5111
5112 int
5113 push_tinst_level (tree d)
5114 {
5115   tree new;
5116
5117   if (tinst_depth >= max_tinst_depth)
5118     {
5119       /* If the instantiation in question still has unbound template parms,
5120          we don't really care if we can't instantiate it, so just return.
5121          This happens with base instantiation for implicit `typename'.  */
5122       if (uses_template_parms (d))
5123         return 0;
5124
5125       last_template_error_tick = tinst_level_tick;
5126       error ("template instantiation depth exceeds maximum of %d (use "
5127              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
5128              max_tinst_depth, d);
5129
5130       print_instantiation_context ();
5131
5132       return 0;
5133     }
5134
5135   new = make_node (TINST_LEVEL);
5136   TINST_DECL (new) = d;
5137   TINST_LOCATION (new) = input_location;
5138   TINST_IN_SYSTEM_HEADER_P (new) = in_system_header;
5139   TREE_CHAIN (new) = current_tinst_level;
5140   current_tinst_level = new;
5141
5142   ++tinst_depth;
5143 #ifdef GATHER_STATISTICS
5144   if (tinst_depth > depth_reached)
5145     depth_reached = tinst_depth;
5146 #endif
5147
5148   ++tinst_level_tick;
5149   return 1;
5150 }
5151
5152 /* We're done instantiating this template; return to the instantiation
5153    context.  */
5154
5155 void
5156 pop_tinst_level (void)
5157 {
5158   tree old = current_tinst_level;
5159
5160   /* Restore the filename and line number stashed away when we started
5161      this instantiation.  */
5162   input_location = TINST_LOCATION (old);
5163   in_system_header = TINST_IN_SYSTEM_HEADER_P (old);
5164   current_tinst_level = TREE_CHAIN (old);
5165   --tinst_depth;
5166   ++tinst_level_tick;
5167 }
5168
5169 /* We're instantiating a deferred template; restore the template
5170    instantiation context in which the instantiation was requested, which
5171    is one step out from LEVEL.  */
5172
5173 static void
5174 reopen_tinst_level (tree level)
5175 {
5176   tree t;
5177
5178   tinst_depth = 0;
5179   for (t = level; t; t = TREE_CHAIN (t))
5180     ++tinst_depth;
5181
5182   current_tinst_level = level;
5183   pop_tinst_level ();
5184 }
5185
5186 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
5187    vector of template arguments, as for tsubst.
5188
5189    Returns an appropriate tsubst'd friend declaration.  */
5190
5191 static tree
5192 tsubst_friend_function (tree decl, tree args)
5193 {
5194   tree new_friend;
5195
5196   if (TREE_CODE (decl) == FUNCTION_DECL
5197       && DECL_TEMPLATE_INSTANTIATION (decl)
5198       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
5199     /* This was a friend declared with an explicit template
5200        argument list, e.g.:
5201
5202        friend void f<>(T);
5203
5204        to indicate that f was a template instantiation, not a new
5205        function declaration.  Now, we have to figure out what
5206        instantiation of what template.  */
5207     {
5208       tree template_id, arglist, fns;
5209       tree new_args;
5210       tree tmpl;
5211       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
5212
5213       /* Friend functions are looked up in the containing namespace scope.
5214          We must enter that scope, to avoid finding member functions of the
5215          current cless with same name.  */
5216       push_nested_namespace (ns);
5217       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
5218                          tf_error | tf_warning, NULL_TREE);
5219       pop_nested_namespace (ns);
5220       arglist = tsubst (DECL_TI_ARGS (decl), args,
5221                         tf_error | tf_warning, NULL_TREE);
5222       template_id = lookup_template_function (fns, arglist);
5223
5224       new_friend = tsubst (decl, args, tf_error | tf_warning, NULL_TREE);
5225       tmpl = determine_specialization (template_id, new_friend,
5226                                        &new_args,
5227                                        /*need_member_template=*/0,
5228                                        TREE_VEC_LENGTH (args),
5229                                        tsk_none);
5230       return instantiate_template (tmpl, new_args, tf_error);
5231     }
5232
5233   new_friend = tsubst (decl, args, tf_error | tf_warning, NULL_TREE);
5234
5235   /* The NEW_FRIEND will look like an instantiation, to the
5236      compiler, but is not an instantiation from the point of view of
5237      the language.  For example, we might have had:
5238
5239      template <class T> struct S {
5240        template <class U> friend void f(T, U);
5241      };
5242
5243      Then, in S<int>, template <class U> void f(int, U) is not an
5244      instantiation of anything.  */
5245   if (new_friend == error_mark_node)
5246     return error_mark_node;
5247
5248   DECL_USE_TEMPLATE (new_friend) = 0;
5249   if (TREE_CODE (decl) == TEMPLATE_DECL)
5250     {
5251       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
5252       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
5253         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
5254     }
5255
5256   /* The mangled name for the NEW_FRIEND is incorrect.  The function
5257      is not a template instantiation and should not be mangled like
5258      one.  Therefore, we forget the mangling here; we'll recompute it
5259      later if we need it.  */
5260   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
5261     {
5262       SET_DECL_RTL (new_friend, NULL_RTX);
5263       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
5264     }
5265
5266   if (DECL_NAMESPACE_SCOPE_P (new_friend))
5267     {
5268       tree old_decl;
5269       tree new_friend_template_info;
5270       tree new_friend_result_template_info;
5271       tree ns;
5272       int  new_friend_is_defn;
5273
5274       /* We must save some information from NEW_FRIEND before calling
5275          duplicate decls since that function will free NEW_FRIEND if
5276          possible.  */
5277       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
5278       new_friend_is_defn =
5279             (DECL_INITIAL (DECL_TEMPLATE_RESULT
5280                            (template_for_substitution (new_friend)))
5281              != NULL_TREE);
5282       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
5283         {
5284           /* This declaration is a `primary' template.  */
5285           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
5286
5287           new_friend_result_template_info
5288             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
5289         }
5290       else
5291         new_friend_result_template_info = NULL_TREE;
5292
5293       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
5294       if (new_friend_is_defn)
5295         DECL_INITIAL (new_friend) = error_mark_node;
5296
5297       /* Inside pushdecl_namespace_level, we will push into the
5298          current namespace. However, the friend function should go
5299          into the namespace of the template.  */
5300       ns = decl_namespace_context (new_friend);
5301       push_nested_namespace (ns);
5302       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
5303       pop_nested_namespace (ns);
5304
5305       if (old_decl != new_friend)
5306         {
5307           /* This new friend declaration matched an existing
5308              declaration.  For example, given:
5309
5310                template <class T> void f(T);
5311                template <class U> class C {
5312                  template <class T> friend void f(T) {}
5313                };
5314
5315              the friend declaration actually provides the definition
5316              of `f', once C has been instantiated for some type.  So,
5317              old_decl will be the out-of-class template declaration,
5318              while new_friend is the in-class definition.
5319
5320              But, if `f' was called before this point, the
5321              instantiation of `f' will have DECL_TI_ARGS corresponding
5322              to `T' but not to `U', references to which might appear
5323              in the definition of `f'.  Previously, the most general
5324              template for an instantiation of `f' was the out-of-class
5325              version; now it is the in-class version.  Therefore, we
5326              run through all specialization of `f', adding to their
5327              DECL_TI_ARGS appropriately.  In particular, they need a
5328              new set of outer arguments, corresponding to the
5329              arguments for this class instantiation.
5330
5331              The same situation can arise with something like this:
5332
5333                friend void f(int);
5334                template <class T> class C {
5335                  friend void f(T) {}
5336                };
5337
5338              when `C<int>' is instantiated.  Now, `f(int)' is defined
5339              in the class.  */
5340
5341           if (!new_friend_is_defn)
5342             /* On the other hand, if the in-class declaration does
5343                *not* provide a definition, then we don't want to alter
5344                existing definitions.  We can just leave everything
5345                alone.  */
5346             ;
5347           else
5348             {
5349               /* Overwrite whatever template info was there before, if
5350                  any, with the new template information pertaining to
5351                  the declaration.  */
5352               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
5353
5354               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
5355                 reregister_specialization (new_friend,
5356                                            most_general_template (old_decl),
5357                                            old_decl);
5358               else
5359                 {
5360                   tree t;
5361                   tree new_friend_args;
5362
5363                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
5364                     = new_friend_result_template_info;
5365
5366                   new_friend_args = TI_ARGS (new_friend_template_info);
5367                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
5368                        t != NULL_TREE;
5369                        t = TREE_CHAIN (t))
5370                     {
5371                       tree spec = TREE_VALUE (t);
5372
5373                       DECL_TI_ARGS (spec)
5374                         = add_outermost_template_args (new_friend_args,
5375                                                        DECL_TI_ARGS (spec));
5376                     }
5377
5378                   /* Now, since specializations are always supposed to
5379                      hang off of the most general template, we must move
5380                      them.  */
5381                   t = most_general_template (old_decl);
5382                   if (t != old_decl)
5383                     {
5384                       DECL_TEMPLATE_SPECIALIZATIONS (t)
5385                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
5386                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
5387                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
5388                     }
5389                 }
5390             }
5391
5392           /* The information from NEW_FRIEND has been merged into OLD_DECL
5393              by duplicate_decls.  */
5394           new_friend = old_decl;
5395         }
5396     }
5397   else
5398     {
5399       tree context = DECL_CONTEXT (new_friend);
5400       bool dependent_p;
5401
5402       /* In the code
5403            template <class T> class C {
5404              template <class U> friend void C1<U>::f (); // case 1
5405              friend void C2<T>::f ();                    // case 2
5406            };
5407          we only need to make sure CONTEXT is a complete type for
5408          case 2.  To distinguish between the two cases, we note that
5409          CONTEXT of case 1 remains dependent type after tsubst while
5410          this isn't true for case 2.  */
5411       ++processing_template_decl;
5412       dependent_p = dependent_type_p (context);
5413       --processing_template_decl;
5414
5415       if (!dependent_p
5416           && !complete_type_or_else (context, NULL_TREE))
5417         return error_mark_node;
5418
5419       if (COMPLETE_TYPE_P (context))
5420         {
5421           /* Check to see that the declaration is really present, and,
5422              possibly obtain an improved declaration.  */
5423           tree fn = check_classfn (context,
5424                                    new_friend, NULL_TREE);
5425
5426           if (fn)
5427             new_friend = fn;
5428         }
5429     }
5430
5431   return new_friend;
5432 }
5433
5434 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
5435    template arguments, as for tsubst.
5436
5437    Returns an appropriate tsubst'd friend type or error_mark_node on
5438    failure.  */
5439
5440 static tree
5441 tsubst_friend_class (tree friend_tmpl, tree args)
5442 {
5443   tree friend_type;
5444   tree tmpl;
5445   tree context;
5446
5447   context = DECL_CONTEXT (friend_tmpl);
5448
5449   if (context)
5450     {
5451       if (TREE_CODE (context) == NAMESPACE_DECL)
5452         push_nested_namespace (context);
5453       else
5454         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
5455     }
5456
5457   /* Look for a class template declaration.  We look for hidden names
5458      because two friend declarations of the same template are the
5459      same.  For example, in:
5460
5461        struct A { 
5462          template <typename> friend class F;
5463        };
5464        template <typename> struct B { 
5465          template <typename> friend class F;
5466        };
5467
5468      both F templates are the same.  */
5469   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
5470                            /*block_p=*/true, 0, 
5471                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
5472
5473   /* But, if we don't find one, it might be because we're in a
5474      situation like this:
5475
5476        template <class T>
5477        struct S {
5478          template <class U>
5479          friend struct S;
5480        };
5481
5482      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
5483      for `S<int>', not the TEMPLATE_DECL.  */
5484   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
5485     {
5486       tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/1);
5487       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
5488     }
5489
5490   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
5491     {
5492       /* The friend template has already been declared.  Just
5493          check to see that the declarations match, and install any new
5494          default parameters.  We must tsubst the default parameters,
5495          of course.  We only need the innermost template parameters
5496          because that is all that redeclare_class_template will look
5497          at.  */
5498       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
5499           > TMPL_ARGS_DEPTH (args))
5500         {
5501           tree parms;
5502           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
5503                                          args, tf_error | tf_warning);
5504           redeclare_class_template (TREE_TYPE (tmpl), parms);
5505         }
5506
5507       friend_type = TREE_TYPE (tmpl);
5508     }
5509   else
5510     {
5511       /* The friend template has not already been declared.  In this
5512          case, the instantiation of the template class will cause the
5513          injection of this template into the global scope.  */
5514       tmpl = tsubst (friend_tmpl, args, tf_error | tf_warning, NULL_TREE);
5515
5516       /* The new TMPL is not an instantiation of anything, so we
5517          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
5518          the new type because that is supposed to be the corresponding
5519          template decl, i.e., TMPL.  */
5520       DECL_USE_TEMPLATE (tmpl) = 0;
5521       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
5522       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
5523       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
5524         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
5525
5526       /* Inject this template into the global scope.  */
5527       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
5528     }
5529
5530   if (context)
5531     {
5532       if (TREE_CODE (context) == NAMESPACE_DECL)
5533         pop_nested_namespace (context);
5534       else
5535         pop_nested_class ();
5536     }
5537
5538   return friend_type;
5539 }
5540
5541 /* Returns zero if TYPE cannot be completed later due to circularity.
5542    Otherwise returns one.  */
5543
5544 static int
5545 can_complete_type_without_circularity (tree type)
5546 {
5547   if (type == NULL_TREE || type == error_mark_node)
5548     return 0;
5549   else if (COMPLETE_TYPE_P (type))
5550     return 1;
5551   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
5552     return can_complete_type_without_circularity (TREE_TYPE (type));
5553   else if (CLASS_TYPE_P (type)
5554            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
5555     return 0;
5556   else
5557     return 1;
5558 }
5559
5560 tree
5561 instantiate_class_template (tree type)
5562 {
5563   tree template, args, pattern, t, member;
5564   tree typedecl;
5565   tree pbinfo;
5566   tree base_list;
5567
5568   if (type == error_mark_node)
5569     return error_mark_node;
5570
5571   if (TYPE_BEING_DEFINED (type)
5572       || COMPLETE_TYPE_P (type)
5573       || dependent_type_p (type))
5574     return type;
5575
5576   /* Figure out which template is being instantiated.  */
5577   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
5578   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
5579
5580   /* Determine what specialization of the original template to
5581      instantiate.  */
5582   t = most_specialized_class (type, template);
5583   if (t == error_mark_node)
5584     {
5585       TYPE_BEING_DEFINED (type) = 1;
5586       return error_mark_node;
5587     }
5588   else if (t)
5589     {
5590       /* This TYPE is actually an instantiation of a partial
5591          specialization.  We replace the innermost set of ARGS with
5592          the arguments appropriate for substitution.  For example,
5593          given:
5594        
5595            template <class T> struct S {};
5596            template <class T> struct S<T*> {};
5597
5598          and supposing that we are instantiating S<int*>, ARGS will
5599          presently be {int*} -- but we need {int}.  */
5600       pattern = TREE_TYPE (t);
5601       args = TREE_PURPOSE (t);
5602     }
5603   else
5604     {
5605       pattern = TREE_TYPE (template);
5606       args = CLASSTYPE_TI_ARGS (type);
5607     }
5608
5609   /* If the template we're instantiating is incomplete, then clearly
5610      there's nothing we can do.  */
5611   if (!COMPLETE_TYPE_P (pattern))
5612     return type;
5613
5614   /* If we've recursively instantiated too many templates, stop.  */
5615   if (! push_tinst_level (type))
5616     return type;
5617
5618   /* Now we're really doing the instantiation.  Mark the type as in
5619      the process of being defined.  */
5620   TYPE_BEING_DEFINED (type) = 1;
5621
5622   /* We may be in the middle of deferred access check.  Disable
5623      it now.  */
5624   push_deferring_access_checks (dk_no_deferred);
5625
5626   push_to_top_level ();
5627
5628   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
5629
5630   /* Set the input location to the template definition. This is needed
5631      if tsubsting causes an error.  */
5632   typedecl = TYPE_MAIN_DECL (type);
5633   input_location = DECL_SOURCE_LOCATION (typedecl);
5634   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
5635
5636   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
5637   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
5638   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
5639   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
5640   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
5641   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
5642   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
5643   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
5644   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
5645   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
5646   TYPE_PACKED (type) = TYPE_PACKED (pattern);
5647   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
5648   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
5649   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
5650   if (ANON_AGGR_TYPE_P (pattern))
5651     SET_ANON_AGGR_TYPE_P (type);
5652   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
5653     {
5654       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
5655       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
5656     }
5657
5658   pbinfo = TYPE_BINFO (pattern);
5659
5660   /* We should never instantiate a nested class before its enclosing
5661      class; we need to look up the nested class by name before we can
5662      instantiate it, and that lookup should instantiate the enclosing
5663      class.  */
5664   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
5665               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
5666               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
5667
5668   base_list = NULL_TREE;
5669   if (BINFO_N_BASE_BINFOS (pbinfo))
5670     {
5671       tree pbase_binfo;
5672       tree context = TYPE_CONTEXT (type);
5673       tree pushed_scope;
5674       int i;
5675
5676       /* We must enter the scope containing the type, as that is where
5677          the accessibility of types named in dependent bases are
5678          looked up from.  */
5679       pushed_scope = push_scope (context ? context : global_namespace);
5680
5681       /* Substitute into each of the bases to determine the actual
5682          basetypes.  */
5683       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
5684         {
5685           tree base;
5686           tree access = BINFO_BASE_ACCESS (pbinfo, i);
5687
5688           /* Substitute to figure out the base class.  */
5689           base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, NULL_TREE);
5690           if (base == error_mark_node)
5691             continue;
5692
5693           base_list = tree_cons (access, base, base_list);
5694           if (BINFO_VIRTUAL_P (pbase_binfo))
5695             TREE_TYPE (base_list) = integer_type_node;
5696         }
5697
5698       /* The list is now in reverse order; correct that.  */
5699       base_list = nreverse (base_list);
5700
5701       if (pushed_scope)
5702         pop_scope (pushed_scope);
5703     }
5704   /* Now call xref_basetypes to set up all the base-class
5705      information.  */
5706   xref_basetypes (type, base_list);
5707
5708
5709   /* Now that our base classes are set up, enter the scope of the
5710      class, so that name lookups into base classes, etc. will work
5711      correctly.  This is precisely analogous to what we do in
5712      begin_class_definition when defining an ordinary non-template
5713      class.  */
5714   pushclass (type);
5715
5716   /* Now members are processed in the order of declaration.  */
5717   for (member = CLASSTYPE_DECL_LIST (pattern);
5718        member; member = TREE_CHAIN (member))
5719     {
5720       tree t = TREE_VALUE (member);
5721
5722       if (TREE_PURPOSE (member))
5723         {
5724           if (TYPE_P (t))
5725             {
5726               /* Build new CLASSTYPE_NESTED_UTDS.  */
5727
5728               tree tag = t;
5729               tree name = TYPE_IDENTIFIER (tag);
5730               tree newtag;
5731               bool class_template_p;
5732
5733               class_template_p = (TREE_CODE (tag) != ENUMERAL_TYPE
5734                                   && TYPE_LANG_SPECIFIC (tag)
5735                                   && CLASSTYPE_IS_TEMPLATE (tag));
5736               /* If the member is a class template, then -- even after
5737                  substitution -- there may be dependent types in the
5738                  template argument list for the class.  We increment
5739                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
5740                  that function will assume that no types are dependent
5741                  when outside of a template.  */
5742               if (class_template_p)
5743                 ++processing_template_decl;
5744               newtag = tsubst (tag, args, tf_error, NULL_TREE);
5745               if (class_template_p)
5746                 --processing_template_decl;
5747               if (newtag == error_mark_node)
5748                 continue;
5749
5750               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
5751                 {
5752                   if (class_template_p)
5753                     /* Unfortunately, lookup_template_class sets
5754                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
5755                        instantiation (i.e., for the type of a member
5756                        template class nested within a template class.)
5757                        This behavior is required for
5758                        maybe_process_partial_specialization to work
5759                        correctly, but is not accurate in this case;
5760                        the TAG is not an instantiation of anything.
5761                        (The corresponding TEMPLATE_DECL is an
5762                        instantiation, but the TYPE is not.) */
5763                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
5764
5765                   /* Now, we call pushtag to put this NEWTAG into the scope of
5766                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
5767                      pushtag calling push_template_decl.  We don't have to do
5768                      this for enums because it will already have been done in
5769                      tsubst_enum.  */
5770                   if (name)
5771                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
5772                   pushtag (name, newtag, /*tag_scope=*/ts_current);
5773                 }
5774             }
5775           else if (TREE_CODE (t) == FUNCTION_DECL
5776                    || DECL_FUNCTION_TEMPLATE_P (t))
5777             {
5778               /* Build new TYPE_METHODS.  */
5779               tree r;
5780
5781               if (TREE_CODE (t) == TEMPLATE_DECL)
5782                 ++processing_template_decl;
5783               r = tsubst (t, args, tf_error, NULL_TREE);
5784               if (TREE_CODE (t) == TEMPLATE_DECL)
5785                 --processing_template_decl;
5786               set_current_access_from_decl (r);
5787               grok_special_member_properties (r);
5788               finish_member_declaration (r);
5789             }
5790           else
5791             {
5792               /* Build new TYPE_FIELDS.  */
5793
5794               if (TREE_CODE (t) != CONST_DECL)
5795                 {
5796                   tree r;
5797
5798                   /* The the file and line for this declaration, to
5799                      assist in error message reporting.  Since we
5800                      called push_tinst_level above, we don't need to
5801                      restore these.  */
5802                   input_location = DECL_SOURCE_LOCATION (t);
5803
5804                   if (TREE_CODE (t) == TEMPLATE_DECL)
5805                     ++processing_template_decl;
5806                   r = tsubst (t, args, tf_error | tf_warning, NULL_TREE);
5807                   if (TREE_CODE (t) == TEMPLATE_DECL)
5808                     --processing_template_decl;
5809                   if (TREE_CODE (r) == VAR_DECL)
5810                     {
5811                       /* In [temp.inst]:
5812
5813                            [t]he initialization (and any associated
5814                            side-effects) of a static data member does
5815                            not occur unless the static data member is
5816                            itself used in a way that requires the
5817                            definition of the static data member to
5818                            exist.  
5819
5820                          Therefore, we do not substitute into the
5821                          initialized for the static data member here.  */
5822                       finish_static_data_member_decl 
5823                         (r, 
5824                          /*init=*/NULL_TREE, 
5825                          /*init_const_expr_p=*/false,
5826                          /*asmspec_tree=*/NULL_TREE, 
5827                          /*flags=*/0);
5828                       if (DECL_INITIALIZED_IN_CLASS_P (r))
5829                         check_static_variable_definition (r, TREE_TYPE (r));
5830                     }
5831                   else if (TREE_CODE (r) == FIELD_DECL)
5832                     {
5833                       /* Determine whether R has a valid type and can be
5834                          completed later.  If R is invalid, then it is
5835                          replaced by error_mark_node so that it will not be
5836                          added to TYPE_FIELDS.  */
5837                       tree rtype = TREE_TYPE (r);
5838                       if (can_complete_type_without_circularity (rtype))
5839                         complete_type (rtype);
5840
5841                       if (!COMPLETE_TYPE_P (rtype))
5842                         {
5843                           cxx_incomplete_type_error (r, rtype);
5844                           r = error_mark_node;
5845                         }
5846                     }
5847
5848                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
5849                      such a thing will already have been added to the field
5850                      list by tsubst_enum in finish_member_declaration in the
5851                      CLASSTYPE_NESTED_UTDS case above.  */
5852                   if (!(TREE_CODE (r) == TYPE_DECL
5853                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
5854                         && DECL_ARTIFICIAL (r)))
5855                     {
5856                       set_current_access_from_decl (r);
5857                       finish_member_declaration (r);
5858                     }
5859                 }
5860             }
5861         }
5862       else
5863         {
5864           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
5865             {
5866               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
5867
5868               tree friend_type = t;
5869               bool adjust_processing_template_decl = false;
5870
5871               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5872                 {
5873                   /* template <class T> friend class C;  */
5874                   friend_type = tsubst_friend_class (friend_type, args);
5875                   adjust_processing_template_decl = true;
5876                 }
5877               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
5878                 {
5879                   /* template <class T> friend class C::D;  */
5880                   friend_type = tsubst (friend_type, args,
5881                                         tf_error | tf_warning, NULL_TREE);
5882                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5883                     friend_type = TREE_TYPE (friend_type);
5884                   adjust_processing_template_decl = true;
5885                 }
5886               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
5887                 {
5888                   /* This could be either
5889
5890                        friend class T::C;
5891
5892                      when dependent_type_p is false or
5893
5894                        template <class U> friend class T::C;
5895
5896                      otherwise.  */
5897                   friend_type = tsubst (friend_type, args,
5898                                         tf_error | tf_warning, NULL_TREE);
5899                   /* Bump processing_template_decl for correct
5900                      dependent_type_p calculation.  */
5901                   ++processing_template_decl;
5902                   if (dependent_type_p (friend_type))
5903                     adjust_processing_template_decl = true;
5904                   --processing_template_decl;
5905                 }
5906               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
5907                        && hidden_name_p (TYPE_NAME (friend_type)))
5908                 {
5909                   /* friend class C;
5910
5911                      where C hasn't been declared yet.  Let's lookup name
5912                      from namespace scope directly, bypassing any name that
5913                      come from dependent base class.  */
5914                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
5915
5916                   /* The call to xref_tag_from_type does injection for friend
5917                      classes.  */
5918                   push_nested_namespace (ns);
5919                   friend_type =
5920                     xref_tag_from_type (friend_type, NULL_TREE,
5921                                         /*tag_scope=*/ts_current);
5922                   pop_nested_namespace (ns);
5923                 }
5924               else if (uses_template_parms (friend_type))
5925                 /* friend class C<T>;  */
5926                 friend_type = tsubst (friend_type, args,
5927                                       tf_error | tf_warning, NULL_TREE);
5928               /* Otherwise it's
5929
5930                    friend class C;
5931
5932                  where C is already declared or
5933
5934                    friend class C<int>;
5935
5936                  We don't have to do anything in these cases.  */
5937
5938               if (adjust_processing_template_decl)
5939                 /* Trick make_friend_class into realizing that the friend
5940                    we're adding is a template, not an ordinary class.  It's
5941                    important that we use make_friend_class since it will
5942                    perform some error-checking and output cross-reference
5943                    information.  */
5944                 ++processing_template_decl;
5945
5946               if (friend_type != error_mark_node)
5947                 make_friend_class (type, friend_type, /*complain=*/false);
5948
5949               if (adjust_processing_template_decl)
5950                 --processing_template_decl;
5951             }
5952           else
5953             {
5954               /* Build new DECL_FRIENDLIST.  */
5955               tree r;
5956
5957               /* The the file and line for this declaration, to
5958                  assist in error message reporting.  Since we
5959                  called push_tinst_level above, we don't need to
5960                  restore these.  */
5961               input_location = DECL_SOURCE_LOCATION (t);
5962
5963               if (TREE_CODE (t) == TEMPLATE_DECL)
5964                 {
5965                   ++processing_template_decl;
5966                   push_deferring_access_checks (dk_no_check);
5967                 }
5968
5969               r = tsubst_friend_function (t, args);
5970               add_friend (type, r, /*complain=*/false);
5971               if (TREE_CODE (t) == TEMPLATE_DECL)
5972                 {
5973                   pop_deferring_access_checks ();
5974                   --processing_template_decl;
5975                 }
5976             }
5977         }
5978     }
5979
5980   /* Set the file and line number information to whatever is given for
5981      the class itself.  This puts error messages involving generated
5982      implicit functions at a predictable point, and the same point
5983      that would be used for non-template classes.  */
5984   input_location = DECL_SOURCE_LOCATION (typedecl);
5985
5986   unreverse_member_declarations (type);
5987   finish_struct_1 (type);
5988   TYPE_BEING_DEFINED (type) = 0;
5989
5990   /* Now that the class is complete, instantiate default arguments for
5991      any member functions.  We don't do this earlier because the
5992      default arguments may reference members of the class.  */
5993   if (!PRIMARY_TEMPLATE_P (template))
5994     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
5995       if (TREE_CODE (t) == FUNCTION_DECL
5996           /* Implicitly generated member functions will not have template
5997              information; they are not instantiations, but instead are
5998              created "fresh" for each instantiation.  */
5999           && DECL_TEMPLATE_INFO (t))
6000         tsubst_default_arguments (t);
6001
6002   popclass ();
6003   pop_from_top_level ();
6004   pop_deferring_access_checks ();
6005   pop_tinst_level ();
6006
6007   /* The vtable for a template class can be emitted in any translation
6008      unit in which the class is instantiated.  When there is no key
6009      method, however, finish_struct_1 will already have added TYPE to
6010      the keyed_classes list.  */
6011   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
6012     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
6013
6014   return type;
6015 }
6016
6017 static tree
6018 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
6019 {
6020   tree r;
6021
6022   if (!t)
6023     r = t;
6024   else if (TYPE_P (t))
6025     r = tsubst (t, args, complain, in_decl);
6026   else
6027     {
6028       r = tsubst_expr (t, args, complain, in_decl);
6029       r = fold_non_dependent_expr (r);
6030     }
6031   return r;
6032 }
6033
6034 /* Substitute ARGS into the vector or list of template arguments T.  */
6035
6036 static tree
6037 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
6038 {
6039   int len = TREE_VEC_LENGTH (t);
6040   int need_new = 0, i;
6041   tree *elts = alloca (len * sizeof (tree));
6042
6043   for (i = 0; i < len; i++)
6044     {
6045       tree orig_arg = TREE_VEC_ELT (t, i);
6046       tree new_arg;
6047
6048       if (TREE_CODE (orig_arg) == TREE_VEC)
6049         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
6050       else
6051         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
6052
6053       if (new_arg == error_mark_node)
6054         return error_mark_node;
6055
6056       elts[i] = new_arg;
6057       if (new_arg != orig_arg)
6058         need_new = 1;
6059     }
6060
6061   if (!need_new)
6062     return t;
6063
6064   t = make_tree_vec (len);
6065   for (i = 0; i < len; i++)
6066     TREE_VEC_ELT (t, i) = elts[i];
6067
6068   return t;
6069 }
6070
6071 /* Return the result of substituting ARGS into the template parameters
6072    given by PARMS.  If there are m levels of ARGS and m + n levels of
6073    PARMS, then the result will contain n levels of PARMS.  For
6074    example, if PARMS is `template <class T> template <class U>
6075    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
6076    result will be `template <int*, double, class V>'.  */
6077
6078 static tree
6079 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
6080 {
6081   tree r = NULL_TREE;
6082   tree* new_parms;
6083
6084   /* When substituting into a template, we must set
6085      PROCESSING_TEMPLATE_DECL as the template parameters may be
6086      dependent if they are based on one-another, and the dependency
6087      predicates are short-circuit outside of templates.  */
6088   ++processing_template_decl;
6089
6090   for (new_parms = &r;
6091        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
6092        new_parms = &(TREE_CHAIN (*new_parms)),
6093          parms = TREE_CHAIN (parms))
6094     {
6095       tree new_vec =
6096         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
6097       int i;
6098
6099       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
6100         {
6101           tree tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
6102           tree default_value = TREE_PURPOSE (tuple);
6103           tree parm_decl = TREE_VALUE (tuple);
6104
6105           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
6106           if (TREE_CODE (parm_decl) == PARM_DECL
6107               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
6108             parm_decl = error_mark_node;
6109           default_value = tsubst_template_arg (default_value, args,
6110                                                complain, NULL_TREE);
6111
6112           tuple = build_tree_list (default_value, parm_decl);
6113           TREE_VEC_ELT (new_vec, i) = tuple;
6114         }
6115
6116       *new_parms =
6117         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
6118                              - TMPL_ARGS_DEPTH (args)),
6119                    new_vec, NULL_TREE);
6120     }
6121
6122   --processing_template_decl;
6123
6124   return r;
6125 }
6126
6127 /* Substitute the ARGS into the indicated aggregate (or enumeration)
6128    type T.  If T is not an aggregate or enumeration type, it is
6129    handled as if by tsubst.  IN_DECL is as for tsubst.  If
6130    ENTERING_SCOPE is nonzero, T is the context for a template which
6131    we are presently tsubst'ing.  Return the substituted value.  */
6132
6133 static tree
6134 tsubst_aggr_type (tree t,
6135                   tree args,
6136                   tsubst_flags_t complain,
6137                   tree in_decl,
6138                   int entering_scope)
6139 {
6140   if (t == NULL_TREE)
6141     return NULL_TREE;
6142
6143   switch (TREE_CODE (t))
6144     {
6145     case RECORD_TYPE:
6146       if (TYPE_PTRMEMFUNC_P (t))
6147         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
6148
6149       /* Else fall through.  */
6150     case ENUMERAL_TYPE:
6151     case UNION_TYPE:
6152       if (TYPE_TEMPLATE_INFO (t))
6153         {
6154           tree argvec;
6155           tree context;
6156           tree r;
6157           bool saved_skip_evaluation;
6158
6159           /* In "sizeof(X<I>)" we need to evaluate "I".  */
6160           saved_skip_evaluation = skip_evaluation;
6161           skip_evaluation = false;
6162
6163           /* First, determine the context for the type we are looking
6164              up.  */
6165           context = TYPE_CONTEXT (t);
6166           if (context)
6167             context = tsubst_aggr_type (context, args, complain,
6168                                         in_decl, /*entering_scope=*/1);
6169
6170           /* Then, figure out what arguments are appropriate for the
6171              type we are trying to find.  For example, given:
6172
6173                template <class T> struct S;
6174                template <class T, class U> void f(T, U) { S<U> su; }
6175
6176              and supposing that we are instantiating f<int, double>,
6177              then our ARGS will be {int, double}, but, when looking up
6178              S we only want {double}.  */
6179           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
6180                                          complain, in_decl);
6181           if (argvec == error_mark_node)
6182             r = error_mark_node;
6183           else
6184             {
6185               r = lookup_template_class (t, argvec, in_decl, context,
6186                                          entering_scope, complain);
6187               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
6188             }
6189           
6190           skip_evaluation = saved_skip_evaluation;
6191
6192           return r;
6193         }
6194       else
6195         /* This is not a template type, so there's nothing to do.  */
6196         return t;
6197
6198     default:
6199       return tsubst (t, args, complain, in_decl);
6200     }
6201 }
6202
6203 /* Substitute into the default argument ARG (a default argument for
6204    FN), which has the indicated TYPE.  */
6205
6206 tree
6207 tsubst_default_argument (tree fn, tree type, tree arg)
6208 {
6209   tree saved_class_ptr = NULL_TREE;
6210   tree saved_class_ref = NULL_TREE;
6211
6212   /* This default argument came from a template.  Instantiate the
6213      default argument here, not in tsubst.  In the case of
6214      something like:
6215
6216        template <class T>
6217        struct S {
6218          static T t();
6219          void f(T = t());
6220        };
6221
6222      we must be careful to do name lookup in the scope of S<T>,
6223      rather than in the current class.  */
6224   push_access_scope (fn);
6225   /* The "this" pointer is not valid in a default argument.  */
6226   if (cfun)
6227     {
6228       saved_class_ptr = current_class_ptr;
6229       cp_function_chain->x_current_class_ptr = NULL_TREE;
6230       saved_class_ref = current_class_ref;
6231       cp_function_chain->x_current_class_ref = NULL_TREE;
6232     }
6233
6234   push_deferring_access_checks(dk_no_deferred);
6235   /* The default argument expression may cause implicitly defined
6236      member functions to be synthesized, which will result in garbage
6237      collection.  We must treat this situation as if we were within
6238      the body of function so as to avoid collecting live data on the
6239       stack.  */
6240   ++function_depth;
6241   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
6242                      tf_error | tf_warning, NULL_TREE);
6243   --function_depth;
6244   pop_deferring_access_checks();
6245
6246   /* Restore the "this" pointer.  */
6247   if (cfun)
6248     {
6249       cp_function_chain->x_current_class_ptr = saved_class_ptr;
6250       cp_function_chain->x_current_class_ref = saved_class_ref;
6251     }
6252
6253   pop_access_scope (fn);
6254
6255   /* Make sure the default argument is reasonable.  */
6256   arg = check_default_argument (type, arg);
6257
6258   return arg;
6259 }
6260
6261 /* Substitute into all the default arguments for FN.  */
6262
6263 static void
6264 tsubst_default_arguments (tree fn)
6265 {
6266   tree arg;
6267   tree tmpl_args;
6268
6269   tmpl_args = DECL_TI_ARGS (fn);
6270
6271   /* If this function is not yet instantiated, we certainly don't need
6272      its default arguments.  */
6273   if (uses_template_parms (tmpl_args))
6274     return;
6275
6276   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
6277        arg;
6278        arg = TREE_CHAIN (arg))
6279     if (TREE_PURPOSE (arg))
6280       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
6281                                                     TREE_VALUE (arg),
6282                                                     TREE_PURPOSE (arg));
6283 }
6284
6285 /* Substitute the ARGS into the T, which is a _DECL.  Return the
6286    result of the substitution.  Issue error and warning messages under
6287    control of COMPLAIN.  */
6288
6289 static tree
6290 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
6291 {
6292   location_t saved_loc;
6293   tree r = NULL_TREE;
6294   tree in_decl = t;
6295
6296   /* Set the filename and linenumber to improve error-reporting.  */
6297   saved_loc = input_location;
6298   input_location = DECL_SOURCE_LOCATION (t);
6299
6300   switch (TREE_CODE (t))
6301     {
6302     case TEMPLATE_DECL:
6303       {
6304         /* We can get here when processing a member function template,
6305            member class template, and template template parameter of
6306            a template class.  */
6307         tree decl = DECL_TEMPLATE_RESULT (t);
6308         tree spec;
6309         tree tmpl_args;
6310         tree full_args;
6311
6312         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
6313           {
6314             /* Template template parameter is treated here.  */
6315             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6316             if (new_type == error_mark_node)
6317               return error_mark_node;
6318
6319             r = copy_decl (t);
6320             TREE_CHAIN (r) = NULL_TREE;
6321             TREE_TYPE (r) = new_type;
6322             DECL_TEMPLATE_RESULT (r)
6323               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
6324             DECL_TEMPLATE_PARMS (r)
6325               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
6326                                        complain);
6327             TYPE_NAME (new_type) = r;
6328             break;
6329           }
6330
6331         /* We might already have an instance of this template.
6332            The ARGS are for the surrounding class type, so the
6333            full args contain the tsubst'd args for the context,
6334            plus the innermost args from the template decl.  */
6335         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
6336           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
6337           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
6338         /* Because this is a template, the arguments will still be
6339            dependent, even after substitution.  If
6340            PROCESSING_TEMPLATE_DECL is not set, the dependency
6341            predicates will short-circuit.  */
6342         ++processing_template_decl;
6343         full_args = tsubst_template_args (tmpl_args, args,
6344                                           complain, in_decl);
6345         --processing_template_decl;
6346         if (full_args == error_mark_node)
6347           return error_mark_node;
6348
6349         /* tsubst_template_args doesn't copy the vector if
6350            nothing changed.  But, *something* should have
6351            changed.  */
6352         gcc_assert (full_args != tmpl_args);
6353
6354         spec = retrieve_specialization (t, full_args,
6355                                         /*class_specializations_p=*/true);
6356         if (spec != NULL_TREE)
6357           {
6358             r = spec;
6359             break;
6360           }
6361
6362         /* Make a new template decl.  It will be similar to the
6363            original, but will record the current template arguments.
6364            We also create a new function declaration, which is just
6365            like the old one, but points to this new template, rather
6366            than the old one.  */
6367         r = copy_decl (t);
6368         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
6369         TREE_CHAIN (r) = NULL_TREE;
6370
6371         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
6372
6373         if (TREE_CODE (decl) == TYPE_DECL)
6374           {
6375             tree new_type;
6376             ++processing_template_decl;
6377             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6378             --processing_template_decl; 
6379             if (new_type == error_mark_node)
6380               return error_mark_node;
6381
6382             TREE_TYPE (r) = new_type;
6383             CLASSTYPE_TI_TEMPLATE (new_type) = r;
6384             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
6385             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
6386             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
6387           }
6388         else
6389           {
6390             tree new_decl;
6391             ++processing_template_decl;
6392             new_decl = tsubst (decl, args, complain, in_decl);
6393             --processing_template_decl;
6394             if (new_decl == error_mark_node)
6395               return error_mark_node;
6396
6397             DECL_TEMPLATE_RESULT (r) = new_decl;
6398             DECL_TI_TEMPLATE (new_decl) = r;
6399             TREE_TYPE (r) = TREE_TYPE (new_decl);
6400             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
6401             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl); 
6402           }
6403
6404         SET_DECL_IMPLICIT_INSTANTIATION (r);
6405         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
6406         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
6407
6408         /* The template parameters for this new template are all the
6409            template parameters for the old template, except the
6410            outermost level of parameters.  */
6411         DECL_TEMPLATE_PARMS (r)
6412           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
6413                                    complain);
6414
6415         if (PRIMARY_TEMPLATE_P (t))
6416           DECL_PRIMARY_TEMPLATE (r) = r;
6417
6418         if (TREE_CODE (decl) != TYPE_DECL)
6419           /* Record this non-type partial instantiation.  */
6420           register_specialization (r, t,
6421                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
6422                                    false);
6423       }
6424       break;
6425
6426     case FUNCTION_DECL:
6427       {
6428         tree ctx;
6429         tree argvec = NULL_TREE;
6430         tree *friends;
6431         tree gen_tmpl;
6432         tree type;
6433         int member;
6434         int args_depth;
6435         int parms_depth;
6436
6437         /* Nobody should be tsubst'ing into non-template functions.  */
6438         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
6439
6440         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
6441           {
6442             tree spec;
6443             bool dependent_p;
6444
6445             /* If T is not dependent, just return it.  We have to
6446                increment PROCESSING_TEMPLATE_DECL because
6447                value_dependent_expression_p assumes that nothing is
6448                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
6449             ++processing_template_decl;
6450             dependent_p = value_dependent_expression_p (t);
6451             --processing_template_decl;
6452             if (!dependent_p)
6453               return t;
6454
6455             /* Calculate the most general template of which R is a
6456                specialization, and the complete set of arguments used to
6457                specialize R.  */
6458             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
6459             argvec = tsubst_template_args (DECL_TI_ARGS
6460                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
6461                                            args, complain, in_decl);
6462
6463             /* Check to see if we already have this specialization.  */
6464             spec = retrieve_specialization (gen_tmpl, argvec,
6465                                             /*class_specializations_p=*/false);
6466
6467             if (spec)
6468               {
6469                 r = spec;
6470                 break;
6471               }
6472
6473             /* We can see more levels of arguments than parameters if
6474                there was a specialization of a member template, like
6475                this:
6476
6477                  template <class T> struct S { template <class U> void f(); }
6478                  template <> template <class U> void S<int>::f(U);
6479
6480                Here, we'll be substituting into the specialization,
6481                because that's where we can find the code we actually
6482                want to generate, but we'll have enough arguments for
6483                the most general template.
6484
6485                We also deal with the peculiar case:
6486
6487                  template <class T> struct S {
6488                    template <class U> friend void f();
6489                  };
6490                  template <class U> void f() {}
6491                  template S<int>;
6492                  template void f<double>();
6493
6494                Here, the ARGS for the instantiation of will be {int,
6495                double}.  But, we only need as many ARGS as there are
6496                levels of template parameters in CODE_PATTERN.  We are
6497                careful not to get fooled into reducing the ARGS in
6498                situations like:
6499
6500                  template <class T> struct S { template <class U> void f(U); }
6501                  template <class T> template <> void S<T>::f(int) {}
6502
6503                which we can spot because the pattern will be a
6504                specialization in this case.  */
6505             args_depth = TMPL_ARGS_DEPTH (args);
6506             parms_depth =
6507               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
6508             if (args_depth > parms_depth
6509                 && !DECL_TEMPLATE_SPECIALIZATION (t))
6510               args = get_innermost_template_args (args, parms_depth);
6511           }
6512         else
6513           {
6514             /* This special case arises when we have something like this:
6515
6516                  template <class T> struct S {
6517                    friend void f<int>(int, double);
6518                  };
6519
6520                Here, the DECL_TI_TEMPLATE for the friend declaration
6521                will be an IDENTIFIER_NODE.  We are being called from
6522                tsubst_friend_function, and we want only to create a
6523                new decl (R) with appropriate types so that we can call
6524                determine_specialization.  */
6525             gen_tmpl = NULL_TREE;
6526           }
6527
6528         if (DECL_CLASS_SCOPE_P (t))
6529           {
6530             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
6531               member = 2;
6532             else
6533               member = 1;
6534             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
6535                                     complain, t, /*entering_scope=*/1);
6536           }
6537         else
6538           {
6539             member = 0;
6540             ctx = DECL_CONTEXT (t);
6541           }
6542         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6543         if (type == error_mark_node)
6544           return error_mark_node;
6545
6546         /* We do NOT check for matching decls pushed separately at this
6547            point, as they may not represent instantiations of this
6548            template, and in any case are considered separate under the
6549            discrete model.  */
6550         r = copy_decl (t);
6551         DECL_USE_TEMPLATE (r) = 0;
6552         TREE_TYPE (r) = type;
6553         /* Clear out the mangled name and RTL for the instantiation.  */
6554         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6555         SET_DECL_RTL (r, NULL_RTX);
6556         DECL_INITIAL (r) = NULL_TREE;
6557         DECL_CONTEXT (r) = ctx;
6558
6559         if (member && DECL_CONV_FN_P (r))
6560           /* Type-conversion operator.  Reconstruct the name, in
6561              case it's the name of one of the template's parameters.  */
6562           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
6563
6564         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
6565                                      complain, t);
6566         DECL_RESULT (r) = NULL_TREE;
6567
6568         TREE_STATIC (r) = 0;
6569         TREE_PUBLIC (r) = TREE_PUBLIC (t);
6570         DECL_EXTERNAL (r) = 1;
6571         /* If this is an instantiation of a function with internal
6572            linkage, we already know what object file linkage will be
6573            assigned to the instantiation.  */
6574         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
6575         DECL_DEFER_OUTPUT (r) = 0;
6576         TREE_CHAIN (r) = NULL_TREE;
6577         DECL_PENDING_INLINE_INFO (r) = 0;
6578         DECL_PENDING_INLINE_P (r) = 0;
6579         DECL_SAVED_TREE (r) = NULL_TREE;
6580         TREE_USED (r) = 0;
6581         if (DECL_CLONED_FUNCTION (r))
6582           {
6583             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
6584                                                args, complain, t);
6585             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
6586             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
6587           }
6588
6589         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
6590            this in the special friend case mentioned above where
6591            GEN_TMPL is NULL.  */
6592         if (gen_tmpl)
6593           {
6594             DECL_TEMPLATE_INFO (r)
6595               = tree_cons (gen_tmpl, argvec, NULL_TREE);
6596             SET_DECL_IMPLICIT_INSTANTIATION (r);
6597             register_specialization (r, gen_tmpl, argvec, false);
6598
6599             /* We're not supposed to instantiate default arguments
6600                until they are called, for a template.  But, for a
6601                declaration like:
6602
6603                  template <class T> void f ()
6604                  { extern void g(int i = T()); }
6605
6606                we should do the substitution when the template is
6607                instantiated.  We handle the member function case in
6608                instantiate_class_template since the default arguments
6609                might refer to other members of the class.  */
6610             if (!member
6611                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
6612                 && !uses_template_parms (argvec))
6613               tsubst_default_arguments (r);
6614           }
6615         else
6616           DECL_TEMPLATE_INFO (r) = NULL_TREE;
6617
6618         /* Copy the list of befriending classes.  */
6619         for (friends = &DECL_BEFRIENDING_CLASSES (r);
6620              *friends;
6621              friends = &TREE_CHAIN (*friends))
6622           {
6623             *friends = copy_node (*friends);
6624             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
6625                                             args, complain,
6626                                             in_decl);
6627           }
6628
6629         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
6630           {
6631             maybe_retrofit_in_chrg (r);
6632             if (DECL_CONSTRUCTOR_P (r))
6633               grok_ctor_properties (ctx, r);
6634             /* If this is an instantiation of a member template, clone it.
6635                If it isn't, that'll be handled by
6636                clone_constructors_and_destructors.  */
6637             if (PRIMARY_TEMPLATE_P (gen_tmpl))
6638               clone_function_decl (r, /*update_method_vec_p=*/0);
6639           }
6640         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r)))
6641           grok_op_properties (r, (complain & tf_error) != 0);
6642
6643         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
6644           SET_DECL_FRIEND_CONTEXT (r,
6645                                    tsubst (DECL_FRIEND_CONTEXT (t),
6646                                             args, complain, in_decl));
6647       }
6648       break;
6649
6650     case PARM_DECL:
6651       {
6652         tree type;
6653
6654         r = copy_node (t);
6655         if (DECL_TEMPLATE_PARM_P (t))
6656           SET_DECL_TEMPLATE_PARM_P (r);
6657
6658         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6659         type = type_decays_to (type);
6660         TREE_TYPE (r) = type;
6661         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
6662
6663         if (DECL_INITIAL (r))
6664           {
6665             if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
6666               DECL_INITIAL (r) = TREE_TYPE (r);
6667             else
6668               DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
6669                                          complain, in_decl);
6670           }
6671
6672         DECL_CONTEXT (r) = NULL_TREE;
6673
6674         if (!DECL_TEMPLATE_PARM_P (r))
6675           DECL_ARG_TYPE (r) = type_passed_as (type);
6676         if (TREE_CHAIN (t))
6677           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
6678                                    complain, TREE_CHAIN (t));
6679       }
6680       break;
6681
6682     case FIELD_DECL:
6683       {
6684         tree type;
6685
6686         r = copy_decl (t);
6687         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6688         if (type == error_mark_node)
6689           return error_mark_node;
6690         TREE_TYPE (r) = type;
6691         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
6692
6693         /* We don't have to set DECL_CONTEXT here; it is set by
6694            finish_member_declaration.  */
6695         DECL_INITIAL (r) = tsubst_expr (DECL_INITIAL (t), args,
6696                                         complain, in_decl);
6697         TREE_CHAIN (r) = NULL_TREE;
6698         if (VOID_TYPE_P (type))
6699           error ("instantiation of %q+D as type %qT", r, type);
6700       }
6701       break;
6702
6703     case USING_DECL:
6704       /* We reach here only for member using decls.  */
6705       if (DECL_DEPENDENT_P (t))
6706         {
6707           r = do_class_using_decl
6708             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
6709              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
6710           if (!r)
6711             r = error_mark_node;
6712         }
6713       else
6714         {
6715           r = copy_node (t);
6716           TREE_CHAIN (r) = NULL_TREE;
6717         }
6718       break;
6719
6720     case TYPE_DECL:
6721     case VAR_DECL:
6722       {
6723         tree argvec = NULL_TREE;
6724         tree gen_tmpl = NULL_TREE;
6725         tree spec;
6726         tree tmpl = NULL_TREE;
6727         tree ctx;
6728         tree type = NULL_TREE;
6729         bool local_p;
6730
6731         if (TREE_CODE (t) == TYPE_DECL)
6732           {
6733             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6734             if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
6735                 || t == TYPE_MAIN_DECL (TREE_TYPE (t)))
6736               {
6737                 /* If this is the canonical decl, we don't have to
6738                    mess with instantiations, and often we can't (for
6739                    typename, template type parms and such).  Note that
6740                    TYPE_NAME is not correct for the above test if
6741                    we've copied the type for a typedef.  */
6742                 r = TYPE_NAME (type);
6743                 break;
6744               }
6745           }
6746
6747         /* Check to see if we already have the specialization we
6748            need.  */
6749         spec = NULL_TREE;
6750         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
6751           {
6752             /* T is a static data member or namespace-scope entity.
6753                We have to substitute into namespace-scope variables
6754                (even though such entities are never templates) because
6755                of cases like:
6756                
6757                  template <class T> void f() { extern T t; }
6758
6759                where the entity referenced is not known until
6760                instantiation time.  */
6761             local_p = false;
6762             ctx = DECL_CONTEXT (t);
6763             if (DECL_CLASS_SCOPE_P (t))
6764               {
6765                 ctx = tsubst_aggr_type (ctx, args,
6766                                         complain,
6767                                         in_decl, /*entering_scope=*/1);
6768                 /* If CTX is unchanged, then T is in fact the
6769                    specialization we want.  That situation occurs when
6770                    referencing a static data member within in its own
6771                    class.  We can use pointer equality, rather than
6772                    same_type_p, because DECL_CONTEXT is always
6773                    canonical.  */
6774                 if (ctx == DECL_CONTEXT (t))
6775                   spec = t;
6776               }
6777
6778             if (!spec)
6779               {
6780                 tmpl = DECL_TI_TEMPLATE (t);
6781                 gen_tmpl = most_general_template (tmpl);
6782                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
6783                 spec = (retrieve_specialization 
6784                         (gen_tmpl, argvec,
6785                          /*class_specializations_p=*/false));
6786               }
6787           }
6788         else
6789           {
6790             /* A local variable.  */
6791             local_p = true;
6792             /* Subsequent calls to pushdecl will fill this in.  */
6793             ctx = NULL_TREE;
6794             spec = retrieve_local_specialization (t);
6795           }
6796         /* If we already have the specialization we need, there is
6797            nothing more to do.  */ 
6798         if (spec)
6799           {
6800             r = spec;
6801             break;
6802           }
6803
6804         /* Create a new node for the specialization we need.  */
6805         r = copy_decl (t);
6806         if (TREE_CODE (r) == VAR_DECL)
6807           {
6808             /* Even if the original location is out of scope, the
6809                newly substituted one is not.  */
6810             DECL_DEAD_FOR_LOCAL (r) = 0;
6811             DECL_INITIALIZED_P (r) = 0;
6812             DECL_TEMPLATE_INSTANTIATED (r) = 0;
6813             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6814             if (type == error_mark_node)
6815               return error_mark_node;
6816             if (TREE_CODE (type) == FUNCTION_TYPE)
6817               {
6818                 /* It may seem that this case cannot occur, since:
6819
6820                      typedef void f();
6821                      void g() { f x; }
6822
6823                    declares a function, not a variable.  However:
6824       
6825                      typedef void f();
6826                      template <typename T> void g() { T t; }
6827                      template void g<f>();
6828
6829                    is an attempt to declare a variable with function
6830                    type.  */
6831                 error ("variable %qD has function type",
6832                        /* R is not yet sufficiently initialized, so we
6833                           just use its name.  */
6834                        DECL_NAME (r));
6835                 return error_mark_node;
6836               }
6837             type = complete_type (type);
6838             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
6839               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
6840             type = check_var_type (DECL_NAME (r), type);
6841
6842             if (DECL_HAS_VALUE_EXPR_P (t))
6843               {
6844                 tree ve = DECL_VALUE_EXPR (t);
6845                 ve = tsubst_expr (ve, args, complain, in_decl);
6846                 SET_DECL_VALUE_EXPR (r, ve);
6847               }
6848           }
6849         else if (DECL_SELF_REFERENCE_P (t))
6850           SET_DECL_SELF_REFERENCE_P (r);
6851         TREE_TYPE (r) = type;
6852         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
6853         DECL_CONTEXT (r) = ctx;
6854         /* Clear out the mangled name and RTL for the instantiation.  */
6855         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6856         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
6857           SET_DECL_RTL (r, NULL_RTX);
6858         /* The initializer must not be expanded until it is required;
6859            see [temp.inst].  */
6860         DECL_INITIAL (r) = NULL_TREE;
6861         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
6862           SET_DECL_RTL (r, NULL_RTX);
6863         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
6864
6865         if (!local_p)
6866           {
6867             /* A static data member declaration is always marked
6868                external when it is declared in-class, even if an
6869                initializer is present.  We mimic the non-template
6870                processing here.  */
6871             DECL_EXTERNAL (r) = 1;
6872
6873             register_specialization (r, gen_tmpl, argvec, false);
6874             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
6875             SET_DECL_IMPLICIT_INSTANTIATION (r);
6876           }
6877         else
6878           register_local_specialization (r, t);
6879
6880         TREE_CHAIN (r) = NULL_TREE;
6881         layout_decl (r, 0);
6882       }
6883       break;
6884
6885     default:
6886       gcc_unreachable ();
6887     }
6888
6889   /* Restore the file and line information.  */
6890   input_location = saved_loc;
6891
6892   return r;
6893 }
6894
6895 /* Substitute into the ARG_TYPES of a function type.  */
6896
6897 static tree
6898 tsubst_arg_types (tree arg_types,
6899                   tree args,
6900                   tsubst_flags_t complain,
6901                   tree in_decl)
6902 {
6903   tree remaining_arg_types;
6904   tree type;
6905   tree default_arg;
6906   tree result = NULL_TREE;
6907
6908   if (!arg_types || arg_types == void_list_node)
6909     return arg_types;
6910
6911   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
6912                                           args, complain, in_decl);
6913   if (remaining_arg_types == error_mark_node)
6914     return error_mark_node;
6915
6916   type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
6917   if (type == error_mark_node)
6918     return error_mark_node;
6919   if (VOID_TYPE_P (type))
6920     {
6921       if (complain & tf_error)
6922         {
6923           error ("invalid parameter type %qT", type);
6924           if (in_decl)
6925             error ("in declaration %q+D", in_decl);
6926         }
6927       return error_mark_node;
6928     }
6929
6930   /* Do array-to-pointer, function-to-pointer conversion, and ignore
6931      top-level qualifiers as required.  */
6932   type = TYPE_MAIN_VARIANT (type_decays_to (type));
6933
6934   /* We do not substitute into default arguments here.  The standard
6935      mandates that they be instantiated only when needed, which is
6936      done in build_over_call.  */
6937   default_arg = TREE_PURPOSE (arg_types);
6938
6939   if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
6940     {
6941       /* We've instantiated a template before its default arguments
6942          have been parsed.  This can happen for a nested template
6943          class, and is not an error unless we require the default
6944          argument in a call of this function.  */
6945       result = tree_cons (default_arg, type, remaining_arg_types);
6946       VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), result);
6947     }
6948   else
6949     result = hash_tree_cons (default_arg, type, remaining_arg_types);
6950
6951   return result;
6952 }
6953
6954 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
6955    *not* handle the exception-specification for FNTYPE, because the
6956    initial substitution of explicitly provided template parameters
6957    during argument deduction forbids substitution into the
6958    exception-specification:
6959
6960      [temp.deduct]
6961
6962      All references in the function type of the function template to  the
6963      corresponding template parameters are replaced by the specified tem-
6964      plate argument values.  If a substitution in a template parameter or
6965      in  the function type of the function template results in an invalid
6966      type, type deduction fails.  [Note: The equivalent  substitution  in
6967      exception specifications is done only when the function is instanti-
6968      ated, at which point a program is  ill-formed  if  the  substitution
6969      results in an invalid type.]  */
6970
6971 static tree
6972 tsubst_function_type (tree t,
6973                       tree args,
6974                       tsubst_flags_t complain,
6975                       tree in_decl)
6976 {
6977   tree return_type;
6978   tree arg_types;
6979   tree fntype;
6980
6981   /* The TYPE_CONTEXT is not used for function/method types.  */
6982   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
6983
6984   /* Substitute the return type.  */
6985   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6986   if (return_type == error_mark_node)
6987     return error_mark_node;
6988   /* The standard does not presently indicate that creation of a
6989      function type with an invalid return type is a deduction failure.
6990      However, that is clearly analogous to creating an array of "void"
6991      or a reference to a reference.  This is core issue #486.  */
6992   if (TREE_CODE (return_type) == ARRAY_TYPE
6993       || TREE_CODE (return_type) == FUNCTION_TYPE)
6994     {
6995       if (complain & tf_error)
6996         {
6997           if (TREE_CODE (return_type) == ARRAY_TYPE)
6998             error ("function returning an array");
6999           else
7000             error ("function returning a function");
7001         }
7002       return error_mark_node;
7003     }
7004
7005   /* Substitute the argument types.  */
7006   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
7007                                 complain, in_decl);
7008   if (arg_types == error_mark_node)
7009     return error_mark_node;
7010
7011   /* Construct a new type node and return it.  */
7012   if (TREE_CODE (t) == FUNCTION_TYPE)
7013     fntype = build_function_type (return_type, arg_types);
7014   else
7015     {
7016       tree r = TREE_TYPE (TREE_VALUE (arg_types));
7017       if (! IS_AGGR_TYPE (r))
7018         {
7019           /* [temp.deduct]
7020
7021              Type deduction may fail for any of the following
7022              reasons:
7023
7024              -- Attempting to create "pointer to member of T" when T
7025              is not a class type.  */
7026           if (complain & tf_error)
7027             error ("creating pointer to member function of non-class type %qT",
7028                       r);
7029           return error_mark_node;
7030         }
7031
7032       fntype = build_method_type_directly (r, return_type,
7033                                            TREE_CHAIN (arg_types));
7034     }
7035   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
7036   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
7037
7038   return fntype;
7039 }
7040
7041 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
7042    ARGS into that specification, and return the substituted
7043    specification.  If there is no specification, return NULL_TREE.  */
7044
7045 static tree
7046 tsubst_exception_specification (tree fntype,
7047                                 tree args,
7048                                 tsubst_flags_t complain,
7049                                 tree in_decl)
7050 {
7051   tree specs;
7052   tree new_specs;
7053
7054   specs = TYPE_RAISES_EXCEPTIONS (fntype);
7055   new_specs = NULL_TREE;
7056   if (specs)
7057     {
7058       if (! TREE_VALUE (specs))
7059         new_specs = specs;
7060       else
7061         while (specs)
7062           {
7063             tree spec;
7064             spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
7065             if (spec == error_mark_node)
7066               return spec;
7067             new_specs = add_exception_specifier (new_specs, spec, complain);
7068             specs = TREE_CHAIN (specs);
7069           }
7070     }
7071   return new_specs;
7072 }
7073
7074 /* Substitute into the PARMS of a call-declarator.  */
7075
7076 static tree
7077 tsubst_call_declarator_parms (tree parms,
7078                               tree args,
7079                               tsubst_flags_t complain,
7080                               tree in_decl)
7081 {
7082   tree new_parms;
7083   tree type;
7084   tree defarg;
7085
7086   if (!parms || parms == void_list_node)
7087     return parms;
7088
7089   new_parms = tsubst_call_declarator_parms (TREE_CHAIN (parms),
7090                                             args, complain, in_decl);
7091
7092   /* Figure out the type of this parameter.  */
7093   type = tsubst (TREE_VALUE (parms), args, complain, in_decl);
7094
7095   /* Figure out the default argument as well.  Note that we use
7096      tsubst_expr since the default argument is really an expression.  */
7097   defarg = tsubst_expr (TREE_PURPOSE (parms), args, complain, in_decl);
7098
7099   /* Chain this parameter on to the front of those we have already
7100      processed.  We don't use hash_tree_cons because that function
7101      doesn't check TREE_PARMLIST.  */
7102   new_parms = tree_cons (defarg, type, new_parms);
7103
7104   return new_parms;
7105 }
7106
7107 /* Take the tree structure T and replace template parameters used
7108    therein with the argument vector ARGS.  IN_DECL is an associated
7109    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
7110    Issue error and warning messages under control of COMPLAIN.  Note
7111    that we must be relatively non-tolerant of extensions here, in
7112    order to preserve conformance; if we allow substitutions that
7113    should not be allowed, we may allow argument deductions that should
7114    not succeed, and therefore report ambiguous overload situations
7115    where there are none.  In theory, we could allow the substitution,
7116    but indicate that it should have failed, and allow our caller to
7117    make sure that the right thing happens, but we don't try to do this
7118    yet.
7119
7120    This function is used for dealing with types, decls and the like;
7121    for expressions, use tsubst_expr or tsubst_copy.  */
7122
7123 static tree
7124 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7125 {
7126   tree type, r;
7127
7128   if (t == NULL_TREE || t == error_mark_node
7129       || t == integer_type_node
7130       || t == void_type_node
7131       || t == char_type_node
7132       || t == unknown_type_node
7133       || TREE_CODE (t) == NAMESPACE_DECL)
7134     return t;
7135
7136   if (DECL_P (t))
7137     return tsubst_decl (t, args, complain);
7138
7139   if (TREE_CODE (t) == IDENTIFIER_NODE)
7140     type = IDENTIFIER_TYPE_VALUE (t);
7141   else
7142     type = TREE_TYPE (t);
7143
7144   gcc_assert (type != unknown_type_node);
7145
7146   if (type
7147       && TREE_CODE (t) != TYPENAME_TYPE
7148       && TREE_CODE (t) != IDENTIFIER_NODE
7149       && TREE_CODE (t) != FUNCTION_TYPE
7150       && TREE_CODE (t) != METHOD_TYPE)
7151     type = tsubst (type, args, complain, in_decl);
7152   if (type == error_mark_node)
7153     return error_mark_node;
7154
7155   switch (TREE_CODE (t))
7156     {
7157     case RECORD_TYPE:
7158     case UNION_TYPE:
7159     case ENUMERAL_TYPE:
7160       return tsubst_aggr_type (t, args, complain, in_decl,
7161                                /*entering_scope=*/0);
7162
7163     case ERROR_MARK:
7164     case IDENTIFIER_NODE:
7165     case VOID_TYPE:
7166     case REAL_TYPE:
7167     case COMPLEX_TYPE:
7168     case VECTOR_TYPE:
7169     case BOOLEAN_TYPE:
7170     case INTEGER_CST:
7171     case REAL_CST:
7172     case STRING_CST:
7173       return t;
7174
7175     case INTEGER_TYPE:
7176       if (t == integer_type_node)
7177         return t;
7178
7179       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
7180           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
7181         return t;
7182
7183       {
7184         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
7185
7186         /* The array dimension behaves like a non-type template arg,
7187            in that we want to fold it as much as possible.  */
7188         max = tsubst_template_arg (omax, args, complain, in_decl);
7189         max = fold_decl_constant_value (max);
7190
7191         if (TREE_CODE (max) != INTEGER_CST 
7192             && TREE_CODE (max) != TEMPLATE_PARM_INDEX
7193             && !at_function_scope_p ())
7194           {
7195             if (complain & tf_error)
7196               error ("array bound is not an integer constant");
7197             return error_mark_node;
7198           }
7199
7200         /* [temp.deduct]
7201
7202            Type deduction may fail for any of the following
7203            reasons:
7204
7205              Attempting to create an array with a size that is
7206              zero or negative.  */
7207         if (integer_zerop (max) && !(complain & tf_error))
7208           /* We must fail if performing argument deduction (as
7209              indicated by the state of complain), so that
7210              another substitution can be found.  */
7211           return error_mark_node;
7212         else if (TREE_CODE (max) == INTEGER_CST
7213                  && INT_CST_LT (max, integer_zero_node))
7214           {
7215             if (complain & tf_error)
7216               error ("creating array with negative size (%qE)", max);
7217
7218             return error_mark_node;
7219           }
7220
7221         return compute_array_index_type (NULL_TREE, max);
7222       }
7223
7224     case TEMPLATE_TYPE_PARM:
7225     case TEMPLATE_TEMPLATE_PARM:
7226     case BOUND_TEMPLATE_TEMPLATE_PARM:
7227     case TEMPLATE_PARM_INDEX:
7228       {
7229         int idx;
7230         int level;
7231         int levels;
7232         tree arg = NULL_TREE;
7233
7234         r = NULL_TREE;
7235
7236         gcc_assert (TREE_VEC_LENGTH (args) > 0);
7237         if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
7238             || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
7239             || TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
7240           {
7241             idx = TEMPLATE_TYPE_IDX (t);
7242             level = TEMPLATE_TYPE_LEVEL (t);
7243           }
7244         else
7245           {
7246             idx = TEMPLATE_PARM_IDX (t);
7247             level = TEMPLATE_PARM_LEVEL (t);
7248           }
7249
7250         levels = TMPL_ARGS_DEPTH (args);
7251         if (level <= levels)
7252           arg = TMPL_ARG (args, level, idx);
7253
7254         if (arg == error_mark_node)
7255           return error_mark_node;
7256         else if (arg != NULL_TREE)
7257           {
7258             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
7259               {
7260                 int quals;
7261                 gcc_assert (TYPE_P (arg));
7262
7263                 /* cv-quals from the template are discarded when
7264                    substituting in a function or reference type.  */
7265                 if (TREE_CODE (arg) == FUNCTION_TYPE
7266                     || TREE_CODE (arg) == METHOD_TYPE
7267                     || TREE_CODE (arg) == REFERENCE_TYPE)
7268                   quals = cp_type_quals (arg);
7269                 else
7270                   quals = cp_type_quals (arg) | cp_type_quals (t);
7271                   
7272                 return cp_build_qualified_type_real
7273                   (arg, quals, complain | tf_ignore_bad_quals);
7274               }
7275             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
7276               {
7277                 /* We are processing a type constructed from a
7278                    template template parameter.  */
7279                 tree argvec = tsubst (TYPE_TI_ARGS (t),
7280                                       args, complain, in_decl);
7281                 if (argvec == error_mark_node)
7282                   return error_mark_node;
7283
7284                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
7285                    are resolving nested-types in the signature of a
7286                    member function templates.  Otherwise ARG is a
7287                    TEMPLATE_DECL and is the real template to be
7288                    instantiated.  */
7289                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
7290                   arg = TYPE_NAME (arg);
7291
7292                 r = lookup_template_class (arg,
7293                                            argvec, in_decl,
7294                                            DECL_CONTEXT (arg),
7295                                             /*entering_scope=*/0,
7296                                            complain);
7297                 return cp_build_qualified_type_real
7298                   (r, TYPE_QUALS (t), complain);
7299               }
7300             else
7301               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
7302               return arg;
7303           }
7304
7305         if (level == 1)
7306           /* This can happen during the attempted tsubst'ing in
7307              unify.  This means that we don't yet have any information
7308              about the template parameter in question.  */
7309           return t;
7310
7311         /* If we get here, we must have been looking at a parm for a
7312            more deeply nested template.  Make a new version of this
7313            template parameter, but with a lower level.  */
7314         switch (TREE_CODE (t))
7315           {
7316           case TEMPLATE_TYPE_PARM:
7317           case TEMPLATE_TEMPLATE_PARM:
7318           case BOUND_TEMPLATE_TEMPLATE_PARM:
7319             if (cp_type_quals (t))
7320               {
7321                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
7322                 r = cp_build_qualified_type_real
7323                   (r, cp_type_quals (t),
7324                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
7325                                ? tf_ignore_bad_quals : 0));
7326               }
7327             else
7328               {
7329                 r = copy_type (t);
7330                 TEMPLATE_TYPE_PARM_INDEX (r)
7331                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
7332                                                 r, levels);
7333                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
7334                 TYPE_MAIN_VARIANT (r) = r;
7335                 TYPE_POINTER_TO (r) = NULL_TREE;
7336                 TYPE_REFERENCE_TO (r) = NULL_TREE;
7337
7338                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
7339                   {
7340                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
7341                                           complain, in_decl);
7342                     if (argvec == error_mark_node)
7343                       return error_mark_node;
7344
7345                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
7346                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
7347                   }
7348               }
7349             break;
7350
7351           case TEMPLATE_PARM_INDEX:
7352             r = reduce_template_parm_level (t, type, levels);
7353             break;
7354
7355           default:
7356             gcc_unreachable ();
7357           }
7358
7359         return r;
7360       }
7361
7362     case TREE_LIST:
7363       {
7364         tree purpose, value, chain;
7365
7366         if (t == void_list_node)
7367           return t;
7368
7369         purpose = TREE_PURPOSE (t);
7370         if (purpose)
7371           {
7372             purpose = tsubst (purpose, args, complain, in_decl);
7373             if (purpose == error_mark_node)
7374               return error_mark_node;
7375           }
7376         value = TREE_VALUE (t);
7377         if (value)
7378           {
7379             value = tsubst (value, args, complain, in_decl);
7380             if (value == error_mark_node)
7381               return error_mark_node;
7382           }
7383         chain = TREE_CHAIN (t);
7384         if (chain && chain != void_type_node)
7385           {
7386             chain = tsubst (chain, args, complain, in_decl);
7387             if (chain == error_mark_node)
7388               return error_mark_node;
7389           }
7390         if (purpose == TREE_PURPOSE (t)
7391             && value == TREE_VALUE (t)
7392             && chain == TREE_CHAIN (t))
7393           return t;
7394         return hash_tree_cons (purpose, value, chain);
7395       }
7396
7397     case TREE_BINFO:
7398       /* We should never be tsubsting a binfo.  */
7399       gcc_unreachable ();
7400
7401     case TREE_VEC:
7402       /* A vector of template arguments.  */
7403       gcc_assert (!type);
7404       return tsubst_template_args (t, args, complain, in_decl);
7405
7406     case POINTER_TYPE:
7407     case REFERENCE_TYPE:
7408       {
7409         enum tree_code code;
7410
7411         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
7412           return t;
7413
7414         code = TREE_CODE (t);
7415
7416
7417         /* [temp.deduct]
7418
7419            Type deduction may fail for any of the following
7420            reasons:
7421
7422            -- Attempting to create a pointer to reference type.
7423            -- Attempting to create a reference to a reference type or
7424               a reference to void.  */
7425         if (TREE_CODE (type) == REFERENCE_TYPE
7426             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
7427           {
7428             static location_t last_loc;
7429
7430             /* We keep track of the last time we issued this error
7431                message to avoid spewing a ton of messages during a
7432                single bad template instantiation.  */
7433             if (complain & tf_error
7434 #ifdef USE_MAPPED_LOCATION
7435                 && last_loc != input_location
7436 #else
7437                 && (last_loc.line != input_line
7438                     || last_loc.file != input_filename)
7439 #endif
7440                   )
7441               {
7442                 if (TREE_CODE (type) == VOID_TYPE)
7443                   error ("forming reference to void");
7444                 else
7445                   error ("forming %s to reference type %qT",
7446                          (code == POINTER_TYPE) ? "pointer" : "reference",
7447                          type);
7448                 last_loc = input_location;
7449               }
7450
7451             return error_mark_node;
7452           }
7453         else if (code == POINTER_TYPE)
7454           {
7455             r = build_pointer_type (type);
7456             if (TREE_CODE (type) == METHOD_TYPE)
7457               r = build_ptrmemfunc_type (r);
7458           }
7459         else
7460           r = build_reference_type (type);
7461         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7462
7463         if (r != error_mark_node)
7464           /* Will this ever be needed for TYPE_..._TO values?  */
7465           layout_type (r);
7466
7467         return r;
7468       }
7469     case OFFSET_TYPE:
7470       {
7471         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
7472         if (r == error_mark_node || !IS_AGGR_TYPE (r))
7473           {
7474             /* [temp.deduct]
7475
7476                Type deduction may fail for any of the following
7477                reasons:
7478
7479                -- Attempting to create "pointer to member of T" when T
7480                   is not a class type.  */
7481             if (complain & tf_error)
7482               error ("creating pointer to member of non-class type %qT", r);
7483             return error_mark_node;
7484           }
7485         if (TREE_CODE (type) == REFERENCE_TYPE)
7486           {
7487             if (complain & tf_error)
7488               error ("creating pointer to member reference type %qT", type);
7489             return error_mark_node;
7490           }
7491         if (TREE_CODE (type) == VOID_TYPE)
7492           {
7493             if (complain & tf_error)
7494               error ("creating pointer to member of type void");
7495             return error_mark_node;
7496           }
7497         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
7498         if (TREE_CODE (type) == FUNCTION_TYPE)
7499           {
7500             /* The type of the implicit object parameter gets its
7501                cv-qualifiers from the FUNCTION_TYPE. */
7502             tree method_type;
7503             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
7504                                                       cp_type_quals (type));
7505             tree memptr;
7506             method_type = build_method_type_directly (this_type,
7507                                                       TREE_TYPE (type),
7508                                                       TYPE_ARG_TYPES (type));
7509             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
7510             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
7511                                                  complain);
7512           }
7513         else
7514           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
7515                                                TYPE_QUALS (t),
7516                                                complain);
7517       }
7518     case FUNCTION_TYPE:
7519     case METHOD_TYPE:
7520       {
7521         tree fntype;
7522         tree specs;
7523         fntype = tsubst_function_type (t, args, complain, in_decl);
7524         if (fntype == error_mark_node)
7525           return error_mark_node;
7526
7527         /* Substitute the exception specification.  */
7528         specs = tsubst_exception_specification (t, args, complain,
7529                                                 in_decl);
7530         if (specs == error_mark_node)
7531           return error_mark_node;
7532         if (specs)
7533           fntype = build_exception_variant (fntype, specs);
7534         return fntype;
7535       }
7536     case ARRAY_TYPE:
7537       {
7538         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
7539         if (domain == error_mark_node)
7540           return error_mark_node;
7541
7542         /* As an optimization, we avoid regenerating the array type if
7543            it will obviously be the same as T.  */
7544         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
7545           return t;
7546
7547         /* These checks should match the ones in grokdeclarator.
7548
7549            [temp.deduct]
7550
7551            The deduction may fail for any of the following reasons:
7552
7553            -- Attempting to create an array with an element type that
7554               is void, a function type, or a reference type, or [DR337]
7555               an abstract class type.  */
7556         if (TREE_CODE (type) == VOID_TYPE
7557             || TREE_CODE (type) == FUNCTION_TYPE
7558             || TREE_CODE (type) == REFERENCE_TYPE)
7559           {
7560             if (complain & tf_error)
7561               error ("creating array of %qT", type);
7562             return error_mark_node;
7563           }
7564         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
7565           {
7566             if (complain & tf_error)
7567               error ("creating array of %qT, which is an abstract class type",
7568                      type);
7569             return error_mark_node;
7570           }
7571
7572         r = build_cplus_array_type (type, domain);
7573         return r;
7574       }
7575
7576     case PLUS_EXPR:
7577     case MINUS_EXPR:
7578       {
7579         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7580         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
7581
7582         if (e1 == error_mark_node || e2 == error_mark_node)
7583           return error_mark_node;
7584
7585         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
7586       }
7587
7588     case NEGATE_EXPR:
7589     case NOP_EXPR:
7590       {
7591         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7592         if (e == error_mark_node)
7593           return error_mark_node;
7594
7595         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
7596       }
7597
7598     case TYPENAME_TYPE:
7599       {
7600         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
7601                                      in_decl, /*entering_scope=*/1);
7602         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
7603                               complain, in_decl);
7604
7605         if (ctx == error_mark_node || f == error_mark_node)
7606           return error_mark_node;
7607
7608         if (!IS_AGGR_TYPE (ctx))
7609           {
7610             if (complain & tf_error)
7611               error ("%qT is not a class, struct, or union type", ctx);
7612             return error_mark_node;
7613           }
7614         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
7615           {
7616             /* Normally, make_typename_type does not require that the CTX
7617                have complete type in order to allow things like:
7618
7619                  template <class T> struct S { typename S<T>::X Y; };
7620
7621                But, such constructs have already been resolved by this
7622                point, so here CTX really should have complete type, unless
7623                it's a partial instantiation.  */
7624             ctx = complete_type (ctx);
7625             if (!COMPLETE_TYPE_P (ctx))
7626               {
7627                 if (complain & tf_error)
7628                   cxx_incomplete_type_error (NULL_TREE, ctx);
7629                 return error_mark_node;
7630               }
7631           }
7632
7633         f = make_typename_type (ctx, f, typename_type,
7634                                 (complain & tf_error) | tf_keep_type_decl);
7635         if (f == error_mark_node)
7636           return f;
7637         if (TREE_CODE (f) == TYPE_DECL)
7638           {
7639             complain |= tf_ignore_bad_quals;
7640             f = TREE_TYPE (f);
7641           }
7642
7643         if (TREE_CODE (f) != TYPENAME_TYPE)
7644           {
7645             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
7646               error ("%qT resolves to %qT, which is not an enumeration type",
7647                      t, f);
7648             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
7649               error ("%qT resolves to %qT, which is is not a class type",
7650                      t, f);
7651           }
7652
7653         return cp_build_qualified_type_real
7654           (f, cp_type_quals (f) | cp_type_quals (t), complain);
7655       }
7656
7657     case UNBOUND_CLASS_TEMPLATE:
7658       {
7659         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
7660                                      in_decl, /*entering_scope=*/1);
7661         tree name = TYPE_IDENTIFIER (t);
7662         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
7663
7664         if (ctx == error_mark_node || name == error_mark_node)
7665           return error_mark_node;
7666
7667         if (parm_list)
7668           parm_list = tsubst_template_parms (parm_list, args, complain);
7669         return make_unbound_class_template (ctx, name, parm_list, complain);
7670       }
7671
7672     case INDIRECT_REF:
7673     case ADDR_EXPR:
7674     case CALL_EXPR:
7675       gcc_unreachable ();
7676
7677     case ARRAY_REF:
7678       {
7679         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7680         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
7681         if (e1 == error_mark_node || e2 == error_mark_node)
7682           return error_mark_node;
7683
7684         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
7685       }
7686
7687     case SCOPE_REF:
7688       {
7689         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7690         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
7691         if (e1 == error_mark_node || e2 == error_mark_node)
7692           return error_mark_node;
7693
7694         return build_qualified_name (/*type=*/NULL_TREE,
7695                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
7696       }
7697
7698     case TYPEOF_TYPE:
7699       {
7700         tree type;
7701
7702         type = finish_typeof (tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
7703                                            complain, in_decl));
7704         return cp_build_qualified_type_real (type,
7705                                              cp_type_quals (t)
7706                                              | cp_type_quals (type),
7707                                              complain);
7708       }
7709
7710     default:
7711       sorry ("use of %qs in template",
7712              tree_code_name [(int) TREE_CODE (t)]);
7713       return error_mark_node;
7714     }
7715 }
7716
7717 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
7718    type of the expression on the left-hand side of the "." or "->"
7719    operator.  */
7720
7721 static tree
7722 tsubst_baselink (tree baselink, tree object_type,
7723                  tree args, tsubst_flags_t complain, tree in_decl)
7724 {
7725     tree name;
7726     tree qualifying_scope;
7727     tree fns;
7728     tree optype;
7729     tree template_args = 0;
7730     bool template_id_p = false;
7731
7732     /* A baselink indicates a function from a base class.  The
7733        BASELINK_ACCESS_BINFO and BASELINK_BINFO are going to have
7734        non-dependent types; otherwise, the lookup could not have
7735        succeeded.  However, they may indicate bases of the template
7736        class, rather than the instantiated class.
7737
7738        In addition, lookups that were not ambiguous before may be
7739        ambiguous now.  Therefore, we perform the lookup again.  */
7740     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
7741     fns = BASELINK_FUNCTIONS (baselink);
7742     optype = BASELINK_OPTYPE (baselink);
7743     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
7744       {
7745         template_id_p = true;
7746         template_args = TREE_OPERAND (fns, 1);
7747         fns = TREE_OPERAND (fns, 0);
7748         if (template_args)
7749           template_args = tsubst_template_args (template_args, args,
7750                                                 complain, in_decl);
7751       }
7752     name = DECL_NAME (get_first_fn (fns));
7753     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
7754
7755     /* If lookup found a single function, mark it as used at this
7756        point.  (If it lookup found multiple functions the one selected
7757        later by overload resolution will be marked as used at that
7758        point.)  */
7759     if (BASELINK_P (baselink))
7760       fns = BASELINK_FUNCTIONS (baselink);
7761     if (!template_id_p && !really_overloaded_fn (fns))
7762       mark_used (OVL_CURRENT (fns));
7763
7764     /* Add back the template arguments, if present.  */
7765     if (BASELINK_P (baselink) && template_id_p)
7766       BASELINK_FUNCTIONS (baselink)
7767         = build_nt (TEMPLATE_ID_EXPR,
7768                     BASELINK_FUNCTIONS (baselink),
7769                     template_args);
7770     /* Update the conversion operator type.  */
7771     BASELINK_OPTYPE (baselink) 
7772       = tsubst (optype, args, complain, in_decl);
7773
7774     if (!object_type)
7775       object_type = current_class_type;
7776     return adjust_result_of_qualified_name_lookup (baselink,
7777                                                    qualifying_scope,
7778                                                    object_type);
7779 }
7780
7781 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
7782    true if the qualified-id will be a postfix-expression in-and-of
7783    itself; false if more of the postfix-expression follows the
7784    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
7785    of "&".  */
7786
7787 static tree
7788 tsubst_qualified_id (tree qualified_id, tree args,
7789                      tsubst_flags_t complain, tree in_decl,
7790                      bool done, bool address_p)
7791 {
7792   tree expr;
7793   tree scope;
7794   tree name;
7795   bool is_template;
7796   tree template_args;
7797
7798   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
7799
7800   /* Figure out what name to look up.  */
7801   name = TREE_OPERAND (qualified_id, 1);
7802   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
7803     {
7804       is_template = true;
7805       template_args = TREE_OPERAND (name, 1);
7806       if (template_args)
7807         template_args = tsubst_template_args (template_args, args,
7808                                               complain, in_decl);
7809       name = TREE_OPERAND (name, 0);
7810     }
7811   else
7812     {
7813       is_template = false;
7814       template_args = NULL_TREE;
7815     }
7816
7817   /* Substitute into the qualifying scope.  When there are no ARGS, we
7818      are just trying to simplify a non-dependent expression.  In that
7819      case the qualifying scope may be dependent, and, in any case,
7820      substituting will not help.  */
7821   scope = TREE_OPERAND (qualified_id, 0);
7822   if (args)
7823     {
7824       scope = tsubst (scope, args, complain, in_decl);
7825       expr = tsubst_copy (name, args, complain, in_decl);
7826     }
7827   else
7828     expr = name;
7829
7830   if (dependent_type_p (scope))
7831     return build_qualified_name (/*type=*/NULL_TREE, 
7832                                  scope, expr, 
7833                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
7834
7835   if (!BASELINK_P (name) && !DECL_P (expr))
7836     {
7837       if (TREE_CODE (expr) == BIT_NOT_EXPR)
7838         /* If this were actually a destructor call, it would have been
7839            parsed as such by the parser.  */
7840         expr = error_mark_node;
7841       else
7842         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
7843       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
7844                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
7845         {
7846           if (complain & tf_error)
7847             {
7848               error ("dependent-name %qE is parsed as a non-type, but "
7849                      "instantiation yields a type", qualified_id);
7850               inform ("say %<typename %E%> if a type is meant", qualified_id);
7851             }
7852           return error_mark_node;
7853         }
7854     }
7855
7856   if (DECL_P (expr))
7857     {
7858       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
7859                                            scope);
7860       /* Remember that there was a reference to this entity.  */
7861       mark_used (expr);
7862     }
7863
7864   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
7865     {
7866       if (complain & tf_error)
7867         qualified_name_lookup_error (scope,
7868                                      TREE_OPERAND (qualified_id, 1),
7869                                      expr);
7870       return error_mark_node;
7871     }
7872
7873   if (is_template)
7874     expr = lookup_template_function (expr, template_args);
7875
7876   if (expr == error_mark_node && complain & tf_error)
7877     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
7878                                  expr);
7879   else if (TYPE_P (scope))
7880     {
7881       expr = (adjust_result_of_qualified_name_lookup
7882               (expr, scope, current_class_type));
7883       expr = (finish_qualified_id_expr 
7884               (scope, expr, done, address_p,
7885                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
7886                /*template_arg_p=*/false));
7887     }
7888
7889   /* Expressions do not generally have reference type.  */
7890   if (TREE_CODE (expr) != SCOPE_REF
7891       /* However, if we're about to form a pointer-to-member, we just
7892          want the referenced member referenced.  */
7893       && TREE_CODE (expr) != OFFSET_REF)
7894     expr = convert_from_reference (expr);
7895
7896   return expr;
7897 }
7898
7899 /* Like tsubst, but deals with expressions.  This function just replaces
7900    template parms; to finish processing the resultant expression, use
7901    tsubst_expr.  */
7902
7903 static tree
7904 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7905 {
7906   enum tree_code code;
7907   tree r;
7908
7909   if (t == NULL_TREE || t == error_mark_node)
7910     return t;
7911
7912   code = TREE_CODE (t);
7913
7914   switch (code)
7915     {
7916     case PARM_DECL:
7917       r = retrieve_local_specialization (t);
7918       gcc_assert (r != NULL);
7919       mark_used (r);
7920       return r;
7921
7922     case CONST_DECL:
7923       {
7924         tree enum_type;
7925         tree v;
7926
7927         if (DECL_TEMPLATE_PARM_P (t))
7928           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
7929         /* There is no need to substitute into namespace-scope
7930            enumerators.  */
7931         if (DECL_NAMESPACE_SCOPE_P (t))
7932           return t;
7933         /* If ARGS is NULL, then T is known to be non-dependent.  */
7934         if (args == NULL_TREE)
7935           return integral_constant_value (t);
7936
7937         /* Unfortunately, we cannot just call lookup_name here.
7938            Consider:
7939
7940              template <int I> int f() {
7941              enum E { a = I };
7942              struct S { void g() { E e = a; } };
7943              };
7944
7945            When we instantiate f<7>::S::g(), say, lookup_name is not
7946            clever enough to find f<7>::a.  */
7947         enum_type
7948           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
7949                               /*entering_scope=*/0);
7950
7951         for (v = TYPE_VALUES (enum_type);
7952              v != NULL_TREE;
7953              v = TREE_CHAIN (v))
7954           if (TREE_PURPOSE (v) == DECL_NAME (t))
7955             return TREE_VALUE (v);
7956
7957           /* We didn't find the name.  That should never happen; if
7958              name-lookup found it during preliminary parsing, we
7959              should find it again here during instantiation.  */
7960         gcc_unreachable ();
7961       }
7962       return t;
7963
7964     case FIELD_DECL:
7965       if (DECL_CONTEXT (t))
7966         {
7967           tree ctx;
7968
7969           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
7970                                   /*entering_scope=*/1);
7971           if (ctx != DECL_CONTEXT (t))
7972             {
7973               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
7974               if (!r)
7975                 {
7976                   if (complain & tf_error)
7977                     error ("using invalid field %qD", t);
7978                   return error_mark_node;
7979                 }
7980               return r;
7981             }
7982         }
7983
7984       return t;
7985
7986     case VAR_DECL:
7987     case FUNCTION_DECL:
7988       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
7989           || local_variable_p (t))
7990         t = tsubst (t, args, complain, in_decl);
7991       mark_used (t);
7992       return t;
7993
7994     case BASELINK:
7995       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
7996
7997     case TEMPLATE_DECL:
7998       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7999         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
8000                        args, complain, in_decl);
8001       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
8002         return tsubst (t, args, complain, in_decl);
8003       else if (DECL_CLASS_SCOPE_P (t)
8004                && uses_template_parms (DECL_CONTEXT (t)))
8005         {
8006           /* Template template argument like the following example need
8007              special treatment:
8008
8009                template <template <class> class TT> struct C {};
8010                template <class T> struct D {
8011                  template <class U> struct E {};
8012                  C<E> c;                                // #1
8013                };
8014                D<int> d;                                // #2
8015
8016              We are processing the template argument `E' in #1 for
8017              the template instantiation #2.  Originally, `E' is a
8018              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
8019              have to substitute this with one having context `D<int>'.  */
8020
8021           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
8022           return lookup_field (context, DECL_NAME(t), 0, false);
8023         }
8024       else
8025         /* Ordinary template template argument.  */
8026         return t;
8027
8028     case CAST_EXPR:
8029     case REINTERPRET_CAST_EXPR:
8030     case CONST_CAST_EXPR:
8031     case STATIC_CAST_EXPR:
8032     case DYNAMIC_CAST_EXPR:
8033     case NOP_EXPR:
8034       return build1
8035         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
8036          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
8037
8038     case INDIRECT_REF:
8039     case NEGATE_EXPR:
8040     case TRUTH_NOT_EXPR:
8041     case BIT_NOT_EXPR:
8042     case ADDR_EXPR:
8043     case UNARY_PLUS_EXPR:      /* Unary + */
8044     case SIZEOF_EXPR:
8045     case ALIGNOF_EXPR:
8046     case ARROW_EXPR:
8047     case THROW_EXPR:
8048     case TYPEID_EXPR:
8049     case REALPART_EXPR:
8050     case IMAGPART_EXPR:
8051       return build1
8052         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
8053          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
8054
8055     case COMPONENT_REF:
8056       {
8057         tree object;
8058         tree name;
8059
8060         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
8061         name = TREE_OPERAND (t, 1);
8062         if (TREE_CODE (name) == BIT_NOT_EXPR)
8063           {
8064             name = tsubst_copy (TREE_OPERAND (name, 0), args,
8065                                 complain, in_decl);
8066             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
8067           }
8068         else if (TREE_CODE (name) == SCOPE_REF
8069                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
8070           {
8071             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
8072                                      complain, in_decl);
8073             name = TREE_OPERAND (name, 1);
8074             name = tsubst_copy (TREE_OPERAND (name, 0), args,
8075                                 complain, in_decl);
8076             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
8077             name = build_qualified_name (/*type=*/NULL_TREE,
8078                                          base, name, 
8079                                          /*template_p=*/false);
8080           }
8081         else if (TREE_CODE (name) == BASELINK)
8082           name = tsubst_baselink (name,
8083                                   non_reference (TREE_TYPE (object)),
8084                                   args, complain,
8085                                   in_decl);
8086         else
8087           name = tsubst_copy (name, args, complain, in_decl);
8088         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
8089       }
8090
8091     case PLUS_EXPR:
8092     case MINUS_EXPR:
8093     case MULT_EXPR:
8094     case TRUNC_DIV_EXPR:
8095     case CEIL_DIV_EXPR:
8096     case FLOOR_DIV_EXPR:
8097     case ROUND_DIV_EXPR:
8098     case EXACT_DIV_EXPR:
8099     case BIT_AND_EXPR:
8100     case BIT_IOR_EXPR:
8101     case BIT_XOR_EXPR:
8102     case TRUNC_MOD_EXPR:
8103     case FLOOR_MOD_EXPR:
8104     case TRUTH_ANDIF_EXPR:
8105     case TRUTH_ORIF_EXPR:
8106     case TRUTH_AND_EXPR:
8107     case TRUTH_OR_EXPR:
8108     case RSHIFT_EXPR:
8109     case LSHIFT_EXPR:
8110     case RROTATE_EXPR:
8111     case LROTATE_EXPR:
8112     case EQ_EXPR:
8113     case NE_EXPR:
8114     case MAX_EXPR:
8115     case MIN_EXPR:
8116     case LE_EXPR:
8117     case GE_EXPR:
8118     case LT_EXPR:
8119     case GT_EXPR:
8120     case COMPOUND_EXPR:
8121     case DOTSTAR_EXPR:
8122     case MEMBER_REF:
8123     case PREDECREMENT_EXPR:
8124     case PREINCREMENT_EXPR:
8125     case POSTDECREMENT_EXPR:
8126     case POSTINCREMENT_EXPR:
8127       return build_nt
8128         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8129          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
8130
8131     case SCOPE_REF:
8132       return build_qualified_name (/*type=*/NULL_TREE,
8133                                    tsubst_copy (TREE_OPERAND (t, 0),
8134                                                 args, complain, in_decl),
8135                                    tsubst_copy (TREE_OPERAND (t, 1),
8136                                                 args, complain, in_decl),
8137                                    QUALIFIED_NAME_IS_TEMPLATE (t));
8138
8139     case ARRAY_REF:
8140       return build_nt
8141         (ARRAY_REF,
8142          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8143          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
8144          NULL_TREE, NULL_TREE);
8145
8146     case CALL_EXPR:
8147       return build_nt (code,
8148                        tsubst_copy (TREE_OPERAND (t, 0), args,
8149                                     complain, in_decl),
8150                        tsubst_copy (TREE_OPERAND (t, 1), args, complain,
8151                                     in_decl),
8152                        NULL_TREE);
8153
8154     case COND_EXPR:
8155     case MODOP_EXPR:
8156     case PSEUDO_DTOR_EXPR:
8157       {
8158         r = build_nt
8159           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8160            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
8161            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
8162         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
8163         return r;
8164       }
8165
8166     case NEW_EXPR:
8167       {
8168         r = build_nt
8169         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8170          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
8171          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
8172         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
8173         return r;
8174       }
8175
8176     case DELETE_EXPR:
8177       {
8178         r = build_nt
8179         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8180          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
8181         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
8182         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
8183         return r;
8184       }
8185
8186     case TEMPLATE_ID_EXPR:
8187       {
8188         /* Substituted template arguments */
8189         tree fn = TREE_OPERAND (t, 0);
8190         tree targs = TREE_OPERAND (t, 1);
8191
8192         fn = tsubst_copy (fn, args, complain, in_decl);
8193         if (targs)
8194           targs = tsubst_template_args (targs, args, complain, in_decl);
8195
8196         return lookup_template_function (fn, targs);
8197       }
8198
8199     case TREE_LIST:
8200       {
8201         tree purpose, value, chain;
8202
8203         if (t == void_list_node)
8204           return t;
8205
8206         purpose = TREE_PURPOSE (t);
8207         if (purpose)
8208           purpose = tsubst_copy (purpose, args, complain, in_decl);
8209         value = TREE_VALUE (t);
8210         if (value)
8211           value = tsubst_copy (value, args, complain, in_decl);
8212         chain = TREE_CHAIN (t);
8213         if (chain && chain != void_type_node)
8214           chain = tsubst_copy (chain, args, complain, in_decl);
8215         if (purpose == TREE_PURPOSE (t)
8216             && value == TREE_VALUE (t)
8217             && chain == TREE_CHAIN (t))
8218           return t;
8219         return tree_cons (purpose, value, chain);
8220       }
8221
8222     case RECORD_TYPE:
8223     case UNION_TYPE:
8224     case ENUMERAL_TYPE:
8225     case INTEGER_TYPE:
8226     case TEMPLATE_TYPE_PARM:
8227     case TEMPLATE_TEMPLATE_PARM:
8228     case BOUND_TEMPLATE_TEMPLATE_PARM:
8229     case TEMPLATE_PARM_INDEX:
8230     case POINTER_TYPE:
8231     case REFERENCE_TYPE:
8232     case OFFSET_TYPE:
8233     case FUNCTION_TYPE:
8234     case METHOD_TYPE:
8235     case ARRAY_TYPE:
8236     case TYPENAME_TYPE:
8237     case UNBOUND_CLASS_TEMPLATE:
8238     case TYPEOF_TYPE:
8239     case TYPE_DECL:
8240       return tsubst (t, args, complain, in_decl);
8241
8242     case IDENTIFIER_NODE:
8243       if (IDENTIFIER_TYPENAME_P (t))
8244         {
8245           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8246           return mangle_conv_op_name_for_type (new_type);
8247         }
8248       else
8249         return t;
8250
8251     case CONSTRUCTOR:
8252       /* This is handled by tsubst_copy_and_build.  */
8253       gcc_unreachable ();
8254
8255     case VA_ARG_EXPR:
8256       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
8257                                           in_decl),
8258                              tsubst (TREE_TYPE (t), args, complain, in_decl));
8259
8260     case CLEANUP_POINT_EXPR:
8261       /* We shouldn't have built any of these during initial template
8262          generation.  Instead, they should be built during instantiation
8263          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
8264       gcc_unreachable ();
8265
8266     case OFFSET_REF:
8267       mark_used (TREE_OPERAND (t, 1));
8268       return t;
8269
8270     default:
8271       return t;
8272     }
8273 }
8274
8275 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
8276
8277 static tree
8278 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
8279                           tree in_decl)
8280 {
8281 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
8282
8283   tree purpose, value, chain;
8284
8285   if (t == NULL)
8286     return t;
8287
8288   if (TREE_CODE (t) != TREE_LIST)
8289     return tsubst_copy_and_build (t, args, complain, in_decl,
8290                                   /*function_p=*/false);
8291
8292   if (t == void_list_node)
8293     return t;
8294
8295   purpose = TREE_PURPOSE (t);
8296   if (purpose)
8297     purpose = RECUR (purpose);
8298   value = TREE_VALUE (t);
8299   if (value)
8300     value = RECUR (value);
8301   chain = TREE_CHAIN (t);
8302   if (chain && chain != void_type_node)
8303     chain = RECUR (chain);
8304   return tree_cons (purpose, value, chain);
8305 #undef RECUR
8306 }
8307
8308 /* Like tsubst_copy for expressions, etc. but also does semantic
8309    processing.  */
8310
8311 static tree
8312 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8313 {
8314   tree stmt, tmp;
8315
8316   if (t == NULL_TREE || t == error_mark_node)
8317     return t;
8318
8319   if (EXPR_HAS_LOCATION (t))
8320     input_location = EXPR_LOCATION (t);
8321   if (STATEMENT_CODE_P (TREE_CODE (t)))
8322     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
8323
8324   switch (TREE_CODE (t))
8325     {
8326     case STATEMENT_LIST:
8327       {
8328         tree_stmt_iterator i;
8329         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
8330           tsubst_expr (tsi_stmt (i), args, complain, in_decl);
8331         break;
8332       }
8333
8334     case CTOR_INITIALIZER:
8335       finish_mem_initializers (tsubst_initializer_list
8336                                (TREE_OPERAND (t, 0), args));
8337       break;
8338
8339     case RETURN_EXPR:
8340       finish_return_stmt (tsubst_expr (TREE_OPERAND (t, 0),
8341                                        args, complain, in_decl));
8342       break;
8343
8344     case EXPR_STMT:
8345       tmp = tsubst_expr (EXPR_STMT_EXPR (t), args, complain, in_decl);
8346       if (EXPR_STMT_STMT_EXPR_RESULT (t))
8347         finish_stmt_expr_expr (tmp, cur_stmt_expr);
8348       else
8349         finish_expr_stmt (tmp);
8350       break;
8351
8352     case USING_STMT:
8353       do_using_directive (tsubst_expr (USING_STMT_NAMESPACE (t),
8354                                        args, complain, in_decl));
8355       break;
8356
8357     case DECL_EXPR:
8358       {
8359         tree decl;
8360         tree init;
8361
8362         decl = DECL_EXPR_DECL (t);
8363         if (TREE_CODE (decl) == LABEL_DECL)
8364           finish_label_decl (DECL_NAME (decl));
8365         else if (TREE_CODE (decl) == USING_DECL)
8366           {
8367             tree scope = USING_DECL_SCOPE (decl);
8368             tree name = DECL_NAME (decl);
8369             tree decl;
8370
8371             scope = tsubst_expr (scope, args, complain, in_decl);
8372             decl = lookup_qualified_name (scope, name,
8373                                           /*is_type_p=*/false,
8374                                           /*complain=*/false);
8375             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
8376               qualified_name_lookup_error (scope, name, decl);
8377             else
8378               do_local_using_decl (decl, scope, name);
8379           }
8380         else
8381           {
8382             init = DECL_INITIAL (decl);
8383             decl = tsubst (decl, args, complain, in_decl);
8384             if (decl != error_mark_node)
8385               {
8386                 if (init)
8387                   DECL_INITIAL (decl) = error_mark_node;
8388                 /* By marking the declaration as instantiated, we avoid
8389                    trying to instantiate it.  Since instantiate_decl can't
8390                    handle local variables, and since we've already done
8391                    all that needs to be done, that's the right thing to
8392                    do.  */
8393                 if (TREE_CODE (decl) == VAR_DECL)
8394                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
8395                 if (TREE_CODE (decl) == VAR_DECL
8396                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
8397                   /* Anonymous aggregates are a special case.  */
8398                   finish_anon_union (decl);
8399                 else
8400                   {
8401                     maybe_push_decl (decl);
8402                     if (TREE_CODE (decl) == VAR_DECL
8403                         && DECL_PRETTY_FUNCTION_P (decl))
8404                       {
8405                         /* For __PRETTY_FUNCTION__ we have to adjust the
8406                            initializer.  */
8407                         const char *const name
8408                           = cxx_printable_name (current_function_decl, 2);
8409                         init = cp_fname_init (name, &TREE_TYPE (decl));
8410                       }
8411                     else
8412                       init = tsubst_expr (init, args, complain, in_decl);
8413                     finish_decl (decl, init, NULL_TREE);
8414                   }
8415               }
8416           }
8417
8418         /* A DECL_EXPR can also be used as an expression, in the condition
8419            clause of an if/for/while construct.  */
8420         return decl;
8421       }
8422
8423     case FOR_STMT:
8424       stmt = begin_for_stmt ();
8425       tsubst_expr (FOR_INIT_STMT (t), args, complain, in_decl);
8426       finish_for_init_stmt (stmt);
8427       tmp = tsubst_expr (FOR_COND (t), args, complain, in_decl);
8428       finish_for_cond (tmp, stmt);
8429       tmp = tsubst_expr (FOR_EXPR (t), args, complain, in_decl);
8430       finish_for_expr (tmp, stmt);
8431       tsubst_expr (FOR_BODY (t), args, complain, in_decl);
8432       finish_for_stmt (stmt);
8433       break;
8434
8435     case WHILE_STMT:
8436       stmt = begin_while_stmt ();
8437       tmp = tsubst_expr (WHILE_COND (t), args, complain, in_decl);
8438       finish_while_stmt_cond (tmp, stmt);
8439       tsubst_expr (WHILE_BODY (t), args, complain, in_decl);
8440       finish_while_stmt (stmt);
8441       break;
8442
8443     case DO_STMT:
8444       stmt = begin_do_stmt ();
8445       tsubst_expr (DO_BODY (t), args, complain, in_decl);
8446       finish_do_body (stmt);
8447       tmp = tsubst_expr (DO_COND (t), args, complain, in_decl);
8448       finish_do_stmt (tmp, stmt);
8449       break;
8450
8451     case IF_STMT:
8452       stmt = begin_if_stmt ();
8453       tmp = tsubst_expr (IF_COND (t), args, complain, in_decl);
8454       finish_if_stmt_cond (tmp, stmt);
8455       tsubst_expr (THEN_CLAUSE (t), args, complain, in_decl);
8456       finish_then_clause (stmt);
8457
8458       if (ELSE_CLAUSE (t))
8459         {
8460           begin_else_clause (stmt);
8461           tsubst_expr (ELSE_CLAUSE (t), args, complain, in_decl);
8462           finish_else_clause (stmt);
8463         }
8464
8465       finish_if_stmt (stmt);
8466       break;
8467
8468     case BIND_EXPR:
8469       if (BIND_EXPR_BODY_BLOCK (t))
8470         stmt = begin_function_body ();
8471       else
8472         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
8473                                     ? BCS_TRY_BLOCK : 0);
8474
8475       tsubst_expr (BIND_EXPR_BODY (t), args, complain, in_decl);
8476
8477       if (BIND_EXPR_BODY_BLOCK (t))
8478         finish_function_body (stmt);
8479       else
8480         finish_compound_stmt (stmt);
8481       break;
8482
8483     case BREAK_STMT:
8484       finish_break_stmt ();
8485       break;
8486
8487     case CONTINUE_STMT:
8488       finish_continue_stmt ();
8489       break;
8490
8491     case SWITCH_STMT:
8492       stmt = begin_switch_stmt ();
8493       tmp = tsubst_expr (SWITCH_STMT_COND (t), args, complain, in_decl);
8494       finish_switch_cond (tmp, stmt);
8495       tsubst_expr (SWITCH_STMT_BODY (t), args, complain, in_decl);
8496       finish_switch_stmt (stmt);
8497       break;
8498
8499     case CASE_LABEL_EXPR:
8500       finish_case_label (tsubst_expr (CASE_LOW (t), args, complain, in_decl),
8501                          tsubst_expr (CASE_HIGH (t), args, complain,
8502                                       in_decl));
8503       break;
8504
8505     case LABEL_EXPR:
8506       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
8507       break;
8508
8509     case GOTO_EXPR:
8510       tmp = GOTO_DESTINATION (t);
8511       if (TREE_CODE (tmp) != LABEL_DECL)
8512         /* Computed goto's must be tsubst'd into.  On the other hand,
8513            non-computed gotos must not be; the identifier in question
8514            will have no binding.  */
8515         tmp = tsubst_expr (tmp, args, complain, in_decl);
8516       else
8517         tmp = DECL_NAME (tmp);
8518       finish_goto_stmt (tmp);
8519       break;
8520
8521     case ASM_EXPR:
8522       tmp = finish_asm_stmt
8523         (ASM_VOLATILE_P (t),
8524          tsubst_expr (ASM_STRING (t), args, complain, in_decl),
8525          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
8526          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
8527          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
8528       {
8529         tree asm_expr = tmp;
8530         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
8531           asm_expr = TREE_OPERAND (asm_expr, 0);
8532         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
8533       }
8534       break;
8535
8536     case TRY_BLOCK:
8537       if (CLEANUP_P (t))
8538         {
8539           stmt = begin_try_block ();
8540           tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
8541           finish_cleanup_try_block (stmt);
8542           finish_cleanup (tsubst_expr (TRY_HANDLERS (t), args,
8543                                        complain, in_decl),
8544                           stmt);
8545         }
8546       else
8547         {
8548           tree compound_stmt = NULL_TREE;
8549
8550           if (FN_TRY_BLOCK_P (t))
8551             stmt = begin_function_try_block (&compound_stmt);
8552           else
8553             stmt = begin_try_block ();
8554
8555           tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
8556
8557           if (FN_TRY_BLOCK_P (t))
8558             finish_function_try_block (stmt);
8559           else
8560             finish_try_block (stmt);
8561
8562           tsubst_expr (TRY_HANDLERS (t), args, complain, in_decl);
8563           if (FN_TRY_BLOCK_P (t))
8564             finish_function_handler_sequence (stmt, compound_stmt);
8565           else
8566             finish_handler_sequence (stmt);
8567         }
8568       break;
8569
8570     case HANDLER:
8571       {
8572         tree decl;
8573
8574         stmt = begin_handler ();
8575         if (HANDLER_PARMS (t))
8576           {
8577             decl = HANDLER_PARMS (t);
8578             decl = tsubst (decl, args, complain, in_decl);
8579             /* Prevent instantiate_decl from trying to instantiate
8580                this variable.  We've already done all that needs to be
8581                done.  */
8582             DECL_TEMPLATE_INSTANTIATED (decl) = 1;
8583           }
8584         else
8585           decl = NULL_TREE;
8586         finish_handler_parms (decl, stmt);
8587         tsubst_expr (HANDLER_BODY (t), args, complain, in_decl);
8588         finish_handler (stmt);
8589       }
8590       break;
8591
8592     case TAG_DEFN:
8593       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
8594       break;
8595
8596     default:
8597       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
8598
8599       return tsubst_copy_and_build (t, args, complain, in_decl,
8600                                     /*function_p=*/false);
8601     }
8602
8603   return NULL_TREE;
8604 }
8605
8606 /* T is a postfix-expression that is not being used in a function
8607    call.  Return the substituted version of T.  */
8608
8609 static tree
8610 tsubst_non_call_postfix_expression (tree t, tree args,
8611                                     tsubst_flags_t complain,
8612                                     tree in_decl)
8613 {
8614   if (TREE_CODE (t) == SCOPE_REF)
8615     t = tsubst_qualified_id (t, args, complain, in_decl,
8616                              /*done=*/false, /*address_p=*/false);
8617   else
8618     t = tsubst_copy_and_build (t, args, complain, in_decl,
8619                                /*function_p=*/false);
8620
8621   return t;
8622 }
8623
8624 /* Like tsubst but deals with expressions and performs semantic
8625    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
8626
8627 tree
8628 tsubst_copy_and_build (tree t,
8629                        tree args,
8630                        tsubst_flags_t complain,
8631                        tree in_decl,
8632                        bool function_p)
8633 {
8634 #define RECUR(NODE) \
8635   tsubst_copy_and_build (NODE, args, complain, in_decl, /*function_p=*/false)
8636
8637   tree op1;
8638
8639   if (t == NULL_TREE || t == error_mark_node)
8640     return t;
8641
8642   switch (TREE_CODE (t))
8643     {
8644     case USING_DECL:
8645       t = DECL_NAME (t);
8646       /* Fall through.  */
8647     case IDENTIFIER_NODE:
8648       {
8649         tree decl;
8650         cp_id_kind idk;
8651         bool non_integral_constant_expression_p;
8652         const char *error_msg;
8653
8654         if (IDENTIFIER_TYPENAME_P (t))
8655           {
8656             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8657             t = mangle_conv_op_name_for_type (new_type);
8658           }
8659
8660         /* Look up the name.  */
8661         decl = lookup_name (t, 0);
8662
8663         /* By convention, expressions use ERROR_MARK_NODE to indicate
8664            failure, not NULL_TREE.  */
8665         if (decl == NULL_TREE)
8666           decl = error_mark_node;
8667
8668         decl = finish_id_expression (t, decl, NULL_TREE,
8669                                      &idk,
8670                                      /*integral_constant_expression_p=*/false,
8671                                      /*allow_non_integral_constant_expression_p=*/false,
8672                                      &non_integral_constant_expression_p,
8673                                      /*template_p=*/false,
8674                                      /*done=*/true,
8675                                      /*address_p=*/false,
8676                                      /*template_arg_p=*/false,
8677                                      &error_msg);
8678         if (error_msg)
8679           error (error_msg);
8680         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
8681           decl = unqualified_name_lookup_error (decl);
8682         return decl;
8683       }
8684
8685     case TEMPLATE_ID_EXPR:
8686       {
8687         tree object;
8688         tree template = RECUR (TREE_OPERAND (t, 0));
8689         tree targs = TREE_OPERAND (t, 1);
8690
8691         if (targs)
8692           targs = tsubst_template_args (targs, args, complain, in_decl);
8693
8694         if (TREE_CODE (template) == COMPONENT_REF)
8695           {
8696             object = TREE_OPERAND (template, 0);
8697             template = TREE_OPERAND (template, 1);
8698           }
8699         else
8700           object = NULL_TREE;
8701         template = lookup_template_function (template, targs);
8702
8703         if (object)
8704           return build3 (COMPONENT_REF, TREE_TYPE (template),
8705                          object, template, NULL_TREE);
8706         else
8707           return template;
8708       }
8709
8710     case INDIRECT_REF:
8711       {
8712         tree r = RECUR (TREE_OPERAND (t, 0));
8713
8714         if (REFERENCE_REF_P (t))
8715           {
8716             /* A type conversion to reference type will be enclosed in
8717                such an indirect ref, but the substitution of the cast
8718                will have also added such an indirect ref.  */
8719             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
8720               r = convert_from_reference (r);
8721           }
8722         else
8723           r = build_x_indirect_ref (r, "unary *");
8724         return r;
8725       }
8726
8727     case NOP_EXPR:
8728       return build_nop
8729         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8730          RECUR (TREE_OPERAND (t, 0)));
8731
8732     case CAST_EXPR:
8733       return build_functional_cast
8734         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8735          RECUR (TREE_OPERAND (t, 0)));
8736
8737     case REINTERPRET_CAST_EXPR:
8738       return build_reinterpret_cast
8739         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8740          RECUR (TREE_OPERAND (t, 0)));
8741
8742     case CONST_CAST_EXPR:
8743       return build_const_cast
8744         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8745          RECUR (TREE_OPERAND (t, 0)));
8746
8747     case DYNAMIC_CAST_EXPR:
8748       return build_dynamic_cast
8749         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8750          RECUR (TREE_OPERAND (t, 0)));
8751
8752     case STATIC_CAST_EXPR:
8753       return build_static_cast
8754         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8755          RECUR (TREE_OPERAND (t, 0)));
8756
8757     case POSTDECREMENT_EXPR:
8758     case POSTINCREMENT_EXPR:
8759       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
8760                                                 args, complain, in_decl);
8761       return build_x_unary_op (TREE_CODE (t), op1);
8762
8763     case PREDECREMENT_EXPR:
8764     case PREINCREMENT_EXPR:
8765     case NEGATE_EXPR:
8766     case BIT_NOT_EXPR:
8767     case ABS_EXPR:
8768     case TRUTH_NOT_EXPR:
8769     case UNARY_PLUS_EXPR:  /* Unary + */
8770     case REALPART_EXPR:
8771     case IMAGPART_EXPR:
8772       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
8773
8774     case ADDR_EXPR:
8775       op1 = TREE_OPERAND (t, 0);
8776       if (TREE_CODE (op1) == SCOPE_REF)
8777         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
8778                                    /*done=*/true, /*address_p=*/true);
8779       else
8780         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
8781                                                   in_decl);
8782       if (TREE_CODE (op1) == LABEL_DECL)
8783         return finish_label_address_expr (DECL_NAME (op1));
8784       return build_x_unary_op (ADDR_EXPR, op1);
8785
8786     case PLUS_EXPR:
8787     case MINUS_EXPR:
8788     case MULT_EXPR:
8789     case TRUNC_DIV_EXPR:
8790     case CEIL_DIV_EXPR:
8791     case FLOOR_DIV_EXPR:
8792     case ROUND_DIV_EXPR:
8793     case EXACT_DIV_EXPR:
8794     case BIT_AND_EXPR:
8795     case BIT_IOR_EXPR:
8796     case BIT_XOR_EXPR:
8797     case TRUNC_MOD_EXPR:
8798     case FLOOR_MOD_EXPR:
8799     case TRUTH_ANDIF_EXPR:
8800     case TRUTH_ORIF_EXPR:
8801     case TRUTH_AND_EXPR:
8802     case TRUTH_OR_EXPR:
8803     case RSHIFT_EXPR:
8804     case LSHIFT_EXPR:
8805     case RROTATE_EXPR:
8806     case LROTATE_EXPR:
8807     case EQ_EXPR:
8808     case NE_EXPR:
8809     case MAX_EXPR:
8810     case MIN_EXPR:
8811     case LE_EXPR:
8812     case GE_EXPR:
8813     case LT_EXPR:
8814     case GT_EXPR:
8815     case MEMBER_REF:
8816     case DOTSTAR_EXPR:
8817       return build_x_binary_op
8818         (TREE_CODE (t),
8819          RECUR (TREE_OPERAND (t, 0)),
8820          RECUR (TREE_OPERAND (t, 1)),
8821          /*overloaded_p=*/NULL);
8822
8823     case SCOPE_REF:
8824       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
8825                                   /*address_p=*/false);
8826     case ARRAY_REF:
8827       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
8828                                                 args, complain, in_decl);
8829       return build_x_binary_op (ARRAY_REF, op1, RECUR (TREE_OPERAND (t, 1)),
8830                                 /*overloaded_p=*/NULL);
8831
8832     case SIZEOF_EXPR:
8833     case ALIGNOF_EXPR:
8834       op1 = TREE_OPERAND (t, 0);
8835       if (!args)
8836         {
8837           /* When there are no ARGS, we are trying to evaluate a
8838              non-dependent expression from the parser.  Trying to do
8839              the substitutions may not work.  */
8840           if (!TYPE_P (op1))
8841             op1 = TREE_TYPE (op1);
8842         }
8843       else
8844         {
8845           ++skip_evaluation;
8846           op1 = RECUR (op1);
8847           --skip_evaluation;
8848         }
8849       if (TYPE_P (op1))
8850         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
8851       else
8852         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
8853
8854     case MODOP_EXPR:
8855       {
8856         tree r = build_x_modify_expr
8857           (RECUR (TREE_OPERAND (t, 0)),
8858            TREE_CODE (TREE_OPERAND (t, 1)),
8859            RECUR (TREE_OPERAND (t, 2)));
8860         /* TREE_NO_WARNING must be set if either the expression was
8861            parenthesized or it uses an operator such as >>= rather
8862            than plain assignment.  In the former case, it was already
8863            set and must be copied.  In the latter case,
8864            build_x_modify_expr sets it and it must not be reset
8865            here.  */
8866         if (TREE_NO_WARNING (t))
8867           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
8868         return r;
8869       }
8870
8871     case ARROW_EXPR:
8872       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
8873                                                 args, complain, in_decl);
8874       /* Remember that there was a reference to this entity.  */
8875       if (DECL_P (op1))
8876         mark_used (op1);
8877       return build_x_arrow (op1);
8878
8879     case NEW_EXPR:
8880       return build_new
8881         (RECUR (TREE_OPERAND (t, 0)),
8882          RECUR (TREE_OPERAND (t, 1)),
8883          RECUR (TREE_OPERAND (t, 2)),
8884          RECUR (TREE_OPERAND (t, 3)),
8885          NEW_EXPR_USE_GLOBAL (t));
8886
8887     case DELETE_EXPR:
8888      return delete_sanity
8889        (RECUR (TREE_OPERAND (t, 0)),
8890         RECUR (TREE_OPERAND (t, 1)),
8891         DELETE_EXPR_USE_VEC (t),
8892         DELETE_EXPR_USE_GLOBAL (t));
8893
8894     case COMPOUND_EXPR:
8895       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
8896                                     RECUR (TREE_OPERAND (t, 1)));
8897
8898     case CALL_EXPR:
8899       {
8900         tree function;
8901         tree call_args;
8902         bool qualified_p;
8903         bool koenig_p;
8904
8905         function = TREE_OPERAND (t, 0);
8906         /* When we parsed the expression,  we determined whether or
8907            not Koenig lookup should be performed.  */
8908         koenig_p = KOENIG_LOOKUP_P (t);
8909         if (TREE_CODE (function) == SCOPE_REF)
8910           {
8911             qualified_p = true;
8912             function = tsubst_qualified_id (function, args, complain, in_decl,
8913                                             /*done=*/false,
8914                                             /*address_p=*/false);
8915           }
8916         else
8917           {
8918             if (TREE_CODE (function) == COMPONENT_REF)
8919               {
8920                 tree op = TREE_OPERAND (function, 1);
8921
8922                 qualified_p = (TREE_CODE (op) == SCOPE_REF
8923                                || (BASELINK_P (op)
8924                                    && BASELINK_QUALIFIED_P (op)));
8925               }
8926             else
8927               qualified_p = false;
8928             
8929             function = tsubst_copy_and_build (function, args, complain,
8930                                               in_decl,
8931                                               !qualified_p);
8932             if (BASELINK_P (function))
8933               qualified_p = true;
8934           }
8935
8936         call_args = RECUR (TREE_OPERAND (t, 1));
8937
8938         /* We do not perform argument-dependent lookup if normal
8939            lookup finds a non-function, in accordance with the
8940            expected resolution of DR 218.  */
8941         if (koenig_p
8942             && ((is_overloaded_fn (function)
8943                  /* If lookup found a member function, the Koenig lookup is
8944                     not appropriate, even if an unqualified-name was used
8945                     to denote the function.  */
8946                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
8947                 || TREE_CODE (function) == IDENTIFIER_NODE))
8948           function = perform_koenig_lookup (function, call_args);
8949
8950         if (TREE_CODE (function) == IDENTIFIER_NODE)
8951           {
8952             unqualified_name_lookup_error (function);
8953             return error_mark_node;
8954           }
8955
8956         /* Remember that there was a reference to this entity.  */
8957         if (DECL_P (function))
8958           mark_used (function);
8959
8960         if (TREE_CODE (function) == OFFSET_REF)
8961           return build_offset_ref_call_from_tree (function, call_args);
8962         if (TREE_CODE (function) == COMPONENT_REF)
8963           {
8964             if (!BASELINK_P (TREE_OPERAND (function, 1)))
8965               return finish_call_expr (function, call_args,
8966                                        /*disallow_virtual=*/false,
8967                                        /*koenig_p=*/false);
8968             else
8969               return (build_new_method_call
8970                       (TREE_OPERAND (function, 0),
8971                        TREE_OPERAND (function, 1),
8972                        call_args, NULL_TREE,
8973                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL));
8974           }
8975         return finish_call_expr (function, call_args,
8976                                  /*disallow_virtual=*/qualified_p,
8977                                  koenig_p);
8978       }
8979
8980     case COND_EXPR:
8981       return build_x_conditional_expr
8982         (RECUR (TREE_OPERAND (t, 0)),
8983          RECUR (TREE_OPERAND (t, 1)),
8984          RECUR (TREE_OPERAND (t, 2)));
8985
8986     case PSEUDO_DTOR_EXPR:
8987       return finish_pseudo_destructor_expr
8988         (RECUR (TREE_OPERAND (t, 0)),
8989          RECUR (TREE_OPERAND (t, 1)),
8990          RECUR (TREE_OPERAND (t, 2)));
8991
8992     case TREE_LIST:
8993       {
8994         tree purpose, value, chain;
8995
8996         if (t == void_list_node)
8997           return t;
8998
8999         purpose = TREE_PURPOSE (t);
9000         if (purpose)
9001           purpose = RECUR (purpose);
9002         value = TREE_VALUE (t);
9003         if (value)
9004           value = RECUR (value);
9005         chain = TREE_CHAIN (t);
9006         if (chain && chain != void_type_node)
9007           chain = RECUR (chain);
9008         if (purpose == TREE_PURPOSE (t)
9009             && value == TREE_VALUE (t)
9010             && chain == TREE_CHAIN (t))
9011           return t;
9012         return tree_cons (purpose, value, chain);
9013       }
9014
9015     case COMPONENT_REF:
9016       {
9017         tree object;
9018         tree object_type;
9019         tree member;
9020
9021         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
9022                                                      args, complain, in_decl);
9023         /* Remember that there was a reference to this entity.  */
9024         if (DECL_P (object))
9025           mark_used (object);
9026         object_type = TREE_TYPE (object);
9027
9028         member = TREE_OPERAND (t, 1);
9029         if (BASELINK_P (member))
9030           member = tsubst_baselink (member,
9031                                     non_reference (TREE_TYPE (object)),
9032                                     args, complain, in_decl);
9033         else
9034           member = tsubst_copy (member, args, complain, in_decl);
9035         if (member == error_mark_node)
9036           return error_mark_node;
9037
9038         if (object_type && !CLASS_TYPE_P (object_type))
9039           {
9040             if (TREE_CODE (member) == BIT_NOT_EXPR)
9041               return finish_pseudo_destructor_expr (object,
9042                                                     NULL_TREE,
9043                                                     object_type);
9044             else if (TREE_CODE (member) == SCOPE_REF
9045                      && (TREE_CODE (TREE_OPERAND (member, 1)) == BIT_NOT_EXPR))
9046               return finish_pseudo_destructor_expr (object,
9047                                                     object,
9048                                                     object_type);
9049           }
9050         else if (TREE_CODE (member) == SCOPE_REF
9051                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
9052           {
9053             tree tmpl;
9054             tree args;
9055
9056             /* Lookup the template functions now that we know what the
9057                scope is.  */
9058             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
9059             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
9060             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
9061                                             /*is_type_p=*/false,
9062                                             /*complain=*/false);
9063             if (BASELINK_P (member))
9064               {
9065                 BASELINK_FUNCTIONS (member)
9066                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
9067                               args);
9068                 member = (adjust_result_of_qualified_name_lookup
9069                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
9070                            object_type));
9071               }
9072             else
9073               {
9074                 qualified_name_lookup_error (object_type, tmpl, member);
9075                 return error_mark_node;
9076               }
9077           }
9078         else if (TREE_CODE (member) == SCOPE_REF
9079                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
9080                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
9081           {
9082             if (complain & tf_error)
9083               {
9084                 if (TYPE_P (TREE_OPERAND (member, 0)))
9085                   error ("%qT is not a class or namespace",
9086                          TREE_OPERAND (member, 0));
9087                 else
9088                   error ("%qD is not a class or namespace",
9089                          TREE_OPERAND (member, 0));
9090               }
9091             return error_mark_node;
9092           }
9093         else if (TREE_CODE (member) == FIELD_DECL)
9094           return finish_non_static_data_member (member, object, NULL_TREE);
9095
9096         return finish_class_member_access_expr (object, member,
9097                                                 /*template_p=*/false);
9098       }
9099
9100     case THROW_EXPR:
9101       return build_throw
9102         (RECUR (TREE_OPERAND (t, 0)));
9103
9104     case CONSTRUCTOR:
9105       {
9106         VEC(constructor_elt,gc) *n;
9107         constructor_elt *ce;
9108         unsigned HOST_WIDE_INT idx;
9109         tree r;
9110         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9111         bool process_index_p;
9112
9113         /* digest_init will do the wrong thing if we let it.  */
9114         if (type && TYPE_PTRMEMFUNC_P (type))
9115           return t;
9116
9117         /* We do not want to process the index of aggregate
9118            initializers as they are identifier nodes which will be
9119            looked up by digest_init.  */
9120         process_index_p = !(type && IS_AGGR_TYPE (type));
9121
9122         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
9123         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
9124           {
9125             if (ce->index && process_index_p)
9126               ce->index = RECUR (ce->index);
9127             ce->value = RECUR (ce->value);
9128           }
9129
9130         r = build_constructor (NULL_TREE, n);
9131         TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
9132
9133         if (type)
9134           return digest_init (type, r);
9135         return r;
9136       }
9137
9138     case TYPEID_EXPR:
9139       {
9140         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
9141         if (TYPE_P (operand_0))
9142           return get_typeid (operand_0);
9143         return build_typeid (operand_0);
9144       }
9145
9146     case VAR_DECL:
9147       if (!args)
9148         return t;
9149       /* Fall through */
9150
9151     case PARM_DECL:
9152       {
9153         tree r = tsubst_copy (t, args, complain, in_decl);
9154
9155         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
9156           /* If the original type was a reference, we'll be wrapped in
9157              the appropriate INDIRECT_REF.  */
9158           r = convert_from_reference (r);
9159         return r;
9160       }
9161
9162     case VA_ARG_EXPR:
9163       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
9164                              tsubst_copy (TREE_TYPE (t), args, complain,
9165                                           in_decl));
9166
9167     case OFFSETOF_EXPR:
9168       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
9169
9170     case STMT_EXPR:
9171       {
9172         tree old_stmt_expr = cur_stmt_expr;
9173         tree stmt_expr = begin_stmt_expr ();
9174
9175         cur_stmt_expr = stmt_expr;
9176         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
9177         stmt_expr = finish_stmt_expr (stmt_expr, false);
9178         cur_stmt_expr = old_stmt_expr;
9179
9180         return stmt_expr;
9181       }
9182
9183     case CONST_DECL:
9184       t = tsubst_copy (t, args, complain, in_decl);
9185       /* As in finish_id_expression, we resolve enumeration constants
9186          to their underlying values.  */
9187       if (TREE_CODE (t) == CONST_DECL)
9188         return DECL_INITIAL (t);
9189       return t;
9190
9191     default:
9192       /* Handle Objective-C++ constructs, if appropriate.  */
9193       {
9194         tree subst
9195           = objcp_tsubst_copy_and_build (t, args, complain,
9196                                          in_decl, /*function_p=*/false);
9197         if (subst)
9198           return subst;
9199       }
9200       return tsubst_copy (t, args, complain, in_decl);
9201     }
9202
9203 #undef RECUR
9204 }
9205
9206 /* Verify that the instantiated ARGS are valid. For type arguments,
9207    make sure that the type's linkage is ok. For non-type arguments,
9208    make sure they are constants if they are integral or enumerations.
9209    Emit an error under control of COMPLAIN, and return TRUE on error.  */
9210
9211 static bool
9212 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
9213 {
9214   int ix, len = DECL_NTPARMS (tmpl);
9215   bool result = false;
9216
9217   for (ix = 0; ix != len; ix++)
9218     {
9219       tree t = TREE_VEC_ELT (args, ix);
9220
9221       if (TYPE_P (t))
9222         {
9223           /* [basic.link]: A name with no linkage (notably, the name
9224              of a class or enumeration declared in a local scope)
9225              shall not be used to declare an entity with linkage.
9226              This implies that names with no linkage cannot be used as
9227              template arguments.  */
9228           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
9229
9230           if (nt)
9231             {
9232               /* DR 488 makes use of a type with no linkage cause
9233                  type deduction to fail.  */ 
9234               if (complain & tf_error)
9235                 {
9236                   if (TYPE_ANONYMOUS_P (nt))
9237                     error ("%qT is/uses anonymous type", t);
9238                   else
9239                     error ("%qT uses local type %qT", t, nt);
9240                 }
9241               result = true;
9242             }
9243           /* In order to avoid all sorts of complications, we do not
9244              allow variably-modified types as template arguments.  */
9245           else if (variably_modified_type_p (t, NULL_TREE))
9246             {
9247               if (complain & tf_error)
9248                 error ("%qT is a variably modified type", t);
9249               result = true;
9250             }
9251         }
9252       /* A non-type argument of integral or enumerated type must be a
9253          constant.  */
9254       else if (TREE_TYPE (t)
9255                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
9256                && !TREE_CONSTANT (t))
9257         {
9258           if (complain & tf_error)
9259             error ("integral expression %qE is not constant", t);
9260           result = true;
9261         }
9262     }
9263   if (result && (complain & tf_error))
9264     error ("  trying to instantiate %qD", tmpl);
9265   return result;
9266 }
9267
9268 /* Instantiate the indicated variable or function template TMPL with
9269    the template arguments in TARG_PTR.  */
9270
9271 tree
9272 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
9273 {
9274   tree fndecl;
9275   tree gen_tmpl;
9276   tree spec;
9277
9278   if (tmpl == error_mark_node)
9279     return error_mark_node;
9280
9281   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
9282
9283   /* If this function is a clone, handle it specially.  */
9284   if (DECL_CLONED_FUNCTION_P (tmpl))
9285     {
9286       tree spec;
9287       tree clone;
9288
9289       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
9290                                    complain);
9291       if (spec == error_mark_node)
9292         return error_mark_node;
9293
9294       /* Look for the clone.  */
9295       FOR_EACH_CLONE (clone, spec)
9296         if (DECL_NAME (clone) == DECL_NAME (tmpl))
9297           return clone;
9298       /* We should always have found the clone by now.  */
9299       gcc_unreachable ();
9300       return NULL_TREE;
9301     }
9302
9303   /* Check to see if we already have this specialization.  */
9304   spec = retrieve_specialization (tmpl, targ_ptr,
9305                                   /*class_specializations_p=*/false);
9306   if (spec != NULL_TREE)
9307     return spec;
9308
9309   gen_tmpl = most_general_template (tmpl);
9310   if (tmpl != gen_tmpl)
9311     {
9312       /* The TMPL is a partial instantiation.  To get a full set of
9313          arguments we must add the arguments used to perform the
9314          partial instantiation.  */
9315       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
9316                                               targ_ptr);
9317
9318       /* Check to see if we already have this specialization.  */
9319       spec = retrieve_specialization (gen_tmpl, targ_ptr,
9320                                       /*class_specializations_p=*/false);
9321       if (spec != NULL_TREE)
9322         return spec;
9323     }
9324
9325   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
9326                                complain))
9327     return error_mark_node;
9328
9329   /* We are building a FUNCTION_DECL, during which the access of its
9330      parameters and return types have to be checked.  However this
9331      FUNCTION_DECL which is the desired context for access checking
9332      is not built yet.  We solve this chicken-and-egg problem by
9333      deferring all checks until we have the FUNCTION_DECL.  */
9334   push_deferring_access_checks (dk_deferred);
9335
9336   /* Substitute template parameters.  */
9337   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
9338                    targ_ptr, complain, gen_tmpl);
9339   if (fndecl == error_mark_node)
9340     return error_mark_node;
9341
9342   /* Now we know the specialization, compute access previously
9343      deferred.  */
9344   push_access_scope (fndecl);
9345   perform_deferred_access_checks ();
9346   pop_access_scope (fndecl);
9347   pop_deferring_access_checks ();
9348
9349   /* The DECL_TI_TEMPLATE should always be the immediate parent
9350      template, not the most general template.  */
9351   DECL_TI_TEMPLATE (fndecl) = tmpl;
9352
9353   /* If we've just instantiated the main entry point for a function,
9354      instantiate all the alternate entry points as well.  We do this
9355      by cloning the instantiation of the main entry point, not by
9356      instantiating the template clones.  */
9357   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
9358     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
9359
9360   return fndecl;
9361 }
9362
9363 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
9364    arguments that are being used when calling it.  TARGS is a vector
9365    into which the deduced template arguments are placed.
9366
9367    Return zero for success, 2 for an incomplete match that doesn't resolve
9368    all the types, and 1 for complete failure.  An error message will be
9369    printed only for an incomplete match.
9370
9371    If FN is a conversion operator, or we are trying to produce a specific
9372    specialization, RETURN_TYPE is the return type desired.
9373
9374    The EXPLICIT_TARGS are explicit template arguments provided via a
9375    template-id.
9376
9377    The parameter STRICT is one of:
9378
9379    DEDUCE_CALL:
9380      We are deducing arguments for a function call, as in
9381      [temp.deduct.call].
9382
9383    DEDUCE_CONV:
9384      We are deducing arguments for a conversion function, as in
9385      [temp.deduct.conv].
9386
9387    DEDUCE_EXACT:
9388      We are deducing arguments when doing an explicit instantiation
9389      as in [temp.explicit], when determining an explicit specialization
9390      as in [temp.expl.spec], or when taking the address of a function
9391      template, as in [temp.deduct.funcaddr].  */
9392
9393 int
9394 fn_type_unification (tree fn,
9395                      tree explicit_targs,
9396                      tree targs,
9397                      tree args,
9398                      tree return_type,
9399                      unification_kind_t strict,
9400                      int flags)
9401 {
9402   tree parms;
9403   tree fntype;
9404   int result;
9405
9406   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
9407
9408   fntype = TREE_TYPE (fn);
9409   if (explicit_targs)
9410     {
9411       /* [temp.deduct]
9412
9413          The specified template arguments must match the template
9414          parameters in kind (i.e., type, nontype, template), and there
9415          must not be more arguments than there are parameters;
9416          otherwise type deduction fails.
9417
9418          Nontype arguments must match the types of the corresponding
9419          nontype template parameters, or must be convertible to the
9420          types of the corresponding nontype parameters as specified in
9421          _temp.arg.nontype_, otherwise type deduction fails.
9422
9423          All references in the function type of the function template
9424          to the corresponding template parameters are replaced by the
9425          specified template argument values.  If a substitution in a
9426          template parameter or in the function type of the function
9427          template results in an invalid type, type deduction fails.  */
9428       int i;
9429       tree converted_args;
9430       bool incomplete;
9431
9432       if (explicit_targs == error_mark_node)
9433         return 1;
9434
9435       converted_args
9436         = (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
9437                                   explicit_targs, NULL_TREE, tf_none,
9438                                   /*require_all_arguments=*/0));
9439       if (converted_args == error_mark_node)
9440         return 1;
9441
9442       /* Substitute the explicit args into the function type.  This is
9443          necessary so that, for instance, explicitly declared function
9444          arguments can match null pointed constants.  If we were given
9445          an incomplete set of explicit args, we must not do semantic
9446          processing during substitution as we could create partial
9447          instantiations.  */
9448       incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
9449       processing_template_decl += incomplete;
9450       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
9451       processing_template_decl -= incomplete;
9452
9453       if (fntype == error_mark_node)
9454         return 1;
9455
9456       /* Place the explicitly specified arguments in TARGS.  */
9457       for (i = NUM_TMPL_ARGS (converted_args); i--;)
9458         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
9459     }
9460
9461   parms = TYPE_ARG_TYPES (fntype);
9462   /* Never do unification on the 'this' parameter.  */
9463   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
9464     parms = TREE_CHAIN (parms);
9465
9466   if (return_type)
9467     {
9468       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
9469       args = tree_cons (NULL_TREE, return_type, args);
9470     }
9471
9472   /* We allow incomplete unification without an error message here
9473      because the standard doesn't seem to explicitly prohibit it.  Our
9474      callers must be ready to deal with unification failures in any
9475      event.  */
9476   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
9477                                   targs, parms, args, /*subr=*/0,
9478                                   strict, flags);
9479
9480   if (result == 0)
9481     /* All is well so far.  Now, check:
9482
9483        [temp.deduct]
9484
9485        When all template arguments have been deduced, all uses of
9486        template parameters in nondeduced contexts are replaced with
9487        the corresponding deduced argument values.  If the
9488        substitution results in an invalid type, as described above,
9489        type deduction fails.  */
9490     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
9491         == error_mark_node)
9492       return 1;
9493
9494   return result;
9495 }
9496
9497 /* Adjust types before performing type deduction, as described in
9498    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
9499    sections are symmetric.  PARM is the type of a function parameter
9500    or the return type of the conversion function.  ARG is the type of
9501    the argument passed to the call, or the type of the value
9502    initialized with the result of the conversion function.  */
9503
9504 static int
9505 maybe_adjust_types_for_deduction (unification_kind_t strict,
9506                                   tree* parm,
9507                                   tree* arg)
9508 {
9509   int result = 0;
9510
9511   switch (strict)
9512     {
9513     case DEDUCE_CALL:
9514       break;
9515
9516     case DEDUCE_CONV:
9517       {
9518         /* Swap PARM and ARG throughout the remainder of this
9519            function; the handling is precisely symmetric since PARM
9520            will initialize ARG rather than vice versa.  */
9521         tree* temp = parm;
9522         parm = arg;
9523         arg = temp;
9524         break;
9525       }
9526
9527     case DEDUCE_EXACT:
9528       /* There is nothing to do in this case.  */
9529       return 0;
9530
9531     default:
9532       gcc_unreachable ();
9533     }
9534
9535   if (TREE_CODE (*parm) != REFERENCE_TYPE)
9536     {
9537       /* [temp.deduct.call]
9538
9539          If P is not a reference type:
9540
9541          --If A is an array type, the pointer type produced by the
9542          array-to-pointer standard conversion (_conv.array_) is
9543          used in place of A for type deduction; otherwise,
9544
9545          --If A is a function type, the pointer type produced by
9546          the function-to-pointer standard conversion
9547          (_conv.func_) is used in place of A for type deduction;
9548          otherwise,
9549
9550          --If A is a cv-qualified type, the top level
9551          cv-qualifiers of A's type are ignored for type
9552          deduction.  */
9553       if (TREE_CODE (*arg) == ARRAY_TYPE)
9554         *arg = build_pointer_type (TREE_TYPE (*arg));
9555       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
9556         *arg = build_pointer_type (*arg);
9557       else
9558         *arg = TYPE_MAIN_VARIANT (*arg);
9559     }
9560
9561   /* [temp.deduct.call]
9562
9563      If P is a cv-qualified type, the top level cv-qualifiers
9564      of P's type are ignored for type deduction.  If P is a
9565      reference type, the type referred to by P is used for
9566      type deduction.  */
9567   *parm = TYPE_MAIN_VARIANT (*parm);
9568   if (TREE_CODE (*parm) == REFERENCE_TYPE)
9569     {
9570       *parm = TREE_TYPE (*parm);
9571       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
9572     }
9573
9574   /* DR 322. For conversion deduction, remove a reference type on parm
9575      too (which has been swapped into ARG).  */
9576   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
9577     *arg = TREE_TYPE (*arg);
9578
9579   return result;
9580 }
9581
9582 /* Most parms like fn_type_unification.
9583
9584    If SUBR is 1, we're being called recursively (to unify the
9585    arguments of a function or method parameter of a function
9586    template). */
9587
9588 static int
9589 type_unification_real (tree tparms,
9590                        tree targs,
9591                        tree xparms,
9592                        tree xargs,
9593                        int subr,
9594                        unification_kind_t strict,
9595                        int flags)
9596 {
9597   tree parm, arg;
9598   int i;
9599   int ntparms = TREE_VEC_LENGTH (tparms);
9600   int sub_strict;
9601   int saw_undeduced = 0;
9602   tree parms, args;
9603
9604   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
9605   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
9606   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
9607   gcc_assert (ntparms > 0);
9608
9609   switch (strict)
9610     {
9611     case DEDUCE_CALL:
9612       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
9613                     | UNIFY_ALLOW_DERIVED);
9614       break;
9615
9616     case DEDUCE_CONV:
9617       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
9618       break;
9619
9620     case DEDUCE_EXACT:
9621       sub_strict = UNIFY_ALLOW_NONE;
9622       break;
9623
9624     default:
9625       gcc_unreachable ();
9626     }
9627
9628  again:
9629   parms = xparms;
9630   args = xargs;
9631
9632   while (parms && parms != void_list_node
9633          && args && args != void_list_node)
9634     {
9635       parm = TREE_VALUE (parms);
9636       parms = TREE_CHAIN (parms);
9637       arg = TREE_VALUE (args);
9638       args = TREE_CHAIN (args);
9639
9640       if (arg == error_mark_node)
9641         return 1;
9642       if (arg == unknown_type_node)
9643         /* We can't deduce anything from this, but we might get all the
9644            template args from other function args.  */
9645         continue;
9646
9647       /* Conversions will be performed on a function argument that
9648          corresponds with a function parameter that contains only
9649          non-deducible template parameters and explicitly specified
9650          template parameters.  */
9651       if (!uses_template_parms (parm))
9652         {
9653           tree type;
9654
9655           if (!TYPE_P (arg))
9656             type = TREE_TYPE (arg);
9657           else
9658             type = arg;
9659
9660           if (same_type_p (parm, type))
9661             continue;
9662           if (strict != DEDUCE_EXACT
9663               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg, 
9664                                   flags))
9665             continue;
9666           
9667           return 1;
9668         }
9669
9670       if (!TYPE_P (arg))
9671         {
9672           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
9673           if (type_unknown_p (arg))
9674             {
9675               /* [temp.deduct.type] A template-argument can be deduced from
9676                  a pointer to function or pointer to member function
9677                  argument if the set of overloaded functions does not
9678                  contain function templates and at most one of a set of
9679                  overloaded functions provides a unique match.  */
9680
9681               if (resolve_overloaded_unification
9682                   (tparms, targs, parm, arg, strict, sub_strict)
9683                   != 0)
9684                 return 1;
9685               continue;
9686             }
9687           arg = TREE_TYPE (arg);
9688           if (arg == error_mark_node)
9689             return 1;
9690         }
9691
9692       {
9693         int arg_strict = sub_strict;
9694
9695         if (!subr)
9696           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
9697
9698         if (unify (tparms, targs, parm, arg, arg_strict))
9699           return 1;
9700       }
9701     }
9702
9703   /* Fail if we've reached the end of the parm list, and more args
9704      are present, and the parm list isn't variadic.  */
9705   if (args && args != void_list_node && parms == void_list_node)
9706     return 1;
9707   /* Fail if parms are left and they don't have default values.  */
9708   if (parms && parms != void_list_node
9709       && TREE_PURPOSE (parms) == NULL_TREE)
9710     return 1;
9711
9712   if (!subr)
9713     for (i = 0; i < ntparms; i++)
9714       if (!TREE_VEC_ELT (targs, i))
9715         {
9716           tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
9717
9718           /* If this is an undeduced nontype parameter that depends on
9719              a type parameter, try another pass; its type may have been
9720              deduced from a later argument than the one from which
9721              this parameter can be deduced.  */
9722           if (TREE_CODE (tparm) == PARM_DECL
9723               && uses_template_parms (TREE_TYPE (tparm))
9724               && !saw_undeduced++)
9725             goto again;
9726
9727           return 2;
9728         }
9729
9730   return 0;
9731 }
9732
9733 /* Subroutine of type_unification_real.  Args are like the variables at the
9734    call site.  ARG is an overloaded function (or template-id); we try
9735    deducing template args from each of the overloads, and if only one
9736    succeeds, we go with that.  Modifies TARGS and returns 0 on success.  */
9737
9738 static int
9739 resolve_overloaded_unification (tree tparms,
9740                                 tree targs,
9741                                 tree parm,
9742                                 tree arg,
9743                                 unification_kind_t strict,
9744                                 int sub_strict)
9745 {
9746   tree tempargs = copy_node (targs);
9747   int good = 0;
9748   bool addr_p;
9749
9750   if (TREE_CODE (arg) == ADDR_EXPR)
9751     {
9752       arg = TREE_OPERAND (arg, 0);
9753       addr_p = true;
9754     }
9755   else
9756     addr_p = false;
9757
9758   if (TREE_CODE (arg) == COMPONENT_REF)
9759     /* Handle `&x' where `x' is some static or non-static member
9760        function name.  */
9761     arg = TREE_OPERAND (arg, 1);
9762
9763   if (TREE_CODE (arg) == OFFSET_REF)
9764     arg = TREE_OPERAND (arg, 1);
9765
9766   /* Strip baselink information.  */
9767   if (BASELINK_P (arg))
9768     arg = BASELINK_FUNCTIONS (arg);
9769
9770   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
9771     {
9772       /* If we got some explicit template args, we need to plug them into
9773          the affected templates before we try to unify, in case the
9774          explicit args will completely resolve the templates in question.  */
9775
9776       tree expl_subargs = TREE_OPERAND (arg, 1);
9777       arg = TREE_OPERAND (arg, 0);
9778
9779       for (; arg; arg = OVL_NEXT (arg))
9780         {
9781           tree fn = OVL_CURRENT (arg);
9782           tree subargs, elem;
9783
9784           if (TREE_CODE (fn) != TEMPLATE_DECL)
9785             continue;
9786
9787           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
9788                                   expl_subargs, /*check_ret=*/false);
9789           if (subargs)
9790             {
9791               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
9792               good += try_one_overload (tparms, targs, tempargs, parm,
9793                                         elem, strict, sub_strict, addr_p);
9794             }
9795         }
9796     }
9797   else
9798     {
9799       gcc_assert (TREE_CODE (arg) == OVERLOAD
9800                   || TREE_CODE (arg) == FUNCTION_DECL);
9801
9802       for (; arg; arg = OVL_NEXT (arg))
9803         good += try_one_overload (tparms, targs, tempargs, parm,
9804                                   TREE_TYPE (OVL_CURRENT (arg)),
9805                                   strict, sub_strict, addr_p);
9806     }
9807
9808   /* [temp.deduct.type] A template-argument can be deduced from a pointer
9809      to function or pointer to member function argument if the set of
9810      overloaded functions does not contain function templates and at most
9811      one of a set of overloaded functions provides a unique match.
9812
9813      So if we found multiple possibilities, we return success but don't
9814      deduce anything.  */
9815
9816   if (good == 1)
9817     {
9818       int i = TREE_VEC_LENGTH (targs);
9819       for (; i--; )
9820         if (TREE_VEC_ELT (tempargs, i))
9821           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
9822     }
9823   if (good)
9824     return 0;
9825
9826   return 1;
9827 }
9828
9829 /* Subroutine of resolve_overloaded_unification; does deduction for a single
9830    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
9831    different overloads deduce different arguments for a given parm.
9832    ADDR_P is true if the expression for which deduction is being
9833    performed was of the form "& fn" rather than simply "fn".
9834
9835    Returns 1 on success.  */
9836
9837 static int
9838 try_one_overload (tree tparms,
9839                   tree orig_targs,
9840                   tree targs,
9841                   tree parm,
9842                   tree arg,
9843                   unification_kind_t strict,
9844                   int sub_strict,
9845                   bool addr_p)
9846 {
9847   int nargs;
9848   tree tempargs;
9849   int i;
9850
9851   /* [temp.deduct.type] A template-argument can be deduced from a pointer
9852      to function or pointer to member function argument if the set of
9853      overloaded functions does not contain function templates and at most
9854      one of a set of overloaded functions provides a unique match.
9855
9856      So if this is a template, just return success.  */
9857
9858   if (uses_template_parms (arg))
9859     return 1;
9860
9861   if (TREE_CODE (arg) == METHOD_TYPE)
9862     arg = build_ptrmemfunc_type (build_pointer_type (arg));
9863   else if (addr_p)
9864     arg = build_pointer_type (arg);
9865
9866   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
9867
9868   /* We don't copy orig_targs for this because if we have already deduced
9869      some template args from previous args, unify would complain when we
9870      try to deduce a template parameter for the same argument, even though
9871      there isn't really a conflict.  */
9872   nargs = TREE_VEC_LENGTH (targs);
9873   tempargs = make_tree_vec (nargs);
9874
9875   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
9876     return 0;
9877
9878   /* First make sure we didn't deduce anything that conflicts with
9879      explicitly specified args.  */
9880   for (i = nargs; i--; )
9881     {
9882       tree elt = TREE_VEC_ELT (tempargs, i);
9883       tree oldelt = TREE_VEC_ELT (orig_targs, i);
9884
9885       if (!elt)
9886         /*NOP*/;
9887       else if (uses_template_parms (elt))
9888         /* Since we're unifying against ourselves, we will fill in
9889            template args used in the function parm list with our own
9890            template parms.  Discard them.  */
9891         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
9892       else if (oldelt && !template_args_equal (oldelt, elt))
9893         return 0;
9894     }
9895
9896   for (i = nargs; i--; )
9897     {
9898       tree elt = TREE_VEC_ELT (tempargs, i);
9899
9900       if (elt)
9901         TREE_VEC_ELT (targs, i) = elt;
9902     }
9903
9904   return 1;
9905 }
9906
9907 /* PARM is a template class (perhaps with unbound template
9908    parameters).  ARG is a fully instantiated type.  If ARG can be
9909    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
9910    TARGS are as for unify.  */
9911
9912 static tree
9913 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
9914 {
9915   tree copy_of_targs;
9916
9917   if (!CLASSTYPE_TEMPLATE_INFO (arg)
9918       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
9919           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
9920     return NULL_TREE;
9921
9922   /* We need to make a new template argument vector for the call to
9923      unify.  If we used TARGS, we'd clutter it up with the result of
9924      the attempted unification, even if this class didn't work out.
9925      We also don't want to commit ourselves to all the unifications
9926      we've already done, since unification is supposed to be done on
9927      an argument-by-argument basis.  In other words, consider the
9928      following pathological case:
9929
9930        template <int I, int J, int K>
9931        struct S {};
9932
9933        template <int I, int J>
9934        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
9935
9936        template <int I, int J, int K>
9937        void f(S<I, J, K>, S<I, I, I>);
9938
9939        void g() {
9940          S<0, 0, 0> s0;
9941          S<0, 1, 2> s2;
9942
9943          f(s0, s2);
9944        }
9945
9946      Now, by the time we consider the unification involving `s2', we
9947      already know that we must have `f<0, 0, 0>'.  But, even though
9948      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
9949      because there are two ways to unify base classes of S<0, 1, 2>
9950      with S<I, I, I>.  If we kept the already deduced knowledge, we
9951      would reject the possibility I=1.  */
9952   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
9953
9954   /* If unification failed, we're done.  */
9955   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
9956              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
9957     return NULL_TREE;
9958
9959   return arg;
9960 }
9961
9962 /* Given a template type PARM and a class type ARG, find the unique
9963    base type in ARG that is an instance of PARM.  We do not examine
9964    ARG itself; only its base-classes.  If there is not exactly one
9965    appropriate base class, return NULL_TREE.  PARM may be the type of
9966    a partial specialization, as well as a plain template type.  Used
9967    by unify.  */
9968
9969 static tree
9970 get_template_base (tree tparms, tree targs, tree parm, tree arg)
9971 {
9972   tree rval = NULL_TREE;
9973   tree binfo;
9974
9975   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
9976
9977   binfo = TYPE_BINFO (complete_type (arg));
9978   if (!binfo)
9979     /* The type could not be completed.  */
9980     return NULL_TREE;
9981
9982   /* Walk in inheritance graph order.  The search order is not
9983      important, and this avoids multiple walks of virtual bases.  */
9984   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
9985     {
9986       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
9987
9988       if (r)
9989         {
9990           /* If there is more than one satisfactory baseclass, then:
9991
9992                [temp.deduct.call]
9993
9994               If they yield more than one possible deduced A, the type
9995               deduction fails.
9996
9997              applies.  */
9998           if (rval && !same_type_p (r, rval))
9999             return NULL_TREE;
10000
10001           rval = r;
10002         }
10003     }
10004
10005   return rval;
10006 }
10007
10008 /* Returns the level of DECL, which declares a template parameter.  */
10009
10010 static int
10011 template_decl_level (tree decl)
10012 {
10013   switch (TREE_CODE (decl))
10014     {
10015     case TYPE_DECL:
10016     case TEMPLATE_DECL:
10017       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
10018
10019     case PARM_DECL:
10020       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
10021
10022     default:
10023       gcc_unreachable ();
10024     }
10025   return 0;
10026 }
10027
10028 /* Decide whether ARG can be unified with PARM, considering only the
10029    cv-qualifiers of each type, given STRICT as documented for unify.
10030    Returns nonzero iff the unification is OK on that basis.  */
10031
10032 static int
10033 check_cv_quals_for_unify (int strict, tree arg, tree parm)
10034 {
10035   int arg_quals = cp_type_quals (arg);
10036   int parm_quals = cp_type_quals (parm);
10037
10038   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
10039       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
10040     {
10041       /*  Although a CVR qualifier is ignored when being applied to a
10042           substituted template parameter ([8.3.2]/1 for example), that
10043           does not apply during deduction [14.8.2.4]/1, (even though
10044           that is not explicitly mentioned, [14.8.2.4]/9 indicates
10045           this).  Except when we're allowing additional CV qualifiers
10046           at the outer level [14.8.2.1]/3,1st bullet.  */
10047       if ((TREE_CODE (arg) == REFERENCE_TYPE
10048            || TREE_CODE (arg) == FUNCTION_TYPE
10049            || TREE_CODE (arg) == METHOD_TYPE)
10050           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
10051         return 0;
10052
10053       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
10054           && (parm_quals & TYPE_QUAL_RESTRICT))
10055         return 0;
10056     }
10057
10058   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
10059       && (arg_quals & parm_quals) != parm_quals)
10060     return 0;
10061
10062   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
10063       && (parm_quals & arg_quals) != arg_quals)
10064     return 0;
10065
10066   return 1;
10067 }
10068
10069 /* Deduce the value of template parameters.  TPARMS is the (innermost)
10070    set of template parameters to a template.  TARGS is the bindings
10071    for those template parameters, as determined thus far; TARGS may
10072    include template arguments for outer levels of template parameters
10073    as well.  PARM is a parameter to a template function, or a
10074    subcomponent of that parameter; ARG is the corresponding argument.
10075    This function attempts to match PARM with ARG in a manner
10076    consistent with the existing assignments in TARGS.  If more values
10077    are deduced, then TARGS is updated.
10078
10079    Returns 0 if the type deduction succeeds, 1 otherwise.  The
10080    parameter STRICT is a bitwise or of the following flags:
10081
10082      UNIFY_ALLOW_NONE:
10083        Require an exact match between PARM and ARG.
10084      UNIFY_ALLOW_MORE_CV_QUAL:
10085        Allow the deduced ARG to be more cv-qualified (by qualification
10086        conversion) than ARG.
10087      UNIFY_ALLOW_LESS_CV_QUAL:
10088        Allow the deduced ARG to be less cv-qualified than ARG.
10089      UNIFY_ALLOW_DERIVED:
10090        Allow the deduced ARG to be a template base class of ARG,
10091        or a pointer to a template base class of the type pointed to by
10092        ARG.
10093      UNIFY_ALLOW_INTEGER:
10094        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
10095        case for more information.
10096      UNIFY_ALLOW_OUTER_LEVEL:
10097        This is the outermost level of a deduction. Used to determine validity
10098        of qualification conversions. A valid qualification conversion must
10099        have const qualified pointers leading up to the inner type which
10100        requires additional CV quals, except at the outer level, where const
10101        is not required [conv.qual]. It would be normal to set this flag in
10102        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
10103      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
10104        This is the outermost level of a deduction, and PARM can be more CV
10105        qualified at this point.
10106      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
10107        This is the outermost level of a deduction, and PARM can be less CV
10108        qualified at this point.  */
10109
10110 static int
10111 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
10112 {
10113   int idx;
10114   tree targ;
10115   tree tparm;
10116   int strict_in = strict;
10117
10118   /* I don't think this will do the right thing with respect to types.
10119      But the only case I've seen it in so far has been array bounds, where
10120      signedness is the only information lost, and I think that will be
10121      okay.  */
10122   while (TREE_CODE (parm) == NOP_EXPR)
10123     parm = TREE_OPERAND (parm, 0);
10124
10125   if (arg == error_mark_node)
10126     return 1;
10127   if (arg == unknown_type_node)
10128     /* We can't deduce anything from this, but we might get all the
10129        template args from other function args.  */
10130     return 0;
10131
10132   /* If PARM uses template parameters, then we can't bail out here,
10133      even if ARG == PARM, since we won't record unifications for the
10134      template parameters.  We might need them if we're trying to
10135      figure out which of two things is more specialized.  */
10136   if (arg == parm && !uses_template_parms (parm))
10137     return 0;
10138
10139   /* Immediately reject some pairs that won't unify because of
10140      cv-qualification mismatches.  */
10141   if (TREE_CODE (arg) == TREE_CODE (parm)
10142       && TYPE_P (arg)
10143       /* It is the elements of the array which hold the cv quals of an array
10144          type, and the elements might be template type parms. We'll check
10145          when we recurse.  */
10146       && TREE_CODE (arg) != ARRAY_TYPE
10147       /* We check the cv-qualifiers when unifying with template type
10148          parameters below.  We want to allow ARG `const T' to unify with
10149          PARM `T' for example, when computing which of two templates
10150          is more specialized, for example.  */
10151       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
10152       && !check_cv_quals_for_unify (strict_in, arg, parm))
10153     return 1;
10154
10155   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
10156       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
10157     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
10158   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
10159   strict &= ~UNIFY_ALLOW_DERIVED;
10160   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
10161   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
10162
10163   switch (TREE_CODE (parm))
10164     {
10165     case TYPENAME_TYPE:
10166     case SCOPE_REF:
10167     case UNBOUND_CLASS_TEMPLATE:
10168       /* In a type which contains a nested-name-specifier, template
10169          argument values cannot be deduced for template parameters used
10170          within the nested-name-specifier.  */
10171       return 0;
10172
10173     case TEMPLATE_TYPE_PARM:
10174     case TEMPLATE_TEMPLATE_PARM:
10175     case BOUND_TEMPLATE_TEMPLATE_PARM:
10176       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
10177
10178       if (TEMPLATE_TYPE_LEVEL (parm)
10179           != template_decl_level (tparm))
10180         /* The PARM is not one we're trying to unify.  Just check
10181            to see if it matches ARG.  */
10182         return (TREE_CODE (arg) == TREE_CODE (parm)
10183                 && same_type_p (parm, arg)) ? 0 : 1;
10184       idx = TEMPLATE_TYPE_IDX (parm);
10185       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
10186       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
10187
10188       /* Check for mixed types and values.  */
10189       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
10190            && TREE_CODE (tparm) != TYPE_DECL)
10191           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
10192               && TREE_CODE (tparm) != TEMPLATE_DECL))
10193         return 1;
10194
10195       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
10196         {
10197           /* ARG must be constructed from a template class or a template
10198              template parameter.  */
10199           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
10200               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
10201             return 1;
10202
10203           {
10204             tree parmtmpl = TYPE_TI_TEMPLATE (parm);
10205             tree parmvec = TYPE_TI_ARGS (parm);
10206             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
10207             tree argtmplvec
10208               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
10209             int i;
10210
10211             /* The parameter and argument roles have to be switched here
10212                in order to handle default arguments properly.  For example,
10213                template<template <class> class TT> void f(TT<int>)
10214                should be able to accept vector<int> which comes from
10215                template <class T, class Allocator = allocator>
10216                class vector.  */
10217
10218             if (coerce_template_parms (argtmplvec, parmvec, parmtmpl, 0, 1)
10219                 == error_mark_node)
10220               return 1;
10221
10222             /* Deduce arguments T, i from TT<T> or TT<i>.
10223                We check each element of PARMVEC and ARGVEC individually
10224                rather than the whole TREE_VEC since they can have
10225                different number of elements.  */
10226
10227             for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
10228               {
10229                 if (unify (tparms, targs,
10230                            TREE_VEC_ELT (parmvec, i),
10231                            TREE_VEC_ELT (argvec, i),
10232                            UNIFY_ALLOW_NONE))
10233                   return 1;
10234               }
10235           }
10236           arg = TYPE_TI_TEMPLATE (arg);
10237
10238           /* Fall through to deduce template name.  */
10239         }
10240
10241       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
10242           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
10243         {
10244           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
10245
10246           /* Simple cases: Value already set, does match or doesn't.  */
10247           if (targ != NULL_TREE && template_args_equal (targ, arg))
10248             return 0;
10249           else if (targ)
10250             return 1;
10251         }
10252       else
10253         {
10254           /* If PARM is `const T' and ARG is only `int', we don't have
10255              a match unless we are allowing additional qualification.
10256              If ARG is `const int' and PARM is just `T' that's OK;
10257              that binds `const int' to `T'.  */
10258           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
10259                                          arg, parm))
10260             return 1;
10261
10262           /* Consider the case where ARG is `const volatile int' and
10263              PARM is `const T'.  Then, T should be `volatile int'.  */
10264           arg = cp_build_qualified_type_real
10265             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
10266           if (arg == error_mark_node)
10267             return 1;
10268
10269           /* Simple cases: Value already set, does match or doesn't.  */
10270           if (targ != NULL_TREE && same_type_p (targ, arg))
10271             return 0;
10272           else if (targ)
10273             return 1;
10274
10275           /* Make sure that ARG is not a variable-sized array.  (Note
10276              that were talking about variable-sized arrays (like
10277              `int[n]'), rather than arrays of unknown size (like
10278              `int[]').)  We'll get very confused by such a type since
10279              the bound of the array will not be computable in an
10280              instantiation.  Besides, such types are not allowed in
10281              ISO C++, so we can do as we please here.  */
10282           if (variably_modified_type_p (arg, NULL_TREE))
10283             return 1;
10284         }
10285
10286       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
10287       return 0;
10288
10289     case TEMPLATE_PARM_INDEX:
10290       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
10291       if (tparm == error_mark_node)
10292         return 1;
10293
10294       if (TEMPLATE_PARM_LEVEL (parm)
10295           != template_decl_level (tparm))
10296         /* The PARM is not one we're trying to unify.  Just check
10297            to see if it matches ARG.  */
10298         return !(TREE_CODE (arg) == TREE_CODE (parm)
10299                  && cp_tree_equal (parm, arg));
10300
10301       idx = TEMPLATE_PARM_IDX (parm);
10302       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
10303
10304       if (targ)
10305         return !cp_tree_equal (targ, arg);
10306
10307       /* [temp.deduct.type] If, in the declaration of a function template
10308          with a non-type template-parameter, the non-type
10309          template-parameter is used in an expression in the function
10310          parameter-list and, if the corresponding template-argument is
10311          deduced, the template-argument type shall match the type of the
10312          template-parameter exactly, except that a template-argument
10313          deduced from an array bound may be of any integral type.
10314          The non-type parameter might use already deduced type parameters.  */
10315       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
10316       if (!TREE_TYPE (arg))
10317         /* Template-parameter dependent expression.  Just accept it for now.
10318            It will later be processed in convert_template_argument.  */
10319         ;
10320       else if (same_type_p (TREE_TYPE (arg), tparm))
10321         /* OK */;
10322       else if ((strict & UNIFY_ALLOW_INTEGER)
10323                && (TREE_CODE (tparm) == INTEGER_TYPE
10324                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
10325         /* Convert the ARG to the type of PARM; the deduced non-type
10326            template argument must exactly match the types of the
10327            corresponding parameter.  */
10328         arg = fold (build_nop (TREE_TYPE (parm), arg));
10329       else if (uses_template_parms (tparm))
10330         /* We haven't deduced the type of this parameter yet.  Try again
10331            later.  */
10332         return 0;
10333       else
10334         return 1;
10335
10336       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
10337       return 0;
10338
10339     case PTRMEM_CST:
10340      {
10341         /* A pointer-to-member constant can be unified only with
10342          another constant.  */
10343       if (TREE_CODE (arg) != PTRMEM_CST)
10344         return 1;
10345
10346       /* Just unify the class member. It would be useless (and possibly
10347          wrong, depending on the strict flags) to unify also
10348          PTRMEM_CST_CLASS, because we want to be sure that both parm and
10349          arg refer to the same variable, even if through different
10350          classes. For instance:
10351
10352          struct A { int x; };
10353          struct B : A { };
10354
10355          Unification of &A::x and &B::x must succeed.  */
10356       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
10357                     PTRMEM_CST_MEMBER (arg), strict);
10358      }
10359
10360     case POINTER_TYPE:
10361       {
10362         if (TREE_CODE (arg) != POINTER_TYPE)
10363           return 1;
10364
10365         /* [temp.deduct.call]
10366
10367            A can be another pointer or pointer to member type that can
10368            be converted to the deduced A via a qualification
10369            conversion (_conv.qual_).
10370
10371            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
10372            This will allow for additional cv-qualification of the
10373            pointed-to types if appropriate.  */
10374
10375         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
10376           /* The derived-to-base conversion only persists through one
10377              level of pointers.  */
10378           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
10379
10380         return unify (tparms, targs, TREE_TYPE (parm),
10381                       TREE_TYPE (arg), strict);
10382       }
10383
10384     case REFERENCE_TYPE:
10385       if (TREE_CODE (arg) != REFERENCE_TYPE)
10386         return 1;
10387       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
10388                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
10389
10390     case ARRAY_TYPE:
10391       if (TREE_CODE (arg) != ARRAY_TYPE)
10392         return 1;
10393       if ((TYPE_DOMAIN (parm) == NULL_TREE)
10394           != (TYPE_DOMAIN (arg) == NULL_TREE))
10395         return 1;
10396       if (TYPE_DOMAIN (parm) != NULL_TREE)
10397         {
10398           tree parm_max;
10399           tree arg_max;
10400           bool parm_cst;
10401           bool arg_cst;
10402
10403           /* Our representation of array types uses "N - 1" as the
10404              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
10405              not an integer constant.  We cannot unify arbitrarily
10406              complex expressions, so we eliminate the MINUS_EXPRs
10407              here.  */
10408           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
10409           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
10410           if (!parm_cst)
10411             {
10412               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
10413               parm_max = TREE_OPERAND (parm_max, 0);
10414             }
10415           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
10416           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
10417           if (!arg_cst)
10418             {
10419               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
10420                  trying to unify the type of a variable with the type
10421                  of a template parameter.  For example:
10422
10423                    template <unsigned int N>
10424                    void f (char (&) [N]);
10425                    int g(); 
10426                    void h(int i) {
10427                      char a[g(i)];
10428                      f(a); 
10429                    }
10430
10431                 Here, the type of the ARG will be "int [g(i)]", and
10432                 may be a SAVE_EXPR, etc.  */
10433               if (TREE_CODE (arg_max) != MINUS_EXPR)
10434                 return 1;
10435               arg_max = TREE_OPERAND (arg_max, 0);
10436             }
10437
10438           /* If only one of the bounds used a MINUS_EXPR, compensate
10439              by adding one to the other bound.  */
10440           if (parm_cst && !arg_cst)
10441             parm_max = fold_build2 (PLUS_EXPR,
10442                                     integer_type_node,
10443                                     parm_max,
10444                                     integer_one_node);
10445           else if (arg_cst && !parm_cst)
10446             arg_max = fold_build2 (PLUS_EXPR,
10447                                    integer_type_node,
10448                                    arg_max,
10449                                    integer_one_node);
10450
10451           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
10452             return 1;
10453         }
10454       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
10455                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
10456
10457     case REAL_TYPE:
10458     case COMPLEX_TYPE:
10459     case VECTOR_TYPE:
10460     case INTEGER_TYPE:
10461     case BOOLEAN_TYPE:
10462     case ENUMERAL_TYPE:
10463     case VOID_TYPE:
10464       if (TREE_CODE (arg) != TREE_CODE (parm))
10465         return 1;
10466
10467       /* We have already checked cv-qualification at the top of the
10468          function.  */
10469       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
10470         return 1;
10471
10472       /* As far as unification is concerned, this wins.  Later checks
10473          will invalidate it if necessary.  */
10474       return 0;
10475
10476       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
10477       /* Type INTEGER_CST can come from ordinary constant template args.  */
10478     case INTEGER_CST:
10479       while (TREE_CODE (arg) == NOP_EXPR)
10480         arg = TREE_OPERAND (arg, 0);
10481
10482       if (TREE_CODE (arg) != INTEGER_CST)
10483         return 1;
10484       return !tree_int_cst_equal (parm, arg);
10485
10486     case TREE_VEC:
10487       {
10488         int i;
10489         if (TREE_CODE (arg) != TREE_VEC)
10490           return 1;
10491         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
10492           return 1;
10493         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
10494           if (unify (tparms, targs,
10495                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
10496                      UNIFY_ALLOW_NONE))
10497             return 1;
10498         return 0;
10499       }
10500
10501     case RECORD_TYPE:
10502     case UNION_TYPE:
10503       if (TREE_CODE (arg) != TREE_CODE (parm))
10504         return 1;
10505
10506       if (TYPE_PTRMEMFUNC_P (parm))
10507         {
10508           if (!TYPE_PTRMEMFUNC_P (arg))
10509             return 1;
10510
10511           return unify (tparms, targs,
10512                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
10513                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
10514                         strict);
10515         }
10516
10517       if (CLASSTYPE_TEMPLATE_INFO (parm))
10518         {
10519           tree t = NULL_TREE;
10520
10521           if (strict_in & UNIFY_ALLOW_DERIVED)
10522             {
10523               /* First, we try to unify the PARM and ARG directly.  */
10524               t = try_class_unification (tparms, targs,
10525                                          parm, arg);
10526
10527               if (!t)
10528                 {
10529                   /* Fallback to the special case allowed in
10530                      [temp.deduct.call]:
10531
10532                        If P is a class, and P has the form
10533                        template-id, then A can be a derived class of
10534                        the deduced A.  Likewise, if P is a pointer to
10535                        a class of the form template-id, A can be a
10536                        pointer to a derived class pointed to by the
10537                        deduced A.  */
10538                   t = get_template_base (tparms, targs, parm, arg);
10539
10540                   if (!t)
10541                     return 1;
10542                 }
10543             }
10544           else if (CLASSTYPE_TEMPLATE_INFO (arg)
10545                    && (CLASSTYPE_TI_TEMPLATE (parm)
10546                        == CLASSTYPE_TI_TEMPLATE (arg)))
10547             /* Perhaps PARM is something like S<U> and ARG is S<int>.
10548                Then, we should unify `int' and `U'.  */
10549             t = arg;
10550           else
10551             /* There's no chance of unification succeeding.  */
10552             return 1;
10553
10554           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
10555                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
10556         }
10557       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
10558         return 1;
10559       return 0;
10560
10561     case METHOD_TYPE:
10562     case FUNCTION_TYPE:
10563       if (TREE_CODE (arg) != TREE_CODE (parm))
10564         return 1;
10565
10566       /* CV qualifications for methods can never be deduced, they must
10567          match exactly.  We need to check them explicitly here,
10568          because type_unification_real treats them as any other
10569          cvqualified parameter.  */
10570       if (TREE_CODE (parm) == METHOD_TYPE
10571           && (!check_cv_quals_for_unify
10572               (UNIFY_ALLOW_NONE,
10573                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
10574                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
10575         return 1;
10576
10577       if (unify (tparms, targs, TREE_TYPE (parm),
10578                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
10579         return 1;
10580       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
10581                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
10582                                     LOOKUP_NORMAL);
10583
10584     case OFFSET_TYPE:
10585       /* Unify a pointer to member with a pointer to member function, which
10586          deduces the type of the member as a function type. */
10587       if (TYPE_PTRMEMFUNC_P (arg))
10588         {
10589           tree method_type;
10590           tree fntype;
10591           cp_cv_quals cv_quals;
10592
10593           /* Check top-level cv qualifiers */
10594           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
10595             return 1;
10596
10597           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
10598                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
10599             return 1;
10600
10601           /* Determine the type of the function we are unifying against. */
10602           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
10603           fntype =
10604             build_function_type (TREE_TYPE (method_type),
10605                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
10606
10607           /* Extract the cv-qualifiers of the member function from the
10608              implicit object parameter and place them on the function
10609              type to be restored later. */
10610           cv_quals =
10611             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
10612           fntype = build_qualified_type (fntype, cv_quals);
10613           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
10614         }
10615
10616       if (TREE_CODE (arg) != OFFSET_TYPE)
10617         return 1;
10618       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
10619                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
10620         return 1;
10621       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
10622                     strict);
10623
10624     case CONST_DECL:
10625       if (DECL_TEMPLATE_PARM_P (parm))
10626         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
10627       if (arg != integral_constant_value (parm))
10628         return 1;
10629       return 0;
10630
10631     case FIELD_DECL:
10632     case TEMPLATE_DECL:
10633       /* Matched cases are handled by the ARG == PARM test above.  */
10634       return 1;
10635
10636     default:
10637       gcc_assert (EXPR_P (parm));
10638
10639       /* We must be looking at an expression.  This can happen with
10640          something like:
10641
10642            template <int I>
10643            void foo(S<I>, S<I + 2>);
10644
10645          This is a "nondeduced context":
10646
10647            [deduct.type]
10648
10649            The nondeduced contexts are:
10650
10651            --A type that is a template-id in which one or more of
10652              the template-arguments is an expression that references
10653              a template-parameter.
10654
10655          In these cases, we assume deduction succeeded, but don't
10656          actually infer any unifications.  */
10657
10658       if (!uses_template_parms (parm)
10659           && !template_args_equal (parm, arg))
10660         return 1;
10661       else
10662         return 0;
10663     }
10664 }
10665 \f
10666 /* Note that DECL can be defined in this translation unit, if
10667    required.  */
10668
10669 static void
10670 mark_definable (tree decl)
10671 {
10672   tree clone;
10673   DECL_NOT_REALLY_EXTERN (decl) = 1;
10674   FOR_EACH_CLONE (clone, decl)
10675     DECL_NOT_REALLY_EXTERN (clone) = 1;
10676 }
10677
10678 /* Called if RESULT is explicitly instantiated, or is a member of an
10679    explicitly instantiated class.  */
10680
10681 void
10682 mark_decl_instantiated (tree result, int extern_p)
10683 {
10684   SET_DECL_EXPLICIT_INSTANTIATION (result);
10685
10686   /* If this entity has already been written out, it's too late to
10687      make any modifications.  */
10688   if (TREE_ASM_WRITTEN (result))
10689     return;
10690
10691   if (TREE_CODE (result) != FUNCTION_DECL)
10692     /* The TREE_PUBLIC flag for function declarations will have been
10693        set correctly by tsubst.  */
10694     TREE_PUBLIC (result) = 1;
10695
10696   /* This might have been set by an earlier implicit instantiation.  */
10697   DECL_COMDAT (result) = 0;
10698
10699   if (extern_p)
10700     DECL_NOT_REALLY_EXTERN (result) = 0;
10701   else
10702     {
10703       mark_definable (result);
10704       /* Always make artificials weak.  */
10705       if (DECL_ARTIFICIAL (result) && flag_weak)
10706         comdat_linkage (result);
10707       /* For WIN32 we also want to put explicit instantiations in
10708          linkonce sections.  */
10709       else if (TREE_PUBLIC (result))
10710         maybe_make_one_only (result);
10711     }
10712
10713   /* If EXTERN_P, then this function will not be emitted -- unless
10714      followed by an explicit instantiation, at which point its linkage
10715      will be adjusted.  If !EXTERN_P, then this function will be
10716      emitted here.  In neither circumstance do we want
10717      import_export_decl to adjust the linkage.  */
10718   DECL_INTERFACE_KNOWN (result) = 1;
10719 }
10720
10721 /* Given two function templates PAT1 and PAT2, return:
10722
10723    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
10724    -1 if PAT2 is more specialized than PAT1.
10725    0 if neither is more specialized.
10726
10727    LEN indicates the number of parameters we should consider
10728    (defaulted parameters should not be considered).
10729
10730    The 1998 std underspecified function template partial ordering, and
10731    DR214 addresses the issue.  We take pairs of arguments, one from
10732    each of the templates, and deduce them against each other.  One of
10733    the templates will be more specialized if all the *other*
10734    template's arguments deduce against its arguments and at least one
10735    of its arguments *does* *not* deduce against the other template's
10736    corresponding argument.  Deduction is done as for class templates.
10737    The arguments used in deduction have reference and top level cv
10738    qualifiers removed.  Iff both arguments were originally reference
10739    types *and* deduction succeeds in both directions, the template
10740    with the more cv-qualified argument wins for that pairing (if
10741    neither is more cv-qualified, they both are equal).  Unlike regular
10742    deduction, after all the arguments have been deduced in this way,
10743    we do *not* verify the deduced template argument values can be
10744    substituted into non-deduced contexts, nor do we have to verify
10745    that all template arguments have been deduced.  */
10746
10747 int
10748 more_specialized_fn (tree pat1, tree pat2, int len)
10749 {
10750   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
10751   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
10752   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
10753   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
10754   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
10755   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
10756   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
10757   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
10758   int better1 = 0;
10759   int better2 = 0;
10760   
10761   /* Remove the this parameter from non-static member functions.  If
10762      one is a non-static member function and the other is not a static
10763      member function, remove the first parameter from that function
10764      also.  This situation occurs for operator functions where we
10765      locate both a member function (with this pointer) and non-member
10766      operator (with explicit first operand).  */
10767   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
10768     {
10769       len--; /* LEN is the number of significant arguments for DECL1 */
10770       args1 = TREE_CHAIN (args1);
10771       if (!DECL_STATIC_FUNCTION_P (decl2))
10772         args2 = TREE_CHAIN (args2);
10773     }
10774   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
10775     {
10776       args2 = TREE_CHAIN (args2);
10777       if (!DECL_STATIC_FUNCTION_P (decl1))
10778         {
10779           len--;
10780           args1 = TREE_CHAIN (args1);
10781         }
10782     }
10783     
10784   /* If only one is a conversion operator, they are unordered.  */
10785   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
10786     return 0;
10787
10788   /* Consider the return type for a conversion function */
10789   if (DECL_CONV_FN_P (decl1))
10790     {
10791       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
10792       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
10793       len++;
10794     }
10795
10796   processing_template_decl++;
10797
10798   while (len--)
10799     {
10800       tree arg1 = TREE_VALUE (args1);
10801       tree arg2 = TREE_VALUE (args2);
10802       int deduce1, deduce2;
10803       int quals1 = -1;
10804       int quals2 = -1;
10805
10806       if (TREE_CODE (arg1) == REFERENCE_TYPE)
10807         {
10808           arg1 = TREE_TYPE (arg1);
10809           quals1 = cp_type_quals (arg1);
10810         }
10811
10812       if (TREE_CODE (arg2) == REFERENCE_TYPE)
10813         {
10814           arg2 = TREE_TYPE (arg2);
10815           quals2 = cp_type_quals (arg2);
10816         }
10817
10818       if ((quals1 < 0) != (quals2 < 0))
10819         {
10820           /* Only of the args is a reference, see if we should apply
10821              array/function pointer decay to it.  This is not part of
10822              DR214, but is, IMHO, consistent with the deduction rules
10823              for the function call itself, and with our earlier
10824              implementation of the underspecified partial ordering
10825              rules.  (nathan).  */
10826           if (quals1 >= 0)
10827             {
10828               switch (TREE_CODE (arg1))
10829                 {
10830                 case ARRAY_TYPE:
10831                   arg1 = TREE_TYPE (arg1);
10832                   /* FALLTHROUGH. */
10833                 case FUNCTION_TYPE:
10834                   arg1 = build_pointer_type (arg1);
10835                   break;
10836
10837                 default:
10838                   break;
10839                 }
10840             }
10841           else
10842             {
10843               switch (TREE_CODE (arg2))
10844                 {
10845                 case ARRAY_TYPE:
10846                   arg2 = TREE_TYPE (arg2);
10847                   /* FALLTHROUGH. */
10848                 case FUNCTION_TYPE:
10849                   arg2 = build_pointer_type (arg2);
10850                   break;
10851
10852                 default:
10853                   break;
10854                 }
10855             }
10856         }
10857
10858       arg1 = TYPE_MAIN_VARIANT (arg1);
10859       arg2 = TYPE_MAIN_VARIANT (arg2);
10860
10861       deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
10862       deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
10863
10864       if (!deduce1)
10865         better2 = -1;
10866       if (!deduce2)
10867         better1 = -1;
10868       if (better1 < 0 && better2 < 0)
10869         /* We've failed to deduce something in either direction.
10870            These must be unordered.  */
10871         break;
10872
10873       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
10874         {
10875           /* Deduces in both directions, see if quals can
10876              disambiguate.  Pretend the worse one failed to deduce. */
10877           if ((quals1 & quals2) == quals2)
10878             deduce1 = 0;
10879           if ((quals1 & quals2) == quals1)
10880             deduce2 = 0;
10881         }
10882       if (deduce1 && !deduce2 && !better2)
10883         better2 = 1;
10884       if (deduce2 && !deduce1 && !better1)
10885         better1 = 1;
10886
10887       args1 = TREE_CHAIN (args1);
10888       args2 = TREE_CHAIN (args2);
10889     }
10890
10891   processing_template_decl--;
10892
10893   return (better1 > 0) - (better2 > 0);
10894 }
10895
10896 /* Determine which of two partial specializations is more specialized.
10897   
10898    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
10899    to the first partial specialization.  The TREE_VALUE is the
10900    innermost set of template parameters for the partial
10901    specialization.  PAT2 is similar, but for the second template.
10902
10903    Return 1 if the first partial specialization is more specialized;
10904    -1 if the second is more specialized; 0 if neither is more
10905    specialized.
10906
10907    See [temp.class.order] for information about determining which of
10908    two templates is more specialized.  */ 
10909
10910 int
10911 more_specialized_class (tree pat1, tree pat2)
10912 {
10913   tree targs;
10914   tree tmpl1, tmpl2;
10915   int winner = 0;
10916   
10917   tmpl1 = TREE_TYPE (pat1);
10918   tmpl2 = TREE_TYPE (pat2);
10919
10920   /* Just like what happens for functions, if we are ordering between
10921      different class template specializations, we may encounter dependent
10922      types in the arguments, and we need our dependency check functions
10923      to behave correctly.  */
10924   ++processing_template_decl;
10925   targs = get_class_bindings (TREE_VALUE (pat1), 
10926                               CLASSTYPE_TI_ARGS (tmpl1),
10927                               CLASSTYPE_TI_ARGS (tmpl2));
10928   if (targs)
10929     --winner;
10930
10931   targs = get_class_bindings (TREE_VALUE (pat2), 
10932                               CLASSTYPE_TI_ARGS (tmpl2),
10933                               CLASSTYPE_TI_ARGS (tmpl1));
10934   if (targs)
10935     ++winner;
10936   --processing_template_decl;
10937
10938   return winner;
10939 }
10940
10941 /* Return the template arguments that will produce the function signature
10942    DECL from the function template FN, with the explicit template
10943    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
10944    also match.  Return NULL_TREE if no satisfactory arguments could be
10945    found.  */
10946
10947 static tree
10948 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
10949 {
10950   int ntparms = DECL_NTPARMS (fn);
10951   tree targs = make_tree_vec (ntparms);
10952   tree decl_type;
10953   tree decl_arg_types;
10954
10955   /* Substitute the explicit template arguments into the type of DECL.
10956      The call to fn_type_unification will handle substitution into the
10957      FN.  */
10958   decl_type = TREE_TYPE (decl);
10959   if (explicit_args && uses_template_parms (decl_type))
10960     {
10961       tree tmpl;
10962       tree converted_args;
10963
10964       if (DECL_TEMPLATE_INFO (decl))
10965         tmpl = DECL_TI_TEMPLATE (decl);
10966       else
10967         /* We can get here for some invalid specializations.  */
10968         return NULL_TREE;
10969
10970       converted_args
10971         = (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
10972                                   explicit_args, NULL_TREE,
10973                                   tf_none, /*require_all_arguments=*/0));
10974       if (converted_args == error_mark_node)
10975         return NULL_TREE;
10976
10977       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
10978       if (decl_type == error_mark_node)
10979         return NULL_TREE;
10980     }
10981
10982   decl_arg_types = TYPE_ARG_TYPES (decl_type);
10983   /* Never do unification on the 'this' parameter.  */
10984   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
10985     decl_arg_types = TREE_CHAIN (decl_arg_types);
10986
10987   if (fn_type_unification (fn, explicit_args, targs,
10988                            decl_arg_types,
10989                            (check_rettype || DECL_CONV_FN_P (fn)
10990                             ? TREE_TYPE (decl_type) : NULL_TREE),
10991                            DEDUCE_EXACT, LOOKUP_NORMAL))
10992     return NULL_TREE;
10993
10994   return targs;
10995 }
10996
10997 /* Return the innermost template arguments that, when applied to a
10998    template specialization whose innermost template parameters are
10999    TPARMS, and whose specialization arguments are PARMS, yield the
11000    ARGS.
11001
11002    For example, suppose we have:
11003
11004      template <class T, class U> struct S {};
11005      template <class T> struct S<T*, int> {};
11006
11007    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
11008    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
11009    int}.  The resulting vector will be {double}, indicating that `T'
11010    is bound to `double'.  */
11011
11012 static tree
11013 get_class_bindings (tree tparms, tree spec_args, tree args)
11014 {
11015   int i, ntparms = TREE_VEC_LENGTH (tparms);
11016   tree deduced_args;
11017   tree innermost_deduced_args;
11018
11019   innermost_deduced_args = make_tree_vec (ntparms);
11020   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
11021     {
11022       deduced_args = copy_node (args);
11023       SET_TMPL_ARGS_LEVEL (deduced_args,
11024                            TMPL_ARGS_DEPTH (deduced_args),
11025                            innermost_deduced_args);
11026     }
11027   else
11028     deduced_args = innermost_deduced_args; 
11029
11030   if (unify (tparms, deduced_args, 
11031              INNERMOST_TEMPLATE_ARGS (spec_args), 
11032              INNERMOST_TEMPLATE_ARGS (args), 
11033              UNIFY_ALLOW_NONE))
11034     return NULL_TREE;
11035
11036   for (i =  0; i < ntparms; ++i)
11037     if (! TREE_VEC_ELT (innermost_deduced_args, i))
11038       return NULL_TREE;
11039
11040   /* Verify that nondeduced template arguments agree with the type
11041      obtained from argument deduction.
11042      
11043      For example:
11044
11045        struct A { typedef int X; };
11046        template <class T, class U> struct C {};
11047        template <class T> struct C<T, typename T::X> {};
11048
11049      Then with the instantiation `C<A, int>', we can deduce that
11050      `T' is `A' but unify () does not check whether `typename T::X'
11051      is `int'.  */
11052   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
11053   if (spec_args == error_mark_node
11054       /* We only need to check the innermost arguments; the other
11055          arguments will always agree.  */
11056       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
11057                               INNERMOST_TEMPLATE_ARGS (args)))
11058     return NULL_TREE;
11059
11060   return deduced_args;
11061 }
11062
11063 /* In INSTANTIATIONS is a list of <INSTANTIATION, TEMPLATE> pairs.
11064    Pick the most specialized template, and return the corresponding
11065    instantiation, or if there is no corresponding instantiation, the
11066    template itself.  If there is no most specialized template,
11067    error_mark_node is returned.  If there are no templates at all,
11068    NULL_TREE is returned.  */
11069
11070 tree
11071 most_specialized_instantiation (tree instantiations)
11072 {
11073   tree fn, champ;
11074
11075   if (!instantiations)
11076     return NULL_TREE;
11077
11078   ++processing_template_decl;
11079
11080   champ = instantiations;
11081   for (fn = TREE_CHAIN (instantiations); fn; fn = TREE_CHAIN (fn))
11082     {
11083       int fate = 0;
11084
11085       if (get_bindings (TREE_VALUE (champ),
11086                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
11087                         NULL_TREE, /*check_ret=*/false))
11088         fate--;
11089
11090       if (get_bindings (TREE_VALUE (fn),
11091                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
11092                         NULL_TREE, /*check_ret=*/false))
11093         fate++;
11094
11095       if (fate == -1)
11096         champ = fn;
11097       else if (!fate)
11098         {
11099           /* Equally specialized, move to next function.  If there
11100              is no next function, nothing's most specialized.  */
11101           fn = TREE_CHAIN (fn);
11102           champ = fn;
11103           if (!fn)
11104             break;
11105         }
11106     }
11107
11108   if (champ)
11109     /* Now verify that champ is better than everything earlier in the
11110        instantiation list.  */
11111     for (fn = instantiations; fn != champ; fn = TREE_CHAIN (fn))
11112       if (get_bindings (TREE_VALUE (champ),
11113                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
11114                         NULL_TREE, /*check_ret=*/false)
11115           || !get_bindings (TREE_VALUE (fn),
11116                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
11117                             NULL_TREE, /*check_ret=*/false))
11118         {
11119           champ = NULL_TREE;
11120           break;
11121         }
11122
11123   processing_template_decl--;
11124
11125   if (!champ)
11126     return error_mark_node;
11127
11128   return TREE_PURPOSE (champ) ? TREE_PURPOSE (champ) : TREE_VALUE (champ);
11129 }
11130
11131 /* Return the most specialized of the list of templates in FNS that can
11132    produce an instantiation matching DECL, given the explicit template
11133    arguments EXPLICIT_ARGS.  */
11134
11135 static tree
11136 most_specialized (tree fns, tree decl, tree explicit_args)
11137 {
11138   tree candidates = NULL_TREE;
11139   tree fn, args;
11140
11141   for (fn = fns; fn; fn = TREE_CHAIN (fn))
11142     {
11143       tree candidate = TREE_VALUE (fn);
11144
11145       args = get_bindings (candidate, decl, explicit_args, /*check_ret=*/true);
11146       if (args)
11147         candidates = tree_cons (NULL_TREE, candidate, candidates);
11148     }
11149
11150   return most_specialized_instantiation (candidates);
11151 }
11152
11153 /* If DECL is a specialization of some template, return the most
11154    general such template.  Otherwise, returns NULL_TREE.
11155
11156    For example, given:
11157
11158      template <class T> struct S { template <class U> void f(U); };
11159
11160    if TMPL is `template <class U> void S<int>::f(U)' this will return
11161    the full template.  This function will not trace past partial
11162    specializations, however.  For example, given in addition:
11163
11164      template <class T> struct S<T*> { template <class U> void f(U); };
11165
11166    if TMPL is `template <class U> void S<int*>::f(U)' this will return
11167    `template <class T> template <class U> S<T*>::f(U)'.  */
11168
11169 tree
11170 most_general_template (tree decl)
11171 {
11172   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
11173      an immediate specialization.  */
11174   if (TREE_CODE (decl) == FUNCTION_DECL)
11175     {
11176       if (DECL_TEMPLATE_INFO (decl)) {
11177         decl = DECL_TI_TEMPLATE (decl);
11178
11179         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
11180            template friend.  */
11181         if (TREE_CODE (decl) != TEMPLATE_DECL)
11182           return NULL_TREE;
11183       } else
11184         return NULL_TREE;
11185     }
11186
11187   /* Look for more and more general templates.  */
11188   while (DECL_TEMPLATE_INFO (decl))
11189     {
11190       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
11191          (See cp-tree.h for details.)  */
11192       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11193         break;
11194
11195       if (CLASS_TYPE_P (TREE_TYPE (decl))
11196           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
11197         break;
11198
11199       /* Stop if we run into an explicitly specialized class template.  */
11200       if (!DECL_NAMESPACE_SCOPE_P (decl)
11201           && DECL_CONTEXT (decl)
11202           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
11203         break;
11204
11205       decl = DECL_TI_TEMPLATE (decl);
11206     }
11207
11208   return decl;
11209 }
11210
11211 /* Return the most specialized of the class template partial
11212    specializations of TMPL which can produce TYPE, a specialization of
11213    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
11214    a _TYPE node corresponding to the partial specialization, while the
11215    TREE_PURPOSE is the set of template arguments that must be
11216    substituted into the TREE_TYPE in order to generate TYPE.
11217
11218    If the choice of partial specialization is ambiguous, a diagnostic
11219    is issued, and the error_mark_node is returned.  If there are no
11220    partial specializations of TMPL matching TYPE, then NULL_TREE is
11221    returned.  */
11222
11223 static tree
11224 most_specialized_class (tree type, tree tmpl)
11225 {
11226   tree list = NULL_TREE;
11227   tree t;
11228   tree champ;
11229   int fate;
11230   bool ambiguous_p;
11231   tree args;
11232
11233   tmpl = most_general_template (tmpl);
11234   args = CLASSTYPE_TI_ARGS (type);
11235   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
11236     {
11237       tree partial_spec_args;
11238       tree spec_args;
11239
11240       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
11241       spec_args = get_class_bindings (TREE_VALUE (t), 
11242                                       partial_spec_args, 
11243                                       args);
11244       if (spec_args)
11245         {
11246           list = tree_cons (spec_args, TREE_VALUE (t), list);
11247           TREE_TYPE (list) = TREE_TYPE (t);
11248         }
11249     }
11250
11251   if (! list)
11252     return NULL_TREE;
11253
11254   ambiguous_p = false;
11255   t = list;
11256   champ = t;
11257   t = TREE_CHAIN (t);
11258   for (; t; t = TREE_CHAIN (t))
11259     {
11260       fate = more_specialized_class (champ, t);
11261       if (fate == 1)
11262         ;
11263       else
11264         {
11265           if (fate == 0)
11266             {
11267               t = TREE_CHAIN (t);
11268               if (! t)
11269                 {
11270                   ambiguous_p = true;
11271                   break;
11272                 }
11273             }
11274           champ = t;
11275         }
11276     }
11277
11278   if (!ambiguous_p)
11279     for (t = list; t && t != champ; t = TREE_CHAIN (t))
11280       {
11281         fate = more_specialized_class (champ, t);
11282         if (fate != 1)
11283           {
11284             ambiguous_p = true;
11285             break;
11286           }
11287       }
11288
11289   if (ambiguous_p)
11290     {
11291       const char *str = "candidates are:";
11292       error ("ambiguous class template instantiation for %q#T", type);
11293       for (t = list; t; t = TREE_CHAIN (t))
11294         {
11295           error ("%s %+#T", str, TREE_TYPE (t));
11296           str = "               ";
11297         }
11298       return error_mark_node;
11299     }
11300
11301   return champ;
11302 }
11303
11304 /* Explicitly instantiate DECL.  */
11305
11306 void
11307 do_decl_instantiation (tree decl, tree storage)
11308 {
11309   tree result = NULL_TREE;
11310   int extern_p = 0;
11311
11312   if (!decl || decl == error_mark_node)
11313     /* An error occurred, for which grokdeclarator has already issued
11314        an appropriate message.  */
11315     return;
11316   else if (! DECL_LANG_SPECIFIC (decl))
11317     {
11318       error ("explicit instantiation of non-template %q#D", decl);
11319       return;
11320     }
11321   else if (TREE_CODE (decl) == VAR_DECL)
11322     {
11323       /* There is an asymmetry here in the way VAR_DECLs and
11324          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
11325          the latter, the DECL we get back will be marked as a
11326          template instantiation, and the appropriate
11327          DECL_TEMPLATE_INFO will be set up.  This does not happen for
11328          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
11329          should handle VAR_DECLs as it currently handles
11330          FUNCTION_DECLs.  */
11331       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
11332       if (!result || TREE_CODE (result) != VAR_DECL)
11333         {
11334           error ("no matching template for %qD found", decl);
11335           return;
11336         }
11337     }
11338   else if (TREE_CODE (decl) != FUNCTION_DECL)
11339     {
11340       error ("explicit instantiation of %q#D", decl);
11341       return;
11342     }
11343   else
11344     result = decl;
11345
11346   /* Check for various error cases.  Note that if the explicit
11347      instantiation is valid the RESULT will currently be marked as an
11348      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
11349      until we get here.  */
11350
11351   if (DECL_TEMPLATE_SPECIALIZATION (result))
11352     {
11353       /* DR 259 [temp.spec].
11354
11355          Both an explicit instantiation and a declaration of an explicit
11356          specialization shall not appear in a program unless the explicit
11357          instantiation follows a declaration of the explicit specialization.
11358
11359          For a given set of template parameters, if an explicit
11360          instantiation of a template appears after a declaration of an
11361          explicit specialization for that template, the explicit
11362          instantiation has no effect.  */
11363       return;
11364     }
11365   else if (DECL_EXPLICIT_INSTANTIATION (result))
11366     {
11367       /* [temp.spec]
11368
11369          No program shall explicitly instantiate any template more
11370          than once.
11371
11372          We check DECL_NOT_REALLY_EXTERN so as not to complain when
11373          the first instantiation was `extern' and the second is not,
11374          and EXTERN_P for the opposite case.  */
11375       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
11376         pedwarn ("duplicate explicit instantiation of %q#D", result);
11377       /* If an "extern" explicit instantiation follows an ordinary
11378          explicit instantiation, the template is instantiated.  */
11379       if (extern_p)
11380         return;
11381     }
11382   else if (!DECL_IMPLICIT_INSTANTIATION (result))
11383     {
11384       error ("no matching template for %qD found", result);
11385       return;
11386     }
11387   else if (!DECL_TEMPLATE_INFO (result))
11388     {
11389       pedwarn ("explicit instantiation of non-template %q#D", result);
11390       return;
11391     }
11392
11393   if (storage == NULL_TREE)
11394     ;
11395   else if (storage == ridpointers[(int) RID_EXTERN])
11396     {
11397       if (pedantic && !in_system_header)
11398         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
11399                  "instantiations");
11400       extern_p = 1;
11401     }
11402   else
11403     error ("storage class %qD applied to template instantiation", storage);
11404   
11405   check_explicit_instantiation_namespace (result);
11406   mark_decl_instantiated (result, extern_p);
11407   if (! extern_p)
11408     instantiate_decl (result, /*defer_ok=*/1, 
11409                       /*expl_inst_class_mem_p=*/false);
11410 }
11411
11412 void
11413 mark_class_instantiated (tree t, int extern_p)
11414 {
11415   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
11416   SET_CLASSTYPE_INTERFACE_KNOWN (t);
11417   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
11418   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
11419   if (! extern_p)
11420     {
11421       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
11422       rest_of_type_compilation (t, 1);
11423     }
11424 }
11425
11426 /* Called from do_type_instantiation through binding_table_foreach to
11427    do recursive instantiation for the type bound in ENTRY.  */
11428 static void
11429 bt_instantiate_type_proc (binding_entry entry, void *data)
11430 {
11431   tree storage = *(tree *) data;
11432
11433   if (IS_AGGR_TYPE (entry->type)
11434       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
11435     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
11436 }
11437
11438 /* Called from do_type_instantiation to instantiate a member
11439    (a member function or a static member variable) of an
11440    explicitly instantiated class template.  */
11441 static void
11442 instantiate_class_member (tree decl, int extern_p)
11443 {
11444   mark_decl_instantiated (decl, extern_p);
11445   if (! extern_p)
11446     instantiate_decl (decl, /*defer_ok=*/1, 
11447                       /*expl_inst_class_mem_p=*/true);
11448 }
11449
11450 /* Perform an explicit instantiation of template class T.  STORAGE, if
11451    non-null, is the RID for extern, inline or static.  COMPLAIN is
11452    nonzero if this is called from the parser, zero if called recursively,
11453    since the standard is unclear (as detailed below).  */
11454
11455 void
11456 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
11457 {
11458   int extern_p = 0;
11459   int nomem_p = 0;
11460   int static_p = 0;
11461   int previous_instantiation_extern_p = 0;
11462
11463   if (TREE_CODE (t) == TYPE_DECL)
11464     t = TREE_TYPE (t);
11465
11466   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
11467     {
11468       error ("explicit instantiation of non-template type %qT", t);
11469       return;
11470     }
11471
11472   complete_type (t);
11473
11474   if (!COMPLETE_TYPE_P (t))
11475     {
11476       if (complain & tf_error)
11477         error ("explicit instantiation of %q#T before definition of template",
11478                t);
11479       return;
11480     }
11481
11482   if (storage != NULL_TREE)
11483     {
11484       if (pedantic && !in_system_header)
11485         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
11486                 storage);
11487
11488       if (storage == ridpointers[(int) RID_INLINE])
11489         nomem_p = 1;
11490       else if (storage == ridpointers[(int) RID_EXTERN])
11491         extern_p = 1;
11492       else if (storage == ridpointers[(int) RID_STATIC])
11493         static_p = 1;
11494       else
11495         {
11496           error ("storage class %qD applied to template instantiation",
11497                  storage);
11498           extern_p = 0;
11499         }
11500     }
11501
11502   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
11503     {
11504       /* DR 259 [temp.spec].
11505
11506          Both an explicit instantiation and a declaration of an explicit
11507          specialization shall not appear in a program unless the explicit
11508          instantiation follows a declaration of the explicit specialization.
11509
11510          For a given set of template parameters, if an explicit
11511          instantiation of a template appears after a declaration of an
11512          explicit specialization for that template, the explicit
11513          instantiation has no effect.  */
11514       return;
11515     }
11516   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
11517     {
11518       /* [temp.spec]
11519
11520          No program shall explicitly instantiate any template more
11521          than once.
11522
11523          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
11524          instantiation was `extern'.  If EXTERN_P then the second is.
11525          These cases are OK.  */
11526       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
11527
11528       if (!previous_instantiation_extern_p && !extern_p
11529           && (complain & tf_error))
11530         pedwarn ("duplicate explicit instantiation of %q#T", t);
11531
11532       /* If we've already instantiated the template, just return now.  */
11533       if (!CLASSTYPE_INTERFACE_ONLY (t))
11534         return;
11535     }
11536
11537   check_explicit_instantiation_namespace (TYPE_NAME (t));
11538   mark_class_instantiated (t, extern_p);
11539
11540   if (nomem_p)
11541     return;
11542
11543   {
11544     tree tmp;
11545
11546     /* In contrast to implicit instantiation, where only the
11547        declarations, and not the definitions, of members are
11548        instantiated, we have here:
11549
11550          [temp.explicit]
11551
11552          The explicit instantiation of a class template specialization
11553          implies the instantiation of all of its members not
11554          previously explicitly specialized in the translation unit
11555          containing the explicit instantiation.
11556
11557        Of course, we can't instantiate member template classes, since
11558        we don't have any arguments for them.  Note that the standard
11559        is unclear on whether the instantiation of the members are
11560        *explicit* instantiations or not.  However, the most natural
11561        interpretation is that it should be an explicit instantiation.  */
11562
11563     if (! static_p)
11564       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
11565         if (TREE_CODE (tmp) == FUNCTION_DECL
11566             && DECL_TEMPLATE_INSTANTIATION (tmp))
11567           instantiate_class_member (tmp, extern_p);
11568
11569     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
11570       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
11571         instantiate_class_member (tmp, extern_p);
11572
11573     if (CLASSTYPE_NESTED_UTDS (t))
11574       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
11575                              bt_instantiate_type_proc, &storage);
11576   }
11577 }
11578
11579 /* Given a function DECL, which is a specialization of TMPL, modify
11580    DECL to be a re-instantiation of TMPL with the same template
11581    arguments.  TMPL should be the template into which tsubst'ing
11582    should occur for DECL, not the most general template.
11583
11584    One reason for doing this is a scenario like this:
11585
11586      template <class T>
11587      void f(const T&, int i);
11588
11589      void g() { f(3, 7); }
11590
11591      template <class T>
11592      void f(const T& t, const int i) { }
11593
11594    Note that when the template is first instantiated, with
11595    instantiate_template, the resulting DECL will have no name for the
11596    first parameter, and the wrong type for the second.  So, when we go
11597    to instantiate the DECL, we regenerate it.  */
11598
11599 static void
11600 regenerate_decl_from_template (tree decl, tree tmpl)
11601 {
11602   /* The arguments used to instantiate DECL, from the most general
11603      template.  */
11604   tree args;
11605   tree code_pattern;
11606
11607   args = DECL_TI_ARGS (decl);
11608   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
11609
11610   /* Make sure that we can see identifiers, and compute access
11611      correctly.  */
11612   push_access_scope (decl);
11613
11614   if (TREE_CODE (decl) == FUNCTION_DECL)
11615     {
11616       tree decl_parm;
11617       tree pattern_parm;
11618       tree specs;
11619       int args_depth;
11620       int parms_depth;
11621
11622       args_depth = TMPL_ARGS_DEPTH (args);
11623       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
11624       if (args_depth > parms_depth)
11625         args = get_innermost_template_args (args, parms_depth);
11626
11627       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
11628                                               args, tf_error, NULL_TREE);
11629       if (specs)
11630         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
11631                                                     specs);
11632
11633       /* Merge parameter declarations.  */
11634       decl_parm = skip_artificial_parms_for (decl,
11635                                              DECL_ARGUMENTS (decl));
11636       pattern_parm
11637         = skip_artificial_parms_for (code_pattern,
11638                                      DECL_ARGUMENTS (code_pattern));
11639       while (decl_parm)
11640         {
11641           tree parm_type;
11642           tree attributes;
11643
11644           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
11645             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
11646           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
11647                               NULL_TREE);
11648           parm_type = type_decays_to (parm_type);
11649           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
11650             TREE_TYPE (decl_parm) = parm_type;
11651           attributes = DECL_ATTRIBUTES (pattern_parm);
11652           if (DECL_ATTRIBUTES (decl_parm) != attributes)
11653             {
11654               DECL_ATTRIBUTES (decl_parm) = attributes;
11655               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
11656             }
11657           decl_parm = TREE_CHAIN (decl_parm);
11658           pattern_parm = TREE_CHAIN (pattern_parm);
11659         }
11660
11661       /* Merge additional specifiers from the CODE_PATTERN.  */
11662       if (DECL_DECLARED_INLINE_P (code_pattern)
11663           && !DECL_DECLARED_INLINE_P (decl))
11664         DECL_DECLARED_INLINE_P (decl) = 1;
11665       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
11666         DECL_INLINE (decl) = 1;
11667     }
11668   else if (TREE_CODE (decl) == VAR_DECL)
11669     DECL_INITIAL (decl) =
11670       tsubst_expr (DECL_INITIAL (code_pattern), args,
11671                    tf_error, DECL_TI_TEMPLATE (decl));
11672   else
11673     gcc_unreachable ();
11674
11675   pop_access_scope (decl);
11676 }
11677
11678 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
11679    substituted to get DECL.  */
11680
11681 tree
11682 template_for_substitution (tree decl)
11683 {
11684   tree tmpl = DECL_TI_TEMPLATE (decl);
11685
11686   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
11687      for the instantiation.  This is not always the most general
11688      template.  Consider, for example:
11689
11690         template <class T>
11691         struct S { template <class U> void f();
11692                    template <> void f<int>(); };
11693
11694      and an instantiation of S<double>::f<int>.  We want TD to be the
11695      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
11696   while (/* An instantiation cannot have a definition, so we need a
11697             more general template.  */
11698          DECL_TEMPLATE_INSTANTIATION (tmpl)
11699            /* We must also deal with friend templates.  Given:
11700
11701                 template <class T> struct S {
11702                   template <class U> friend void f() {};
11703                 };
11704
11705               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
11706               so far as the language is concerned, but that's still
11707               where we get the pattern for the instantiation from.  On
11708               other hand, if the definition comes outside the class, say:
11709
11710                 template <class T> struct S {
11711                   template <class U> friend void f();
11712                 };
11713                 template <class U> friend void f() {}
11714
11715               we don't need to look any further.  That's what the check for
11716               DECL_INITIAL is for.  */
11717           || (TREE_CODE (decl) == FUNCTION_DECL
11718               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
11719               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
11720     {
11721       /* The present template, TD, should not be a definition.  If it
11722          were a definition, we should be using it!  Note that we
11723          cannot restructure the loop to just keep going until we find
11724          a template with a definition, since that might go too far if
11725          a specialization was declared, but not defined.  */
11726       gcc_assert (TREE_CODE (decl) != VAR_DECL
11727                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
11728
11729       /* Fetch the more general template.  */
11730       tmpl = DECL_TI_TEMPLATE (tmpl);
11731     }
11732
11733   return tmpl;
11734 }
11735
11736 /* Produce the definition of D, a _DECL generated from a template.  If
11737    DEFER_OK is nonzero, then we don't have to actually do the
11738    instantiation now; we just have to do it sometime.  Normally it is
11739    an error if this is an explicit instantiation but D is undefined.
11740    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
11741    explicitly instantiated class template.  */
11742
11743 tree
11744 instantiate_decl (tree d, int defer_ok, 
11745                   bool expl_inst_class_mem_p)
11746 {
11747   tree tmpl = DECL_TI_TEMPLATE (d);
11748   tree gen_args;
11749   tree args;
11750   tree td;
11751   tree code_pattern;
11752   tree spec;
11753   tree gen_tmpl;
11754   bool pattern_defined;
11755   int need_push;
11756   location_t saved_loc = input_location;
11757   bool external_p;
11758
11759   /* This function should only be used to instantiate templates for
11760      functions and static member variables.  */
11761   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
11762               || TREE_CODE (d) == VAR_DECL);
11763
11764   /* Variables are never deferred; if instantiation is required, they
11765      are instantiated right away.  That allows for better code in the
11766      case that an expression refers to the value of the variable --
11767      if the variable has a constant value the referring expression can
11768      take advantage of that fact.  */
11769   if (TREE_CODE (d) == VAR_DECL)
11770     defer_ok = 0;
11771
11772   /* Don't instantiate cloned functions.  Instead, instantiate the
11773      functions they cloned.  */
11774   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
11775     d = DECL_CLONED_FUNCTION (d);
11776
11777   if (DECL_TEMPLATE_INSTANTIATED (d))
11778     /* D has already been instantiated.  It might seem reasonable to
11779        check whether or not D is an explicit instantiation, and, if so,
11780        stop here.  But when an explicit instantiation is deferred
11781        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
11782        is set, even though we still need to do the instantiation.  */
11783     return d;
11784
11785   /* If we already have a specialization of this declaration, then
11786      there's no reason to instantiate it.  Note that
11787      retrieve_specialization gives us both instantiations and
11788      specializations, so we must explicitly check
11789      DECL_TEMPLATE_SPECIALIZATION.  */
11790   gen_tmpl = most_general_template (tmpl);
11791   gen_args = DECL_TI_ARGS (d);
11792   spec = retrieve_specialization (gen_tmpl, gen_args,
11793                                   /*class_specializations_p=*/false);
11794   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
11795     return spec;
11796
11797   /* This needs to happen before any tsubsting.  */
11798   if (! push_tinst_level (d))
11799     return d;
11800
11801   timevar_push (TV_PARSE);
11802
11803   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
11804      for the instantiation.  */
11805   td = template_for_substitution (d);
11806   code_pattern = DECL_TEMPLATE_RESULT (td);
11807
11808   /* We should never be trying to instantiate a member of a class
11809      template or partial specialization.  */ 
11810   gcc_assert (d != code_pattern);
11811  
11812   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
11813       || DECL_TEMPLATE_SPECIALIZATION (td))
11814     /* In the case of a friend template whose definition is provided
11815        outside the class, we may have too many arguments.  Drop the
11816        ones we don't need.  The same is true for specializations.  */
11817     args = get_innermost_template_args
11818       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
11819   else
11820     args = gen_args;
11821
11822   if (TREE_CODE (d) == FUNCTION_DECL)
11823     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
11824   else
11825     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
11826
11827   /* We may be in the middle of deferred access check.  Disable it now.  */
11828   push_deferring_access_checks (dk_no_deferred);
11829
11830   /* Unless an explicit instantiation directive has already determined
11831      the linkage of D, remember that a definition is available for
11832      this entity.  */
11833   if (pattern_defined
11834       && !DECL_INTERFACE_KNOWN (d)
11835       && !DECL_NOT_REALLY_EXTERN (d))
11836     mark_definable (d);
11837
11838   input_location = DECL_SOURCE_LOCATION (d);
11839
11840   /* If D is a member of an explicitly instantiated class template,
11841      and no definition is available, treat it like an implicit
11842      instantiation.  */ 
11843   if (!pattern_defined && expl_inst_class_mem_p 
11844       && DECL_EXPLICIT_INSTANTIATION (d)) 
11845     {
11846       DECL_NOT_REALLY_EXTERN (d) = 0;
11847       DECL_INTERFACE_KNOWN (d) = 0;
11848       SET_DECL_IMPLICIT_INSTANTIATION (d);
11849     }
11850
11851   if (!defer_ok)
11852     {
11853       /* Recheck the substitutions to obtain any warning messages
11854          about ignoring cv qualifiers.  */
11855       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
11856       tree type = TREE_TYPE (gen);
11857
11858       /* Make sure that we can see identifiers, and compute access
11859          correctly.  D is already the target FUNCTION_DECL with the
11860          right context.  */
11861       push_access_scope (d);
11862
11863       if (TREE_CODE (gen) == FUNCTION_DECL)
11864         {
11865           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_error | tf_warning, d);
11866           tsubst (TYPE_RAISES_EXCEPTIONS (type), gen_args,
11867                   tf_error | tf_warning, d);
11868           /* Don't simply tsubst the function type, as that will give
11869              duplicate warnings about poor parameter qualifications.
11870              The function arguments are the same as the decl_arguments
11871              without the top level cv qualifiers.  */
11872           type = TREE_TYPE (type);
11873         }
11874       tsubst (type, gen_args, tf_error | tf_warning, d);
11875
11876       pop_access_scope (d);
11877     }
11878
11879   /* Check to see whether we know that this template will be
11880      instantiated in some other file, as with "extern template"
11881      extension.  */
11882   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
11883   /* In general, we do not instantiate such templates...  */
11884   if (external_p
11885       /* ... but we instantiate inline functions so that we can inline
11886          them and ... */
11887       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
11888       /* ... we instantiate static data members whose values are
11889          needed in integral constant expressions.  */
11890       && ! (TREE_CODE (d) == VAR_DECL 
11891             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
11892     goto out;
11893   /* Defer all other templates, unless we have been explicitly
11894      forbidden from doing so.  */
11895   if (/* If there is no definition, we cannot instantiate the
11896          template.  */
11897       ! pattern_defined 
11898       /* If it's OK to postpone instantiation, do so.  */
11899       || defer_ok
11900       /* If this is a static data member that will be defined
11901          elsewhere, we don't want to instantiate the entire data
11902          member, but we do want to instantiate the initializer so that
11903          we can substitute that elsewhere.  */
11904       || (external_p && TREE_CODE (d) == VAR_DECL))
11905     {
11906       /* The definition of the static data member is now required so
11907          we must substitute the initializer.  */
11908       if (TREE_CODE (d) == VAR_DECL
11909           && !DECL_INITIAL (d) 
11910           && DECL_INITIAL (code_pattern))
11911         {
11912           tree ns;
11913           tree init;
11914
11915           ns = decl_namespace_context (d);
11916           push_nested_namespace (ns);
11917           push_nested_class (DECL_CONTEXT (d));
11918           init = tsubst_expr (DECL_INITIAL (code_pattern), 
11919                               args,
11920                               tf_error | tf_warning, NULL_TREE);
11921           DECL_INITIAL (d) = init;
11922           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
11923                           /*asmspec_tree=*/NULL_TREE,
11924                           LOOKUP_ONLYCONVERTING);
11925           pop_nested_class ();
11926           pop_nested_namespace (ns);
11927         }
11928
11929       /* We restore the source position here because it's used by
11930          add_pending_template.  */
11931       input_location = saved_loc;
11932
11933       if (at_eof && !pattern_defined
11934           && DECL_EXPLICIT_INSTANTIATION (d))
11935         /* [temp.explicit]
11936
11937            The definition of a non-exported function template, a
11938            non-exported member function template, or a non-exported
11939            member function or static data member of a class template
11940            shall be present in every translation unit in which it is
11941            explicitly instantiated.  */
11942         pedwarn
11943           ("explicit instantiation of %qD but no definition available", d);
11944
11945       /* ??? Historically, we have instantiated inline functions, even
11946          when marked as "extern template".  */
11947       if (!(external_p && TREE_CODE (d) == VAR_DECL))
11948         add_pending_template (d);
11949       goto out;
11950     }
11951   /* Tell the repository that D is available in this translation unit
11952      -- and see if it is supposed to be instantiated here.  */
11953   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
11954     {
11955       /* In a PCH file, despite the fact that the repository hasn't
11956          requested instantiation in the PCH it is still possible that
11957          an instantiation will be required in a file that includes the
11958          PCH.  */
11959       if (pch_file)
11960         add_pending_template (d);
11961       /* Instantiate inline functions so that the inliner can do its
11962          job, even though we'll not be emitting a copy of this
11963          function.  */
11964       if (!(TREE_CODE (d) == FUNCTION_DECL
11965             && flag_inline_trees
11966             && DECL_DECLARED_INLINE_P (d)))
11967         goto out;
11968     }
11969
11970   need_push = !cfun || !global_bindings_p ();
11971   if (need_push)
11972     push_to_top_level ();
11973
11974   /* Mark D as instantiated so that recursive calls to
11975      instantiate_decl do not try to instantiate it again.  */
11976   DECL_TEMPLATE_INSTANTIATED (d) = 1;
11977
11978   /* Regenerate the declaration in case the template has been modified
11979      by a subsequent redeclaration.  */
11980   regenerate_decl_from_template (d, td);
11981
11982   /* We already set the file and line above.  Reset them now in case
11983      they changed as a result of calling regenerate_decl_from_template.  */
11984   input_location = DECL_SOURCE_LOCATION (d);
11985
11986   if (TREE_CODE (d) == VAR_DECL)
11987     {
11988       /* Clear out DECL_RTL; whatever was there before may not be right
11989          since we've reset the type of the declaration.  */
11990       SET_DECL_RTL (d, NULL_RTX);
11991       DECL_IN_AGGR_P (d) = 0;
11992
11993       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
11994          initializer.  That function will defer actual emission until
11995          we have a chance to determine linkage.  */
11996       DECL_EXTERNAL (d) = 0;
11997
11998       /* Enter the scope of D so that access-checking works correctly.  */
11999       push_nested_class (DECL_CONTEXT (d));
12000       finish_decl (d, DECL_INITIAL (d), NULL_TREE);
12001       pop_nested_class ();
12002     }
12003   else if (TREE_CODE (d) == FUNCTION_DECL)
12004     {
12005       htab_t saved_local_specializations;
12006       tree subst_decl;
12007       tree tmpl_parm;
12008       tree spec_parm;
12009
12010       /* Save away the current list, in case we are instantiating one
12011          template from within the body of another.  */
12012       saved_local_specializations = local_specializations;
12013
12014       /* Set up the list of local specializations.  */
12015       local_specializations = htab_create (37,
12016                                            hash_local_specialization,
12017                                            eq_local_specializations,
12018                                            NULL);
12019
12020       /* Set up context.  */
12021       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
12022
12023       /* Create substitution entries for the parameters.  */
12024       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
12025       tmpl_parm = DECL_ARGUMENTS (subst_decl);
12026       spec_parm = DECL_ARGUMENTS (d);
12027       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
12028         {
12029           register_local_specialization (spec_parm, tmpl_parm);
12030           spec_parm = skip_artificial_parms_for (d, spec_parm);
12031           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
12032         }
12033       while (tmpl_parm)
12034         {
12035           register_local_specialization (spec_parm, tmpl_parm);
12036           tmpl_parm = TREE_CHAIN (tmpl_parm);
12037           spec_parm = TREE_CHAIN (spec_parm);
12038         }
12039       gcc_assert (!spec_parm);
12040
12041       /* Substitute into the body of the function.  */
12042       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
12043                    tf_error | tf_warning, tmpl);
12044
12045       /* We don't need the local specializations any more.  */
12046       htab_delete (local_specializations);
12047       local_specializations = saved_local_specializations;
12048
12049       /* Finish the function.  */
12050       d = finish_function (0);
12051       expand_or_defer_fn (d);
12052     }
12053
12054   /* We're not deferring instantiation any more.  */
12055   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
12056
12057   if (need_push)
12058     pop_from_top_level ();
12059
12060 out:
12061   input_location = saved_loc;
12062   pop_deferring_access_checks ();
12063   pop_tinst_level ();
12064
12065   timevar_pop (TV_PARSE);
12066
12067   return d;
12068 }
12069
12070 /* Run through the list of templates that we wish we could
12071    instantiate, and instantiate any we can.  RETRIES is the
12072    number of times we retry pending template instantiation.  */
12073
12074 void
12075 instantiate_pending_templates (int retries)
12076 {
12077   tree *t;
12078   tree last = NULL_TREE;
12079   int reconsider;
12080   location_t saved_loc = input_location;
12081   int saved_in_system_header = in_system_header;
12082
12083   /* Instantiating templates may trigger vtable generation.  This in turn
12084      may require further template instantiations.  We place a limit here
12085      to avoid infinite loop.  */
12086   if (pending_templates && retries >= max_tinst_depth)
12087     {
12088       tree decl = TREE_VALUE (pending_templates);
12089
12090       error ("template instantiation depth exceeds maximum of %d"
12091              " instantiating %q+D, possibly from virtual table generation"
12092              " (use -ftemplate-depth-NN to increase the maximum)",
12093              max_tinst_depth, decl);
12094       if (TREE_CODE (decl) == FUNCTION_DECL)
12095         /* Pretend that we defined it.  */
12096         DECL_INITIAL (decl) = error_mark_node;
12097       return;
12098     }
12099
12100   do
12101     {
12102       reconsider = 0;
12103
12104       t = &pending_templates;
12105       while (*t)
12106         {
12107           tree instantiation = TREE_VALUE (*t);
12108
12109           reopen_tinst_level (TREE_PURPOSE (*t));
12110
12111           if (TYPE_P (instantiation))
12112             {
12113               tree fn;
12114
12115               if (!COMPLETE_TYPE_P (instantiation))
12116                 {
12117                   instantiate_class_template (instantiation);
12118                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
12119                     for (fn = TYPE_METHODS (instantiation);
12120                          fn;
12121                          fn = TREE_CHAIN (fn))
12122                       if (! DECL_ARTIFICIAL (fn))
12123                         instantiate_decl (fn, 
12124                                           /*defer_ok=*/0,
12125                                           /*expl_inst_class_mem_p=*/false);
12126                   if (COMPLETE_TYPE_P (instantiation))
12127                     reconsider = 1;
12128                 }
12129
12130               if (COMPLETE_TYPE_P (instantiation))
12131                 /* If INSTANTIATION has been instantiated, then we don't
12132                    need to consider it again in the future.  */
12133                 *t = TREE_CHAIN (*t);
12134               else
12135                 {
12136                   last = *t;
12137                   t = &TREE_CHAIN (*t);
12138                 }
12139             }
12140           else
12141             {
12142               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
12143                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
12144                 {
12145                   instantiation 
12146                     = instantiate_decl (instantiation,
12147                                         /*defer_ok=*/0,
12148                                         /*expl_inst_class_mem_p=*/false);
12149                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
12150                     reconsider = 1;
12151                 }
12152
12153               if (DECL_TEMPLATE_SPECIALIZATION (instantiation)
12154                   || DECL_TEMPLATE_INSTANTIATED (instantiation))
12155                 /* If INSTANTIATION has been instantiated, then we don't
12156                    need to consider it again in the future.  */
12157                 *t = TREE_CHAIN (*t);
12158               else
12159                 {
12160                   last = *t;
12161                   t = &TREE_CHAIN (*t);
12162                 }
12163             }
12164           tinst_depth = 0;
12165           current_tinst_level = NULL_TREE;
12166         }
12167       last_pending_template = last;
12168     }
12169   while (reconsider);
12170
12171   input_location = saved_loc;
12172   in_system_header = saved_in_system_header;
12173 }
12174
12175 /* Substitute ARGVEC into T, which is a list of initializers for
12176    either base class or a non-static data member.  The TREE_PURPOSEs
12177    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
12178    instantiate_decl.  */
12179
12180 static tree
12181 tsubst_initializer_list (tree t, tree argvec)
12182 {
12183   tree inits = NULL_TREE;
12184
12185   for (; t; t = TREE_CHAIN (t))
12186     {
12187       tree decl;
12188       tree init;
12189
12190       decl = tsubst_copy (TREE_PURPOSE (t), argvec, tf_error | tf_warning,
12191                           NULL_TREE);
12192       decl = expand_member_init (decl);
12193       if (decl && !DECL_P (decl))
12194         in_base_initializer = 1;
12195
12196       init = tsubst_expr (TREE_VALUE (t), argvec, tf_error | tf_warning,
12197                           NULL_TREE);
12198       in_base_initializer = 0;
12199
12200       if (decl)
12201         {
12202           init = build_tree_list (decl, init);
12203           TREE_CHAIN (init) = inits;
12204           inits = init;
12205         }
12206     }
12207   return inits;
12208 }
12209
12210 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
12211
12212 static void
12213 set_current_access_from_decl (tree decl)
12214 {
12215   if (TREE_PRIVATE (decl))
12216     current_access_specifier = access_private_node;
12217   else if (TREE_PROTECTED (decl))
12218     current_access_specifier = access_protected_node;
12219   else
12220     current_access_specifier = access_public_node;
12221 }
12222
12223 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
12224    is the instantiation (which should have been created with
12225    start_enum) and ARGS are the template arguments to use.  */
12226
12227 static void
12228 tsubst_enum (tree tag, tree newtag, tree args)
12229 {
12230   tree e;
12231
12232   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
12233     {
12234       tree value;
12235       tree decl;
12236
12237       decl = TREE_VALUE (e);
12238       /* Note that in a template enum, the TREE_VALUE is the
12239          CONST_DECL, not the corresponding INTEGER_CST.  */
12240       value = tsubst_expr (DECL_INITIAL (decl),
12241                            args, tf_error | tf_warning,
12242                            NULL_TREE);
12243
12244       /* Give this enumeration constant the correct access.  */
12245       set_current_access_from_decl (decl);
12246
12247       /* Actually build the enumerator itself.  */
12248       build_enumerator (DECL_NAME (decl), value, newtag);
12249     }
12250
12251   finish_enum (newtag);
12252   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
12253     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
12254 }
12255
12256 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
12257    its type -- but without substituting the innermost set of template
12258    arguments.  So, innermost set of template parameters will appear in
12259    the type.  */
12260
12261 tree
12262 get_mostly_instantiated_function_type (tree decl)
12263 {
12264   tree fn_type;
12265   tree tmpl;
12266   tree targs;
12267   tree tparms;
12268   int parm_depth;
12269
12270   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
12271   targs = DECL_TI_ARGS (decl);
12272   tparms = DECL_TEMPLATE_PARMS (tmpl);
12273   parm_depth = TMPL_PARMS_DEPTH (tparms);
12274
12275   /* There should be as many levels of arguments as there are levels
12276      of parameters.  */
12277   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
12278
12279   fn_type = TREE_TYPE (tmpl);
12280
12281   if (parm_depth == 1)
12282     /* No substitution is necessary.  */
12283     ;
12284   else
12285     {
12286       int i, save_access_control;
12287       tree partial_args;
12288
12289       /* Replace the innermost level of the TARGS with NULL_TREEs to
12290          let tsubst know not to substitute for those parameters.  */
12291       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
12292       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
12293         SET_TMPL_ARGS_LEVEL (partial_args, i,
12294                              TMPL_ARGS_LEVEL (targs, i));
12295       SET_TMPL_ARGS_LEVEL (partial_args,
12296                            TMPL_ARGS_DEPTH (targs),
12297                            make_tree_vec (DECL_NTPARMS (tmpl)));
12298
12299       /* Disable access control as this function is used only during
12300          name-mangling.  */
12301       save_access_control = flag_access_control;
12302       flag_access_control = 0;
12303
12304       ++processing_template_decl;
12305       /* Now, do the (partial) substitution to figure out the
12306          appropriate function type.  */
12307       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
12308       --processing_template_decl;
12309
12310       /* Substitute into the template parameters to obtain the real
12311          innermost set of parameters.  This step is important if the
12312          innermost set of template parameters contains value
12313          parameters whose types depend on outer template parameters.  */
12314       TREE_VEC_LENGTH (partial_args)--;
12315       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
12316
12317       flag_access_control = save_access_control;
12318     }
12319
12320   return fn_type;
12321 }
12322
12323 /* Return truthvalue if we're processing a template different from
12324    the last one involved in diagnostics.  */
12325 int
12326 problematic_instantiation_changed (void)
12327 {
12328   return last_template_error_tick != tinst_level_tick;
12329 }
12330
12331 /* Remember current template involved in diagnostics.  */
12332 void
12333 record_last_problematic_instantiation (void)
12334 {
12335   last_template_error_tick = tinst_level_tick;
12336 }
12337
12338 tree
12339 current_instantiation (void)
12340 {
12341   return current_tinst_level;
12342 }
12343
12344 /* [temp.param] Check that template non-type parm TYPE is of an allowable
12345    type. Return zero for ok, nonzero for disallowed. Issue error and
12346    warning messages under control of COMPLAIN.  */
12347
12348 static int
12349 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
12350 {
12351   if (INTEGRAL_TYPE_P (type))
12352     return 0;
12353   else if (POINTER_TYPE_P (type))
12354     return 0;
12355   else if (TYPE_PTR_TO_MEMBER_P (type))
12356     return 0;
12357   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
12358     return 0;
12359   else if (TREE_CODE (type) == TYPENAME_TYPE)
12360     return 0;
12361
12362   if (complain & tf_error)
12363     error ("%q#T is not a valid type for a template constant parameter", type);
12364   return 1;
12365 }
12366
12367 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
12368    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
12369
12370 static bool
12371 dependent_type_p_r (tree type)
12372 {
12373   tree scope;
12374
12375   /* [temp.dep.type]
12376
12377      A type is dependent if it is:
12378
12379      -- a template parameter. Template template parameters are types
12380         for us (since TYPE_P holds true for them) so we handle
12381         them here.  */
12382   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
12383       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
12384     return true;
12385   /* -- a qualified-id with a nested-name-specifier which contains a
12386         class-name that names a dependent type or whose unqualified-id
12387         names a dependent type.  */
12388   if (TREE_CODE (type) == TYPENAME_TYPE)
12389     return true;
12390   /* -- a cv-qualified type where the cv-unqualified type is
12391         dependent.  */
12392   type = TYPE_MAIN_VARIANT (type);
12393   /* -- a compound type constructed from any dependent type.  */
12394   if (TYPE_PTR_TO_MEMBER_P (type))
12395     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
12396             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
12397                                            (type)));
12398   else if (TREE_CODE (type) == POINTER_TYPE
12399            || TREE_CODE (type) == REFERENCE_TYPE)
12400     return dependent_type_p (TREE_TYPE (type));
12401   else if (TREE_CODE (type) == FUNCTION_TYPE
12402            || TREE_CODE (type) == METHOD_TYPE)
12403     {
12404       tree arg_type;
12405
12406       if (dependent_type_p (TREE_TYPE (type)))
12407         return true;
12408       for (arg_type = TYPE_ARG_TYPES (type);
12409            arg_type;
12410            arg_type = TREE_CHAIN (arg_type))
12411         if (dependent_type_p (TREE_VALUE (arg_type)))
12412           return true;
12413       return false;
12414     }
12415   /* -- an array type constructed from any dependent type or whose
12416         size is specified by a constant expression that is
12417         value-dependent.  */
12418   if (TREE_CODE (type) == ARRAY_TYPE)
12419     {
12420       if (TYPE_DOMAIN (type)
12421           && ((value_dependent_expression_p
12422                (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
12423               || (type_dependent_expression_p
12424                   (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))))
12425         return true;
12426       return dependent_type_p (TREE_TYPE (type));
12427     }
12428
12429   /* -- a template-id in which either the template name is a template
12430      parameter ...  */
12431   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
12432     return true;
12433   /* ... or any of the template arguments is a dependent type or
12434         an expression that is type-dependent or value-dependent.  */
12435   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
12436            && (any_dependent_template_arguments_p
12437                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
12438     return true;
12439
12440   /* All TYPEOF_TYPEs are dependent; if the argument of the `typeof'
12441      expression is not type-dependent, then it should already been
12442      have resolved.  */
12443   if (TREE_CODE (type) == TYPEOF_TYPE)
12444     return true;
12445
12446   /* The standard does not specifically mention types that are local
12447      to template functions or local classes, but they should be
12448      considered dependent too.  For example:
12449
12450        template <int I> void f() {
12451          enum E { a = I };
12452          S<sizeof (E)> s;
12453        }
12454
12455      The size of `E' cannot be known until the value of `I' has been
12456      determined.  Therefore, `E' must be considered dependent.  */
12457   scope = TYPE_CONTEXT (type);
12458   if (scope && TYPE_P (scope))
12459     return dependent_type_p (scope);
12460   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
12461     return type_dependent_expression_p (scope);
12462
12463   /* Other types are non-dependent.  */
12464   return false;
12465 }
12466
12467 /* Returns TRUE if TYPE is dependent, in the sense of
12468    [temp.dep.type].  */
12469
12470 bool
12471 dependent_type_p (tree type)
12472 {
12473   /* If there are no template parameters in scope, then there can't be
12474      any dependent types.  */
12475   if (!processing_template_decl)
12476     return false;
12477
12478   /* If the type is NULL, we have not computed a type for the entity
12479      in question; in that case, the type is dependent.  */
12480   if (!type)
12481     return true;
12482
12483   /* Erroneous types can be considered non-dependent.  */
12484   if (type == error_mark_node)
12485     return false;
12486
12487   /* If we have not already computed the appropriate value for TYPE,
12488      do so now.  */
12489   if (!TYPE_DEPENDENT_P_VALID (type))
12490     {
12491       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
12492       TYPE_DEPENDENT_P_VALID (type) = 1;
12493     }
12494
12495   return TYPE_DEPENDENT_P (type);
12496 }
12497
12498 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
12499
12500 static bool
12501 dependent_scope_ref_p (tree expression, bool criterion (tree))
12502 {
12503   tree scope;
12504   tree name;
12505
12506   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
12507
12508   if (!TYPE_P (TREE_OPERAND (expression, 0)))
12509     return true;
12510
12511   scope = TREE_OPERAND (expression, 0);
12512   name = TREE_OPERAND (expression, 1);
12513
12514   /* [temp.dep.expr]
12515
12516      An id-expression is type-dependent if it contains a
12517      nested-name-specifier that contains a class-name that names a
12518      dependent type.  */
12519   /* The suggested resolution to Core Issue 2 implies that if the
12520      qualifying type is the current class, then we must peek
12521      inside it.  */
12522   if (DECL_P (name)
12523       && currently_open_class (scope)
12524       && !criterion (name))
12525     return false;
12526   if (dependent_type_p (scope))
12527     return true;
12528
12529   return false;
12530 }
12531
12532 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
12533    [temp.dep.constexpr] */
12534
12535 bool
12536 value_dependent_expression_p (tree expression)
12537 {
12538   if (!processing_template_decl)
12539     return false;
12540
12541   /* A name declared with a dependent type.  */
12542   if (DECL_P (expression) && type_dependent_expression_p (expression))
12543     return true;
12544
12545   switch (TREE_CODE (expression))
12546     {
12547     case IDENTIFIER_NODE:
12548       /* A name that has not been looked up -- must be dependent.  */
12549       return true;
12550
12551     case TEMPLATE_PARM_INDEX:
12552       /* A non-type template parm.  */
12553       return true;
12554
12555     case CONST_DECL:
12556       /* A non-type template parm.  */
12557       if (DECL_TEMPLATE_PARM_P (expression))
12558         return true;
12559       return false;
12560
12561     case VAR_DECL:
12562        /* A constant with integral or enumeration type and is initialized
12563           with an expression that is value-dependent.  */
12564       if (DECL_INITIAL (expression)
12565           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
12566           && value_dependent_expression_p (DECL_INITIAL (expression)))
12567         return true;
12568       return false;
12569
12570     case DYNAMIC_CAST_EXPR:
12571     case STATIC_CAST_EXPR:
12572     case CONST_CAST_EXPR:
12573     case REINTERPRET_CAST_EXPR:
12574     case CAST_EXPR:
12575       /* These expressions are value-dependent if the type to which
12576          the cast occurs is dependent or the expression being casted
12577          is value-dependent.  */
12578       {
12579         tree type = TREE_TYPE (expression);
12580
12581         if (dependent_type_p (type))
12582           return true;
12583
12584         /* A functional cast has a list of operands.  */
12585         expression = TREE_OPERAND (expression, 0);
12586         if (!expression)
12587           {
12588             /* If there are no operands, it must be an expression such
12589                as "int()". This should not happen for aggregate types
12590                because it would form non-constant expressions.  */
12591             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
12592
12593             return false;
12594           }
12595
12596         if (TREE_CODE (expression) == TREE_LIST)
12597           {
12598             for (; expression; expression = TREE_CHAIN (expression))
12599               if (value_dependent_expression_p (TREE_VALUE (expression)))
12600                 return true;
12601             return false;
12602           }
12603
12604         return value_dependent_expression_p (expression);
12605       }
12606
12607     case SIZEOF_EXPR:
12608     case ALIGNOF_EXPR:
12609       /* A `sizeof' expression is value-dependent if the operand is
12610          type-dependent.  */
12611       expression = TREE_OPERAND (expression, 0);
12612       if (TYPE_P (expression))
12613         return dependent_type_p (expression);
12614       return type_dependent_expression_p (expression);
12615
12616     case SCOPE_REF:
12617       return dependent_scope_ref_p (expression, value_dependent_expression_p);
12618
12619     case COMPONENT_REF:
12620       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
12621               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
12622
12623     case CALL_EXPR:
12624       /* A CALL_EXPR may appear in a constant expression if it is a
12625          call to a builtin function, e.g., __builtin_constant_p.  All
12626          such calls are value-dependent.  */
12627       return true;
12628
12629     default:
12630       /* A constant expression is value-dependent if any subexpression is
12631          value-dependent.  */
12632       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
12633         {
12634         case tcc_reference:
12635         case tcc_unary:
12636           return (value_dependent_expression_p
12637                   (TREE_OPERAND (expression, 0)));
12638
12639         case tcc_comparison:
12640         case tcc_binary:
12641           return ((value_dependent_expression_p
12642                    (TREE_OPERAND (expression, 0)))
12643                   || (value_dependent_expression_p
12644                       (TREE_OPERAND (expression, 1))));
12645
12646         case tcc_expression:
12647           {
12648             int i;
12649             for (i = 0; i < TREE_CODE_LENGTH (TREE_CODE (expression)); ++i)
12650               /* In some cases, some of the operands may be missing.
12651                  (For example, in the case of PREDECREMENT_EXPR, the
12652                  amount to increment by may be missing.)  That doesn't
12653                  make the expression dependent.  */
12654               if (TREE_OPERAND (expression, i)
12655                   && (value_dependent_expression_p
12656                       (TREE_OPERAND (expression, i))))
12657                 return true;
12658             return false;
12659           }
12660
12661         default:
12662           break;
12663         }
12664     }
12665
12666   /* The expression is not value-dependent.  */
12667   return false;
12668 }
12669
12670 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
12671    [temp.dep.expr].  */
12672
12673 bool
12674 type_dependent_expression_p (tree expression)
12675 {
12676   if (!processing_template_decl)
12677     return false;
12678
12679   if (expression == error_mark_node)
12680     return false;
12681
12682   /* An unresolved name is always dependent.  */
12683   if (TREE_CODE (expression) == IDENTIFIER_NODE
12684       || TREE_CODE (expression) == USING_DECL)
12685     return true;
12686
12687   /* Some expression forms are never type-dependent.  */
12688   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
12689       || TREE_CODE (expression) == SIZEOF_EXPR
12690       || TREE_CODE (expression) == ALIGNOF_EXPR
12691       || TREE_CODE (expression) == TYPEID_EXPR
12692       || TREE_CODE (expression) == DELETE_EXPR
12693       || TREE_CODE (expression) == VEC_DELETE_EXPR
12694       || TREE_CODE (expression) == THROW_EXPR)
12695     return false;
12696
12697   /* The types of these expressions depends only on the type to which
12698      the cast occurs.  */
12699   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
12700       || TREE_CODE (expression) == STATIC_CAST_EXPR
12701       || TREE_CODE (expression) == CONST_CAST_EXPR
12702       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
12703       || TREE_CODE (expression) == CAST_EXPR)
12704     return dependent_type_p (TREE_TYPE (expression));
12705
12706   /* The types of these expressions depends only on the type created
12707      by the expression.  */
12708   if (TREE_CODE (expression) == NEW_EXPR
12709       || TREE_CODE (expression) == VEC_NEW_EXPR)
12710     {
12711       /* For NEW_EXPR tree nodes created inside a template, either
12712          the object type itself or a TREE_LIST may appear as the
12713          operand 1.  */
12714       tree type = TREE_OPERAND (expression, 1);
12715       if (TREE_CODE (type) == TREE_LIST)
12716         /* This is an array type.  We need to check array dimensions
12717            as well.  */
12718         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
12719                || value_dependent_expression_p
12720                     (TREE_OPERAND (TREE_VALUE (type), 1));
12721       else
12722         return dependent_type_p (type);
12723     }
12724
12725   if (TREE_CODE (expression) == SCOPE_REF
12726       && dependent_scope_ref_p (expression,
12727                                 type_dependent_expression_p))
12728     return true;
12729
12730   if (TREE_CODE (expression) == FUNCTION_DECL
12731       && DECL_LANG_SPECIFIC (expression)
12732       && DECL_TEMPLATE_INFO (expression)
12733       && (any_dependent_template_arguments_p
12734           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
12735     return true;
12736
12737   if (TREE_CODE (expression) == TEMPLATE_DECL
12738       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
12739     return false;
12740
12741   if (TREE_TYPE (expression) == unknown_type_node)
12742     {
12743       if (TREE_CODE (expression) == ADDR_EXPR)
12744         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
12745       if (TREE_CODE (expression) == COMPONENT_REF
12746           || TREE_CODE (expression) == OFFSET_REF)
12747         {
12748           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
12749             return true;
12750           expression = TREE_OPERAND (expression, 1);
12751           if (TREE_CODE (expression) == IDENTIFIER_NODE)
12752             return false;
12753         }
12754       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
12755       if (TREE_CODE (expression) == SCOPE_REF)
12756         return false;
12757
12758       if (TREE_CODE (expression) == BASELINK)
12759         expression = BASELINK_FUNCTIONS (expression);
12760
12761       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
12762         {
12763           if (any_dependent_template_arguments_p
12764               (TREE_OPERAND (expression, 1)))
12765             return true;
12766           expression = TREE_OPERAND (expression, 0);
12767         }
12768       gcc_assert (TREE_CODE (expression) == OVERLOAD
12769                   || TREE_CODE (expression) == FUNCTION_DECL);
12770
12771       while (expression)
12772         {
12773           if (type_dependent_expression_p (OVL_CURRENT (expression)))
12774             return true;
12775           expression = OVL_NEXT (expression);
12776         }
12777       return false;
12778     }
12779
12780   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
12781   
12782   return (dependent_type_p (TREE_TYPE (expression)));
12783 }
12784
12785 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
12786    contains a type-dependent expression.  */
12787
12788 bool
12789 any_type_dependent_arguments_p (tree args)
12790 {
12791   while (args)
12792     {
12793       tree arg = TREE_VALUE (args);
12794
12795       if (type_dependent_expression_p (arg))
12796         return true;
12797       args = TREE_CHAIN (args);
12798     }
12799   return false;
12800 }
12801
12802 /* Returns TRUE if the ARG (a template argument) is dependent.  */
12803
12804 static bool
12805 dependent_template_arg_p (tree arg)
12806 {
12807   if (!processing_template_decl)
12808     return false;
12809
12810   if (TREE_CODE (arg) == TEMPLATE_DECL
12811       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
12812     return dependent_template_p (arg);
12813   else if (TYPE_P (arg))
12814     return dependent_type_p (arg);
12815   else
12816     return (type_dependent_expression_p (arg)
12817             || value_dependent_expression_p (arg));
12818 }
12819
12820 /* Returns true if ARGS (a collection of template arguments) contains
12821    any dependent arguments.  */
12822
12823 bool
12824 any_dependent_template_arguments_p (tree args)
12825 {
12826   int i;
12827   int j;
12828
12829   if (!args)
12830     return false;
12831   if (args == error_mark_node)
12832     return true;
12833
12834   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
12835     {
12836       tree level = TMPL_ARGS_LEVEL (args, i + 1);
12837       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
12838         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
12839           return true;
12840     }
12841
12842   return false;
12843 }
12844
12845 /* Returns TRUE if the template TMPL is dependent.  */
12846
12847 bool
12848 dependent_template_p (tree tmpl)
12849 {
12850   if (TREE_CODE (tmpl) == OVERLOAD)
12851     {
12852       while (tmpl)
12853         {
12854           if (dependent_template_p (OVL_FUNCTION (tmpl)))
12855             return true;
12856           tmpl = OVL_CHAIN (tmpl);
12857         }
12858       return false;
12859     }
12860
12861   /* Template template parameters are dependent.  */
12862   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
12863       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
12864     return true;
12865   /* So are names that have not been looked up.  */
12866   if (TREE_CODE (tmpl) == SCOPE_REF
12867       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
12868     return true;
12869   /* So are member templates of dependent classes.  */
12870   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
12871     return dependent_type_p (DECL_CONTEXT (tmpl));
12872   return false;
12873 }
12874
12875 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
12876
12877 bool
12878 dependent_template_id_p (tree tmpl, tree args)
12879 {
12880   return (dependent_template_p (tmpl)
12881           || any_dependent_template_arguments_p (args));
12882 }
12883
12884 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
12885    TYPENAME_TYPE corresponds.  Returns ERROR_MARK_NODE if no such TYPE
12886    can be found.  Note that this function peers inside uninstantiated
12887    templates and therefore should be used only in extremely limited
12888    situations.  ONLY_CURRENT_P restricts this peering to the currently
12889    open classes hierarchy (which is required when comparing types).  */
12890
12891 tree
12892 resolve_typename_type (tree type, bool only_current_p)
12893 {
12894   tree scope;
12895   tree name;
12896   tree decl;
12897   int quals;
12898   tree pushed_scope;
12899
12900   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
12901
12902   scope = TYPE_CONTEXT (type);
12903   name = TYPE_IDENTIFIER (type);
12904
12905   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
12906      it first before we can figure out what NAME refers to.  */
12907   if (TREE_CODE (scope) == TYPENAME_TYPE)
12908     scope = resolve_typename_type (scope, only_current_p);
12909   /* If we don't know what SCOPE refers to, then we cannot resolve the
12910      TYPENAME_TYPE.  */
12911   if (scope == error_mark_node || TREE_CODE (scope) == TYPENAME_TYPE)
12912     return error_mark_node;
12913   /* If the SCOPE is a template type parameter, we have no way of
12914      resolving the name.  */
12915   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
12916     return type;
12917   /* If the SCOPE is not the current instantiation, there's no reason
12918      to look inside it.  */
12919   if (only_current_p && !currently_open_class (scope))
12920     return error_mark_node;
12921   /* If SCOPE is a partial instantiation, it will not have a valid
12922      TYPE_FIELDS list, so use the original template.  */
12923   scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
12924   /* Enter the SCOPE so that name lookup will be resolved as if we
12925      were in the class definition.  In particular, SCOPE will no
12926      longer be considered a dependent type.  */
12927   pushed_scope = push_scope (scope);
12928   /* Look up the declaration.  */
12929   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
12930   /* Obtain the set of qualifiers applied to the TYPE.  */
12931   quals = cp_type_quals (type);
12932   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
12933      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
12934   if (!decl)
12935     type = error_mark_node;
12936   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
12937            && TREE_CODE (decl) == TYPE_DECL)
12938     type = TREE_TYPE (decl);
12939   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
12940            && DECL_CLASS_TEMPLATE_P (decl))
12941     {
12942       tree tmpl;
12943       tree args;
12944       /* Obtain the template and the arguments.  */
12945       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
12946       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
12947       /* Instantiate the template.  */
12948       type = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
12949                                     /*entering_scope=*/0, tf_error | tf_user);
12950     }
12951   else
12952     type = error_mark_node;
12953   /* Qualify the resulting type.  */
12954   if (type != error_mark_node && quals)
12955     type = cp_build_qualified_type (type, quals);
12956   /* Leave the SCOPE.  */
12957   if (pushed_scope)
12958     pop_scope (pushed_scope);
12959
12960   return type;
12961 }
12962
12963 /* EXPR is an expression which is not type-dependent.  Return a proxy
12964    for EXPR that can be used to compute the types of larger
12965    expressions containing EXPR.  */
12966
12967 tree
12968 build_non_dependent_expr (tree expr)
12969 {
12970   tree inner_expr;
12971
12972   /* Preserve null pointer constants so that the type of things like
12973      "p == 0" where "p" is a pointer can be determined.  */
12974   if (null_ptr_cst_p (expr))
12975     return expr;
12976   /* Preserve OVERLOADs; the functions must be available to resolve
12977      types.  */
12978   inner_expr = (TREE_CODE (expr) == ADDR_EXPR ?
12979                 TREE_OPERAND (expr, 0) :
12980                 TREE_CODE (expr) == COMPONENT_REF ?
12981                 TREE_OPERAND (expr, 1) : expr);
12982   if (is_overloaded_fn (inner_expr)
12983       || TREE_CODE (inner_expr) == OFFSET_REF)
12984     return expr;
12985   /* There is no need to return a proxy for a variable.  */
12986   if (TREE_CODE (expr) == VAR_DECL)
12987     return expr;
12988   /* Preserve string constants; conversions from string constants to
12989      "char *" are allowed, even though normally a "const char *"
12990      cannot be used to initialize a "char *".  */
12991   if (TREE_CODE (expr) == STRING_CST)
12992     return expr;
12993   /* Preserve arithmetic constants, as an optimization -- there is no
12994      reason to create a new node.  */
12995   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
12996     return expr;
12997   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
12998      There is at least one place where we want to know that a
12999      particular expression is a throw-expression: when checking a ?:
13000      expression, there are special rules if the second or third
13001      argument is a throw-expression.  */
13002   if (TREE_CODE (expr) == THROW_EXPR)
13003     return expr;
13004
13005   if (TREE_CODE (expr) == COND_EXPR)
13006     return build3 (COND_EXPR,
13007                    TREE_TYPE (expr),
13008                    TREE_OPERAND (expr, 0),
13009                    (TREE_OPERAND (expr, 1)
13010                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
13011                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
13012                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
13013   if (TREE_CODE (expr) == COMPOUND_EXPR
13014       && !COMPOUND_EXPR_OVERLOADED (expr))
13015     return build2 (COMPOUND_EXPR,
13016                    TREE_TYPE (expr),
13017                    TREE_OPERAND (expr, 0),
13018                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
13019
13020   /* If the type is unknown, it can't really be non-dependent */
13021   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
13022   
13023   /* Otherwise, build a NON_DEPENDENT_EXPR.
13024
13025      REFERENCE_TYPEs are not stripped for expressions in templates
13026      because doing so would play havoc with mangling.  Consider, for
13027      example:
13028
13029        template <typename T> void f<T& g>() { g(); }
13030
13031      In the body of "f", the expression for "g" will have
13032      REFERENCE_TYPE, even though the standard says that it should
13033      not.  The reason is that we must preserve the syntactic form of
13034      the expression so that mangling (say) "f<g>" inside the body of
13035      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
13036      stripped here.  */
13037   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
13038 }
13039
13040 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
13041    Return a new TREE_LIST with the various arguments replaced with
13042    equivalent non-dependent expressions.  */
13043
13044 tree
13045 build_non_dependent_args (tree args)
13046 {
13047   tree a;
13048   tree new_args;
13049
13050   new_args = NULL_TREE;
13051   for (a = args; a; a = TREE_CHAIN (a))
13052     new_args = tree_cons (NULL_TREE,
13053                           build_non_dependent_expr (TREE_VALUE (a)),
13054                           new_args);
13055   return nreverse (new_args);
13056 }
13057
13058 #include "gt-cp-pt.h"