OSDN Git Service

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