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