OSDN Git Service

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