OSDN Git Service

/cp
[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, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct GTY (()) pending_template {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 typedef struct GTY(()) spec_entry
86 {
87   tree tmpl;
88   tree args;
89   tree spec;
90 } spec_entry;
91
92 static GTY ((param_is (spec_entry)))
93   htab_t decl_specializations;
94
95 static GTY ((param_is (spec_entry)))
96   htab_t type_specializations;
97
98 /* Contains canonical template parameter types. The vector is indexed by
99    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
100    TREE_LIST, whose TREE_VALUEs contain the canonical template
101    parameters of various types and levels.  */
102 static GTY(()) VEC(tree,gc) *canonical_template_parms;
103
104 #define UNIFY_ALLOW_NONE 0
105 #define UNIFY_ALLOW_MORE_CV_QUAL 1
106 #define UNIFY_ALLOW_LESS_CV_QUAL 2
107 #define UNIFY_ALLOW_DERIVED 4
108 #define UNIFY_ALLOW_INTEGER 8
109 #define UNIFY_ALLOW_OUTER_LEVEL 16
110 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
111 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
112
113 static void push_access_scope (tree);
114 static void pop_access_scope (tree);
115 static bool resolve_overloaded_unification (tree, tree, tree, tree,
116                                             unification_kind_t, int);
117 static int try_one_overload (tree, tree, tree, tree, tree,
118                              unification_kind_t, int, bool);
119 static int unify (tree, tree, tree, tree, int);
120 static void add_pending_template (tree);
121 static int push_tinst_level (tree);
122 static void pop_tinst_level (void);
123 static tree reopen_tinst_level (struct tinst_level *);
124 static tree tsubst_initializer_list (tree, tree);
125 static tree get_class_bindings (tree, tree, tree);
126 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
127                                    bool, bool);
128 static void tsubst_enum (tree, tree, tree);
129 static tree add_to_template_args (tree, tree);
130 static tree add_outermost_template_args (tree, tree);
131 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
132 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
133                                              tree);
134 static int type_unification_real (tree, tree, tree, const tree *,
135                                   unsigned int, int, unification_kind_t, int);
136 static void note_template_header (int);
137 static tree convert_nontype_argument_function (tree, tree);
138 static tree convert_nontype_argument (tree, tree);
139 static tree convert_template_argument (tree, tree, tree,
140                                        tsubst_flags_t, int, tree);
141 static int for_each_template_parm (tree, tree_fn_t, void*,
142                                    struct pointer_set_t*, bool);
143 static tree expand_template_argument_pack (tree);
144 static tree build_template_parm_index (int, int, int, tree, tree);
145 static bool inline_needs_template_parms (tree);
146 static void push_inline_template_parms_recursive (tree, int);
147 static tree retrieve_local_specialization (tree);
148 static void register_local_specialization (tree, tree);
149 static hashval_t hash_specialization (const void *p);
150 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
151 static int mark_template_parm (tree, void *);
152 static int template_parm_this_level_p (tree, void *);
153 static tree tsubst_friend_function (tree, tree);
154 static tree tsubst_friend_class (tree, tree);
155 static int can_complete_type_without_circularity (tree);
156 static tree get_bindings (tree, tree, tree, bool);
157 static int template_decl_level (tree);
158 static int check_cv_quals_for_unify (int, tree, tree);
159 static void template_parm_level_and_index (tree, int*, int*);
160 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
161 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
164 static void regenerate_decl_from_template (tree, tree);
165 static tree most_specialized_class (tree, tree);
166 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
167 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
168 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
169 static bool check_specialization_scope (void);
170 static tree process_partial_specialization (tree);
171 static void set_current_access_from_decl (tree);
172 static tree get_template_base (tree, tree, tree, tree);
173 static tree try_class_unification (tree, tree, tree, tree);
174 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
175                                            tree, tree);
176 static bool template_template_parm_bindings_ok_p (tree, tree);
177 static int template_args_equal (tree, tree);
178 static void tsubst_default_arguments (tree);
179 static tree for_each_template_parm_r (tree *, int *, void *);
180 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
181 static void copy_default_args_to_explicit_spec (tree);
182 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
183 static int eq_local_specializations (const void *, const void *);
184 static bool dependent_template_arg_p (tree);
185 static bool any_template_arguments_need_structural_equality_p (tree);
186 static bool dependent_type_p_r (tree);
187 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
188 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_decl (tree, tree, tsubst_flags_t);
191 static void perform_typedefs_access_check (tree tmpl, tree targs);
192 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
193                                                         location_t);
194 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
195 static tree listify (tree);
196 static tree listify_autos (tree, tree);
197
198 /* Make the current scope suitable for access checking when we are
199    processing T.  T can be FUNCTION_DECL for instantiated function
200    template, or VAR_DECL for static member variable (need by
201    instantiate_decl).  */
202
203 static void
204 push_access_scope (tree t)
205 {
206   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
207               || TREE_CODE (t) == VAR_DECL);
208
209   if (DECL_FRIEND_CONTEXT (t))
210     push_nested_class (DECL_FRIEND_CONTEXT (t));
211   else if (DECL_CLASS_SCOPE_P (t))
212     push_nested_class (DECL_CONTEXT (t));
213   else
214     push_to_top_level ();
215
216   if (TREE_CODE (t) == FUNCTION_DECL)
217     {
218       saved_access_scope = tree_cons
219         (NULL_TREE, current_function_decl, saved_access_scope);
220       current_function_decl = t;
221     }
222 }
223
224 /* Restore the scope set up by push_access_scope.  T is the node we
225    are processing.  */
226
227 static void
228 pop_access_scope (tree t)
229 {
230   if (TREE_CODE (t) == FUNCTION_DECL)
231     {
232       current_function_decl = TREE_VALUE (saved_access_scope);
233       saved_access_scope = TREE_CHAIN (saved_access_scope);
234     }
235
236   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
237     pop_nested_class ();
238   else
239     pop_from_top_level ();
240 }
241
242 /* Do any processing required when DECL (a member template
243    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
244    to DECL, unless it is a specialization, in which case the DECL
245    itself is returned.  */
246
247 tree
248 finish_member_template_decl (tree decl)
249 {
250   if (decl == error_mark_node)
251     return error_mark_node;
252
253   gcc_assert (DECL_P (decl));
254
255   if (TREE_CODE (decl) == TYPE_DECL)
256     {
257       tree type;
258
259       type = TREE_TYPE (decl);
260       if (type == error_mark_node)
261         return error_mark_node;
262       if (MAYBE_CLASS_TYPE_P (type)
263           && CLASSTYPE_TEMPLATE_INFO (type)
264           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
265         {
266           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
267           check_member_template (tmpl);
268           return tmpl;
269         }
270       return NULL_TREE;
271     }
272   else if (TREE_CODE (decl) == FIELD_DECL)
273     error ("data member %qD cannot be a member template", decl);
274   else if (DECL_TEMPLATE_INFO (decl))
275     {
276       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
277         {
278           check_member_template (DECL_TI_TEMPLATE (decl));
279           return DECL_TI_TEMPLATE (decl);
280         }
281       else
282         return decl;
283     }
284   else
285     error ("invalid member template declaration %qD", decl);
286
287   return error_mark_node;
288 }
289
290 /* Create a template info node.  */
291
292 tree
293 build_template_info (tree template_decl, tree template_args)
294 {
295   tree result = make_node (TEMPLATE_INFO);
296   TI_TEMPLATE (result) = template_decl;
297   TI_ARGS (result) = template_args;
298   return result;
299 }
300
301 /* Return the template info node corresponding to T, whatever T is.  */
302
303 tree
304 get_template_info (const_tree t)
305 {
306   tree tinfo = NULL_TREE;
307
308   if (!t || t == error_mark_node)
309     return NULL;
310
311   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
312     tinfo = DECL_TEMPLATE_INFO (t);
313
314   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
315     t = TREE_TYPE (t);
316
317   if (TAGGED_TYPE_P (t))
318     tinfo = TYPE_TEMPLATE_INFO (t);
319
320   return tinfo;
321 }
322
323 /* Returns the template nesting level of the indicated class TYPE.
324
325    For example, in:
326      template <class T>
327      struct A
328      {
329        template <class U>
330        struct B {};
331      };
332
333    A<T>::B<U> has depth two, while A<T> has depth one.
334    Both A<T>::B<int> and A<int>::B<U> have depth one, if
335    they are instantiations, not specializations.
336
337    This function is guaranteed to return 0 if passed NULL_TREE so
338    that, for example, `template_class_depth (current_class_type)' is
339    always safe.  */
340
341 int
342 template_class_depth (tree type)
343 {
344   int depth;
345
346   for (depth = 0;
347        type && TREE_CODE (type) != NAMESPACE_DECL;
348        type = (TREE_CODE (type) == FUNCTION_DECL)
349          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
350     {
351       tree tinfo = get_template_info (type);
352
353       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
354           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
355         ++depth;
356     }
357
358   return depth;
359 }
360
361 /* Subroutine of maybe_begin_member_template_processing.
362    Returns true if processing DECL needs us to push template parms.  */
363
364 static bool
365 inline_needs_template_parms (tree decl)
366 {
367   if (! DECL_TEMPLATE_INFO (decl))
368     return false;
369
370   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
371           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
372 }
373
374 /* Subroutine of maybe_begin_member_template_processing.
375    Push the template parms in PARMS, starting from LEVELS steps into the
376    chain, and ending at the beginning, since template parms are listed
377    innermost first.  */
378
379 static void
380 push_inline_template_parms_recursive (tree parmlist, int levels)
381 {
382   tree parms = TREE_VALUE (parmlist);
383   int i;
384
385   if (levels > 1)
386     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
387
388   ++processing_template_decl;
389   current_template_parms
390     = tree_cons (size_int (processing_template_decl),
391                  parms, current_template_parms);
392   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
393
394   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
395                NULL);
396   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
397     {
398       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
399
400       if (parm == error_mark_node)
401         continue;
402
403       gcc_assert (DECL_P (parm));
404
405       switch (TREE_CODE (parm))
406         {
407         case TYPE_DECL:
408         case TEMPLATE_DECL:
409           pushdecl (parm);
410           break;
411
412         case PARM_DECL:
413           {
414             /* Make a CONST_DECL as is done in process_template_parm.
415                It is ugly that we recreate this here; the original
416                version built in process_template_parm is no longer
417                available.  */
418             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
419                                     CONST_DECL, DECL_NAME (parm),
420                                     TREE_TYPE (parm));
421             DECL_ARTIFICIAL (decl) = 1;
422             TREE_CONSTANT (decl) = 1;
423             TREE_READONLY (decl) = 1;
424             DECL_INITIAL (decl) = DECL_INITIAL (parm);
425             SET_DECL_TEMPLATE_PARM_P (decl);
426             pushdecl (decl);
427           }
428           break;
429
430         default:
431           gcc_unreachable ();
432         }
433     }
434 }
435
436 /* Restore the template parameter context for a member template or
437    a friend template defined in a class definition.  */
438
439 void
440 maybe_begin_member_template_processing (tree decl)
441 {
442   tree parms;
443   int levels = 0;
444
445   if (inline_needs_template_parms (decl))
446     {
447       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
448       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
449
450       if (DECL_TEMPLATE_SPECIALIZATION (decl))
451         {
452           --levels;
453           parms = TREE_CHAIN (parms);
454         }
455
456       push_inline_template_parms_recursive (parms, levels);
457     }
458
459   /* Remember how many levels of template parameters we pushed so that
460      we can pop them later.  */
461   VEC_safe_push (int, heap, inline_parm_levels, levels);
462 }
463
464 /* Undo the effects of maybe_begin_member_template_processing.  */
465
466 void
467 maybe_end_member_template_processing (void)
468 {
469   int i;
470   int last;
471
472   if (VEC_length (int, inline_parm_levels) == 0)
473     return;
474
475   last = VEC_pop (int, inline_parm_levels);
476   for (i = 0; i < last; ++i)
477     {
478       --processing_template_decl;
479       current_template_parms = TREE_CHAIN (current_template_parms);
480       poplevel (0, 0, 0);
481     }
482 }
483
484 /* Return a new template argument vector which contains all of ARGS,
485    but has as its innermost set of arguments the EXTRA_ARGS.  */
486
487 static tree
488 add_to_template_args (tree args, tree extra_args)
489 {
490   tree new_args;
491   int extra_depth;
492   int i;
493   int j;
494
495   extra_depth = TMPL_ARGS_DEPTH (extra_args);
496   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
497
498   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
499     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
500
501   for (j = 1; j <= extra_depth; ++j, ++i)
502     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
503
504   return new_args;
505 }
506
507 /* Like add_to_template_args, but only the outermost ARGS are added to
508    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
509    (EXTRA_ARGS) levels are added.  This function is used to combine
510    the template arguments from a partial instantiation with the
511    template arguments used to attain the full instantiation from the
512    partial instantiation.  */
513
514 static tree
515 add_outermost_template_args (tree args, tree extra_args)
516 {
517   tree new_args;
518
519   /* If there are more levels of EXTRA_ARGS than there are ARGS,
520      something very fishy is going on.  */
521   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
522
523   /* If *all* the new arguments will be the EXTRA_ARGS, just return
524      them.  */
525   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
526     return extra_args;
527
528   /* For the moment, we make ARGS look like it contains fewer levels.  */
529   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
530
531   new_args = add_to_template_args (args, extra_args);
532
533   /* Now, we restore ARGS to its full dimensions.  */
534   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
535
536   return new_args;
537 }
538
539 /* Return the N levels of innermost template arguments from the ARGS.  */
540
541 tree
542 get_innermost_template_args (tree args, int n)
543 {
544   tree new_args;
545   int extra_levels;
546   int i;
547
548   gcc_assert (n >= 0);
549
550   /* If N is 1, just return the innermost set of template arguments.  */
551   if (n == 1)
552     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
553
554   /* If we're not removing anything, just return the arguments we were
555      given.  */
556   extra_levels = TMPL_ARGS_DEPTH (args) - n;
557   gcc_assert (extra_levels >= 0);
558   if (extra_levels == 0)
559     return args;
560
561   /* Make a new set of arguments, not containing the outer arguments.  */
562   new_args = make_tree_vec (n);
563   for (i = 1; i <= n; ++i)
564     SET_TMPL_ARGS_LEVEL (new_args, i,
565                          TMPL_ARGS_LEVEL (args, i + extra_levels));
566
567   return new_args;
568 }
569
570 /* The inverse of get_innermost_template_args: Return all but the innermost
571    EXTRA_LEVELS levels of template arguments from the ARGS.  */
572
573 static tree
574 strip_innermost_template_args (tree args, int extra_levels)
575 {
576   tree new_args;
577   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
578   int i;
579
580   gcc_assert (n >= 0);
581
582   /* If N is 1, just return the outermost set of template arguments.  */
583   if (n == 1)
584     return TMPL_ARGS_LEVEL (args, 1);
585
586   /* If we're not removing anything, just return the arguments we were
587      given.  */
588   gcc_assert (extra_levels >= 0);
589   if (extra_levels == 0)
590     return args;
591
592   /* Make a new set of arguments, not containing the inner arguments.  */
593   new_args = make_tree_vec (n);
594   for (i = 1; i <= n; ++i)
595     SET_TMPL_ARGS_LEVEL (new_args, i,
596                          TMPL_ARGS_LEVEL (args, i));
597
598   return new_args;
599 }
600
601 /* We've got a template header coming up; push to a new level for storing
602    the parms.  */
603
604 void
605 begin_template_parm_list (void)
606 {
607   /* We use a non-tag-transparent scope here, which causes pushtag to
608      put tags in this scope, rather than in the enclosing class or
609      namespace scope.  This is the right thing, since we want
610      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
611      global template class, push_template_decl handles putting the
612      TEMPLATE_DECL into top-level scope.  For a nested template class,
613      e.g.:
614
615        template <class T> struct S1 {
616          template <class T> struct S2 {};
617        };
618
619      pushtag contains special code to call pushdecl_with_scope on the
620      TEMPLATE_DECL for S2.  */
621   begin_scope (sk_template_parms, NULL);
622   ++processing_template_decl;
623   ++processing_template_parmlist;
624   note_template_header (0);
625 }
626
627 /* This routine is called when a specialization is declared.  If it is
628    invalid to declare a specialization here, an error is reported and
629    false is returned, otherwise this routine will return true.  */
630
631 static bool
632 check_specialization_scope (void)
633 {
634   tree scope = current_scope ();
635
636   /* [temp.expl.spec]
637
638      An explicit specialization shall be declared in the namespace of
639      which the template is a member, or, for member templates, in the
640      namespace of which the enclosing class or enclosing class
641      template is a member.  An explicit specialization of a member
642      function, member class or static data member of a class template
643      shall be declared in the namespace of which the class template
644      is a member.  */
645   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
646     {
647       error ("explicit specialization in non-namespace scope %qD", scope);
648       return false;
649     }
650
651   /* [temp.expl.spec]
652
653      In an explicit specialization declaration for a member of a class
654      template or a member template that appears in namespace scope,
655      the member template and some of its enclosing class templates may
656      remain unspecialized, except that the declaration shall not
657      explicitly specialize a class member template if its enclosing
658      class templates are not explicitly specialized as well.  */
659   if (current_template_parms)
660     {
661       error ("enclosing class templates are not explicitly specialized");
662       return false;
663     }
664
665   return true;
666 }
667
668 /* We've just seen template <>.  */
669
670 bool
671 begin_specialization (void)
672 {
673   begin_scope (sk_template_spec, NULL);
674   note_template_header (1);
675   return check_specialization_scope ();
676 }
677
678 /* Called at then end of processing a declaration preceded by
679    template<>.  */
680
681 void
682 end_specialization (void)
683 {
684   finish_scope ();
685   reset_specialization ();
686 }
687
688 /* Any template <>'s that we have seen thus far are not referring to a
689    function specialization.  */
690
691 void
692 reset_specialization (void)
693 {
694   processing_specialization = 0;
695   template_header_count = 0;
696 }
697
698 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
699    it was of the form template <>.  */
700
701 static void
702 note_template_header (int specialization)
703 {
704   processing_specialization = specialization;
705   template_header_count++;
706 }
707
708 /* We're beginning an explicit instantiation.  */
709
710 void
711 begin_explicit_instantiation (void)
712 {
713   gcc_assert (!processing_explicit_instantiation);
714   processing_explicit_instantiation = true;
715 }
716
717
718 void
719 end_explicit_instantiation (void)
720 {
721   gcc_assert (processing_explicit_instantiation);
722   processing_explicit_instantiation = false;
723 }
724
725 /* An explicit specialization or partial specialization TMPL is being
726    declared.  Check that the namespace in which the specialization is
727    occurring is permissible.  Returns false iff it is invalid to
728    specialize TMPL in the current namespace.  */
729
730 static bool
731 check_specialization_namespace (tree tmpl)
732 {
733   tree tpl_ns = decl_namespace_context (tmpl);
734
735   /* [tmpl.expl.spec]
736
737      An explicit specialization shall be declared in the namespace of
738      which the template is a member, or, for member templates, in the
739      namespace of which the enclosing class or enclosing class
740      template is a member.  An explicit specialization of a member
741      function, member class or static data member of a class template
742      shall be declared in the namespace of which the class template is
743      a member.  */
744   if (is_associated_namespace (current_namespace, tpl_ns))
745     /* Same or super-using namespace.  */
746     return true;
747   else
748     {
749       permerror (input_location, "specialization of %qD in different namespace", tmpl);
750       permerror (input_location, "  from definition of %q+#D", tmpl);
751       return false;
752     }
753 }
754
755 /* SPEC is an explicit instantiation.  Check that it is valid to
756    perform this explicit instantiation in the current namespace.  */
757
758 static void
759 check_explicit_instantiation_namespace (tree spec)
760 {
761   tree ns;
762
763   /* DR 275: An explicit instantiation shall appear in an enclosing
764      namespace of its template.  */
765   ns = decl_namespace_context (spec);
766   if (!is_ancestor (current_namespace, ns))
767     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
768                "(which does not enclose namespace %qD)",
769                spec, current_namespace, ns);
770 }
771
772 /* The TYPE is being declared.  If it is a template type, that means it
773    is a partial specialization.  Do appropriate error-checking.  */
774
775 tree
776 maybe_process_partial_specialization (tree type)
777 {
778   tree context;
779
780   if (type == error_mark_node)
781     return error_mark_node;
782
783   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
784     {
785       error ("name of class shadows template template parameter %qD",
786              TYPE_NAME (type));
787       return error_mark_node;
788     }
789
790   context = TYPE_CONTEXT (type);
791
792   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
793     {
794       /* This is for ordinary explicit specialization and partial
795          specialization of a template class such as:
796
797            template <> class C<int>;
798
799          or:
800
801            template <class T> class C<T*>;
802
803          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
804
805       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
806           && !COMPLETE_TYPE_P (type))
807         {
808           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
809           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
810           if (processing_template_decl)
811             {
812               if (push_template_decl (TYPE_MAIN_DECL (type))
813                   == error_mark_node)
814                 return error_mark_node;
815             }
816         }
817       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
818         error ("specialization of %qT after instantiation", type);
819     }
820   else if (CLASS_TYPE_P (type)
821            && !CLASSTYPE_USE_TEMPLATE (type)
822            && CLASSTYPE_TEMPLATE_INFO (type)
823            && context && CLASS_TYPE_P (context)
824            && CLASSTYPE_TEMPLATE_INFO (context))
825     {
826       /* This is for an explicit specialization of member class
827          template according to [temp.expl.spec/18]:
828
829            template <> template <class U> class C<int>::D;
830
831          The context `C<int>' must be an implicit instantiation.
832          Otherwise this is just a member class template declared
833          earlier like:
834
835            template <> class C<int> { template <class U> class D; };
836            template <> template <class U> class C<int>::D;
837
838          In the first case, `C<int>::D' is a specialization of `C<T>::D'
839          while in the second case, `C<int>::D' is a primary template
840          and `C<T>::D' may not exist.  */
841
842       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
843           && !COMPLETE_TYPE_P (type))
844         {
845           tree t;
846           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
847
848           if (current_namespace
849               != decl_namespace_context (tmpl))
850             {
851               permerror (input_location, "specializing %q#T in different namespace", type);
852               permerror (input_location, "  from definition of %q+#D", tmpl);
853             }
854
855           /* Check for invalid specialization after instantiation:
856
857                template <> template <> class C<int>::D<int>;
858                template <> template <class U> class C<int>::D;  */
859
860           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
861                t; t = TREE_CHAIN (t))
862             {
863               tree inst = TREE_VALUE (t);
864               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
865                 {
866                   /* We already have a full specialization of this partial
867                      instantiation.  Reassign it to the new member
868                      specialization template.  */
869                   spec_entry elt;
870                   spec_entry **slot;
871
872                   elt.tmpl = most_general_template (tmpl);
873                   elt.args = CLASSTYPE_TI_ARGS (inst);
874                   elt.spec = inst;
875
876                   htab_remove_elt (type_specializations, &elt);
877
878                   elt.tmpl = tmpl;
879                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
880
881                   slot = (spec_entry **)
882                     htab_find_slot (type_specializations, &elt, INSERT);
883                   *slot = GGC_NEW (spec_entry);
884                   **slot = elt;
885                 }
886               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
887                 /* But if we've had an implicit instantiation, that's a
888                    problem ([temp.expl.spec]/6).  */
889                 error ("specialization %qT after instantiation %qT",
890                        type, inst);
891             }
892
893           /* Mark TYPE as a specialization.  And as a result, we only
894              have one level of template argument for the innermost
895              class template.  */
896           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
897           CLASSTYPE_TI_ARGS (type)
898             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
899         }
900     }
901   else if (processing_specialization)
902     {
903       error ("explicit specialization of non-template %qT", type);
904       return error_mark_node;
905     }
906
907   return type;
908 }
909
910 /* Returns nonzero if we can optimize the retrieval of specializations
911    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
912    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
913
914 static inline bool
915 optimize_specialization_lookup_p (tree tmpl)
916 {
917   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
918           && DECL_CLASS_SCOPE_P (tmpl)
919           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
920              parameter.  */
921           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
922           /* The optimized lookup depends on the fact that the
923              template arguments for the member function template apply
924              purely to the containing class, which is not true if the
925              containing class is an explicit or partial
926              specialization.  */
927           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
928           && !DECL_MEMBER_TEMPLATE_P (tmpl)
929           && !DECL_CONV_FN_P (tmpl)
930           /* It is possible to have a template that is not a member
931              template and is not a member of a template class:
932
933              template <typename T>
934              struct S { friend A::f(); };
935
936              Here, the friend function is a template, but the context does
937              not have template information.  The optimized lookup relies
938              on having ARGS be the template arguments for both the class
939              and the function template.  */
940           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
941 }
942
943 /* Retrieve the specialization (in the sense of [temp.spec] - a
944    specialization is either an instantiation or an explicit
945    specialization) of TMPL for the given template ARGS.  If there is
946    no such specialization, return NULL_TREE.  The ARGS are a vector of
947    arguments, or a vector of vectors of arguments, in the case of
948    templates with more than one level of parameters.
949
950    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
951    then we search for a partial specialization matching ARGS.  This
952    parameter is ignored if TMPL is not a class template.  */
953
954 static tree
955 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
956 {
957   if (args == error_mark_node)
958     return NULL_TREE;
959
960   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
961
962   /* There should be as many levels of arguments as there are
963      levels of parameters.  */
964   gcc_assert (TMPL_ARGS_DEPTH (args)
965               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
966
967   if (optimize_specialization_lookup_p (tmpl))
968     {
969       tree class_template;
970       tree class_specialization;
971       VEC(tree,gc) *methods;
972       tree fns;
973       int idx;
974
975       /* The template arguments actually apply to the containing
976          class.  Find the class specialization with those
977          arguments.  */
978       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
979       class_specialization
980         = retrieve_specialization (class_template, args, 0);
981       if (!class_specialization)
982         return NULL_TREE;
983       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
984          for the specialization.  */
985       idx = class_method_index_for_fn (class_specialization, tmpl);
986       if (idx == -1)
987         return NULL_TREE;
988       /* Iterate through the methods with the indicated name, looking
989          for the one that has an instance of TMPL.  */
990       methods = CLASSTYPE_METHOD_VEC (class_specialization);
991       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
992         {
993           tree fn = OVL_CURRENT (fns);
994           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
995               /* using-declarations can add base methods to the method vec,
996                  and we don't want those here.  */
997               && DECL_CONTEXT (fn) == class_specialization)
998             return fn;
999         }
1000       return NULL_TREE;
1001     }
1002   else
1003     {
1004       spec_entry *found;
1005       spec_entry elt;
1006       htab_t specializations;
1007
1008       elt.tmpl = tmpl;
1009       elt.args = args;
1010       elt.spec = NULL_TREE;
1011
1012       if (DECL_CLASS_TEMPLATE_P (tmpl))
1013         specializations = type_specializations;
1014       else
1015         specializations = decl_specializations;
1016
1017       if (hash == 0)
1018         hash = hash_specialization (&elt);
1019       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1020       if (found)
1021         return found->spec;
1022     }
1023
1024   return NULL_TREE;
1025 }
1026
1027 /* Like retrieve_specialization, but for local declarations.  */
1028
1029 static tree
1030 retrieve_local_specialization (tree tmpl)
1031 {
1032   tree spec;
1033
1034   if (local_specializations == NULL)
1035     return NULL_TREE;
1036
1037   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1038                                      htab_hash_pointer (tmpl));
1039   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1040 }
1041
1042 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1043
1044 int
1045 is_specialization_of (tree decl, tree tmpl)
1046 {
1047   tree t;
1048
1049   if (TREE_CODE (decl) == FUNCTION_DECL)
1050     {
1051       for (t = decl;
1052            t != NULL_TREE;
1053            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1054         if (t == tmpl)
1055           return 1;
1056     }
1057   else
1058     {
1059       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1060
1061       for (t = TREE_TYPE (decl);
1062            t != NULL_TREE;
1063            t = CLASSTYPE_USE_TEMPLATE (t)
1064              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1065         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1066           return 1;
1067     }
1068
1069   return 0;
1070 }
1071
1072 /* Returns nonzero iff DECL is a specialization of friend declaration
1073    FRIEND_DECL according to [temp.friend].  */
1074
1075 bool
1076 is_specialization_of_friend (tree decl, tree friend_decl)
1077 {
1078   bool need_template = true;
1079   int template_depth;
1080
1081   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1082               || TREE_CODE (decl) == TYPE_DECL);
1083
1084   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1085      of a template class, we want to check if DECL is a specialization
1086      if this.  */
1087   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1088       && DECL_TEMPLATE_INFO (friend_decl)
1089       && !DECL_USE_TEMPLATE (friend_decl))
1090     {
1091       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1092       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1093       need_template = false;
1094     }
1095   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1096            && !PRIMARY_TEMPLATE_P (friend_decl))
1097     need_template = false;
1098
1099   /* There is nothing to do if this is not a template friend.  */
1100   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1101     return false;
1102
1103   if (is_specialization_of (decl, friend_decl))
1104     return true;
1105
1106   /* [temp.friend/6]
1107      A member of a class template may be declared to be a friend of a
1108      non-template class.  In this case, the corresponding member of
1109      every specialization of the class template is a friend of the
1110      class granting friendship.
1111
1112      For example, given a template friend declaration
1113
1114        template <class T> friend void A<T>::f();
1115
1116      the member function below is considered a friend
1117
1118        template <> struct A<int> {
1119          void f();
1120        };
1121
1122      For this type of template friend, TEMPLATE_DEPTH below will be
1123      nonzero.  To determine if DECL is a friend of FRIEND, we first
1124      check if the enclosing class is a specialization of another.  */
1125
1126   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1127   if (template_depth
1128       && DECL_CLASS_SCOPE_P (decl)
1129       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1130                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1131     {
1132       /* Next, we check the members themselves.  In order to handle
1133          a few tricky cases, such as when FRIEND_DECL's are
1134
1135            template <class T> friend void A<T>::g(T t);
1136            template <class T> template <T t> friend void A<T>::h();
1137
1138          and DECL's are
1139
1140            void A<int>::g(int);
1141            template <int> void A<int>::h();
1142
1143          we need to figure out ARGS, the template arguments from
1144          the context of DECL.  This is required for template substitution
1145          of `T' in the function parameter of `g' and template parameter
1146          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1147
1148       tree context = DECL_CONTEXT (decl);
1149       tree args = NULL_TREE;
1150       int current_depth = 0;
1151
1152       while (current_depth < template_depth)
1153         {
1154           if (CLASSTYPE_TEMPLATE_INFO (context))
1155             {
1156               if (current_depth == 0)
1157                 args = TYPE_TI_ARGS (context);
1158               else
1159                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1160               current_depth++;
1161             }
1162           context = TYPE_CONTEXT (context);
1163         }
1164
1165       if (TREE_CODE (decl) == FUNCTION_DECL)
1166         {
1167           bool is_template;
1168           tree friend_type;
1169           tree decl_type;
1170           tree friend_args_type;
1171           tree decl_args_type;
1172
1173           /* Make sure that both DECL and FRIEND_DECL are templates or
1174              non-templates.  */
1175           is_template = DECL_TEMPLATE_INFO (decl)
1176                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1177           if (need_template ^ is_template)
1178             return false;
1179           else if (is_template)
1180             {
1181               /* If both are templates, check template parameter list.  */
1182               tree friend_parms
1183                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1184                                          args, tf_none);
1185               if (!comp_template_parms
1186                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1187                       friend_parms))
1188                 return false;
1189
1190               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1191             }
1192           else
1193             decl_type = TREE_TYPE (decl);
1194
1195           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1196                                               tf_none, NULL_TREE);
1197           if (friend_type == error_mark_node)
1198             return false;
1199
1200           /* Check if return types match.  */
1201           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1202             return false;
1203
1204           /* Check if function parameter types match, ignoring the
1205              `this' parameter.  */
1206           friend_args_type = TYPE_ARG_TYPES (friend_type);
1207           decl_args_type = TYPE_ARG_TYPES (decl_type);
1208           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1209             friend_args_type = TREE_CHAIN (friend_args_type);
1210           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1211             decl_args_type = TREE_CHAIN (decl_args_type);
1212
1213           return compparms (decl_args_type, friend_args_type);
1214         }
1215       else
1216         {
1217           /* DECL is a TYPE_DECL */
1218           bool is_template;
1219           tree decl_type = TREE_TYPE (decl);
1220
1221           /* Make sure that both DECL and FRIEND_DECL are templates or
1222              non-templates.  */
1223           is_template
1224             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1225               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1226
1227           if (need_template ^ is_template)
1228             return false;
1229           else if (is_template)
1230             {
1231               tree friend_parms;
1232               /* If both are templates, check the name of the two
1233                  TEMPLATE_DECL's first because is_friend didn't.  */
1234               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1235                   != DECL_NAME (friend_decl))
1236                 return false;
1237
1238               /* Now check template parameter list.  */
1239               friend_parms
1240                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1241                                          args, tf_none);
1242               return comp_template_parms
1243                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1244                  friend_parms);
1245             }
1246           else
1247             return (DECL_NAME (decl)
1248                     == DECL_NAME (friend_decl));
1249         }
1250     }
1251   return false;
1252 }
1253
1254 /* Register the specialization SPEC as a specialization of TMPL with
1255    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1256    is actually just a friend declaration.  Returns SPEC, or an
1257    equivalent prior declaration, if available.  */
1258
1259 static tree
1260 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1261                          hashval_t hash)
1262 {
1263   tree fn;
1264   spec_entry **slot = NULL;
1265   spec_entry elt;
1266
1267   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1268
1269   if (TREE_CODE (spec) == FUNCTION_DECL
1270       && uses_template_parms (DECL_TI_ARGS (spec)))
1271     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1272        register it; we want the corresponding TEMPLATE_DECL instead.
1273        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1274        the more obvious `uses_template_parms (spec)' to avoid problems
1275        with default function arguments.  In particular, given
1276        something like this:
1277
1278           template <class T> void f(T t1, T t = T())
1279
1280        the default argument expression is not substituted for in an
1281        instantiation unless and until it is actually needed.  */
1282     return spec;
1283
1284   if (optimize_specialization_lookup_p (tmpl))
1285     /* We don't put these specializations in the hash table, but we might
1286        want to give an error about a mismatch.  */
1287     fn = retrieve_specialization (tmpl, args, 0);
1288   else
1289     {
1290       elt.tmpl = tmpl;
1291       elt.args = args;
1292       elt.spec = spec;
1293
1294       if (hash == 0)
1295         hash = hash_specialization (&elt);
1296
1297       slot = (spec_entry **)
1298         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1299       if (*slot)
1300         fn = (*slot)->spec;
1301       else
1302         fn = NULL_TREE;
1303     }
1304
1305   /* We can sometimes try to re-register a specialization that we've
1306      already got.  In particular, regenerate_decl_from_template calls
1307      duplicate_decls which will update the specialization list.  But,
1308      we'll still get called again here anyhow.  It's more convenient
1309      to simply allow this than to try to prevent it.  */
1310   if (fn == spec)
1311     return spec;
1312   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1313     {
1314       if (DECL_TEMPLATE_INSTANTIATION (fn))
1315         {
1316           if (DECL_ODR_USED (fn)
1317               || DECL_EXPLICIT_INSTANTIATION (fn))
1318             {
1319               error ("specialization of %qD after instantiation",
1320                      fn);
1321               return error_mark_node;
1322             }
1323           else
1324             {
1325               tree clone;
1326               /* This situation should occur only if the first
1327                  specialization is an implicit instantiation, the
1328                  second is an explicit specialization, and the
1329                  implicit instantiation has not yet been used.  That
1330                  situation can occur if we have implicitly
1331                  instantiated a member function and then specialized
1332                  it later.
1333
1334                  We can also wind up here if a friend declaration that
1335                  looked like an instantiation turns out to be a
1336                  specialization:
1337
1338                    template <class T> void foo(T);
1339                    class S { friend void foo<>(int) };
1340                    template <> void foo(int);
1341
1342                  We transform the existing DECL in place so that any
1343                  pointers to it become pointers to the updated
1344                  declaration.
1345
1346                  If there was a definition for the template, but not
1347                  for the specialization, we want this to look as if
1348                  there were no definition, and vice versa.  */
1349               DECL_INITIAL (fn) = NULL_TREE;
1350               duplicate_decls (spec, fn, is_friend);
1351               /* The call to duplicate_decls will have applied
1352                  [temp.expl.spec]:
1353
1354                    An explicit specialization of a function template
1355                    is inline only if it is explicitly declared to be,
1356                    and independently of whether its function template
1357                    is.
1358
1359                 to the primary function; now copy the inline bits to
1360                 the various clones.  */
1361               FOR_EACH_CLONE (clone, fn)
1362                 {
1363                   DECL_DECLARED_INLINE_P (clone)
1364                     = DECL_DECLARED_INLINE_P (fn);
1365                   DECL_SOURCE_LOCATION (clone)
1366                     = DECL_SOURCE_LOCATION (fn);
1367                 }
1368               check_specialization_namespace (fn);
1369
1370               return fn;
1371             }
1372         }
1373       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1374         {
1375           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1376             /* Dup decl failed, but this is a new definition. Set the
1377                line number so any errors match this new
1378                definition.  */
1379             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1380
1381           return fn;
1382         }
1383     }
1384   else if (fn)
1385     return duplicate_decls (spec, fn, is_friend);
1386
1387   /* A specialization must be declared in the same namespace as the
1388      template it is specializing.  */
1389   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1390       && !check_specialization_namespace (tmpl))
1391     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1392
1393   if (!optimize_specialization_lookup_p (tmpl))
1394     {
1395       gcc_assert (tmpl && args && spec);
1396       *slot = GGC_NEW (spec_entry);
1397       **slot = elt;
1398       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1399           && PRIMARY_TEMPLATE_P (tmpl)
1400           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1401         /* TMPL is a forward declaration of a template function; keep a list
1402            of all specializations in case we need to reassign them to a friend
1403            template later in tsubst_friend_function.  */
1404         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1405           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1406     }
1407
1408   return spec;
1409 }
1410
1411 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1412    TMPL and ARGS members, ignores SPEC.  */
1413
1414 static int
1415 eq_specializations (const void *p1, const void *p2)
1416 {
1417   const spec_entry *e1 = (const spec_entry *)p1;
1418   const spec_entry *e2 = (const spec_entry *)p2;
1419
1420   return (e1->tmpl == e2->tmpl
1421           && comp_template_args (e1->args, e2->args));
1422 }
1423
1424 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1425
1426 static hashval_t
1427 hash_tmpl_and_args (tree tmpl, tree args)
1428 {
1429   hashval_t val = DECL_UID (tmpl);
1430   return iterative_hash_template_arg (args, val);
1431 }
1432
1433 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1434    ignoring SPEC.  */
1435
1436 static hashval_t
1437 hash_specialization (const void *p)
1438 {
1439   const spec_entry *e = (const spec_entry *)p;
1440   return hash_tmpl_and_args (e->tmpl, e->args);
1441 }
1442
1443 /* Recursively calculate a hash value for a template argument ARG, for use
1444    in the hash tables of template specializations.  */
1445
1446 static hashval_t
1447 iterative_hash_template_arg (tree arg, hashval_t val)
1448 {
1449   unsigned HOST_WIDE_INT i;
1450   enum tree_code code;
1451   char tclass;
1452
1453   if (arg == NULL_TREE)
1454     return iterative_hash_object (arg, val);
1455
1456   if (!TYPE_P (arg))
1457     STRIP_NOPS (arg);
1458
1459   code = TREE_CODE (arg);
1460   tclass = TREE_CODE_CLASS (code);
1461
1462   val = iterative_hash_object (code, val);
1463
1464   switch (code)
1465     {
1466     case ERROR_MARK:
1467       return val;
1468
1469     case IDENTIFIER_NODE:
1470       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1471
1472     case TREE_VEC:
1473       {
1474         int i, len = TREE_VEC_LENGTH (arg);
1475         for (i = 0; i < len; ++i)
1476           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1477         return val;
1478       }
1479
1480     case TYPE_PACK_EXPANSION:
1481     case EXPR_PACK_EXPANSION:
1482       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1483
1484     case ARGUMENT_PACK_SELECT:
1485       /* We can get one of these when re-hashing a previous entry in the middle
1486          of substituting into a pack expansion.  Just look through it...  */
1487       arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1488       /* ...and fall through.  */
1489     case TYPE_ARGUMENT_PACK:
1490     case NONTYPE_ARGUMENT_PACK:
1491       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1492
1493     case TREE_LIST:
1494       for (; arg; arg = TREE_CHAIN (arg))
1495         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1496       return val;
1497
1498     case OVERLOAD:
1499       for (; arg; arg = OVL_CHAIN (arg))
1500         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1501       return val;
1502
1503     case CONSTRUCTOR:
1504       {
1505         tree field, value;
1506         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1507           {
1508             val = iterative_hash_template_arg (field, val);
1509             val = iterative_hash_template_arg (value, val);
1510           }
1511         return val;
1512       }
1513
1514     case PARM_DECL:
1515       if (!DECL_ARTIFICIAL (arg))
1516         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1517       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1518
1519     case TARGET_EXPR:
1520       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1521
1522     case PTRMEM_CST:
1523       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1524       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1525
1526     case TEMPLATE_PARM_INDEX:
1527       val = iterative_hash_template_arg
1528         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1529       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1530       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1531
1532     case TRAIT_EXPR:
1533       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1534       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1535       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1536
1537     case BASELINK:
1538       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1539                                          val);
1540       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1541                                           val);
1542
1543     case MODOP_EXPR:
1544       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1545       code = TREE_CODE (TREE_OPERAND (arg, 1));
1546       val = iterative_hash_object (code, val);
1547       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1548
1549     default:
1550       switch (tclass)
1551         {
1552         case tcc_type:
1553           if (TYPE_CANONICAL (arg))
1554             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1555                                           val);
1556           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1557             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1558           /* Otherwise just compare the types during lookup.  */
1559           return val;
1560
1561         case tcc_declaration:
1562         case tcc_constant:
1563           return iterative_hash_expr (arg, val);
1564
1565         default:
1566           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1567           {
1568             unsigned n = TREE_OPERAND_LENGTH (arg);
1569             for (i = 0; i < n; ++i)
1570               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1571             return val;
1572           }
1573         }
1574     }
1575   gcc_unreachable ();
1576   return 0;
1577 }
1578
1579 /* Unregister the specialization SPEC as a specialization of TMPL.
1580    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1581    if the SPEC was listed as a specialization of TMPL.
1582
1583    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1584
1585 bool
1586 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1587 {
1588   spec_entry **slot;
1589   spec_entry elt;
1590
1591   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1592   elt.args = TI_ARGS (tinfo);
1593   elt.spec = NULL_TREE;
1594
1595   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1596   if (*slot)
1597     {
1598       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1599       gcc_assert (new_spec != NULL_TREE);
1600       (*slot)->spec = new_spec;
1601       return 1;
1602     }
1603
1604   return 0;
1605 }
1606
1607 /* Compare an entry in the local specializations hash table P1 (which
1608    is really a pointer to a TREE_LIST) with P2 (which is really a
1609    DECL).  */
1610
1611 static int
1612 eq_local_specializations (const void *p1, const void *p2)
1613 {
1614   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1615 }
1616
1617 /* Hash P1, an entry in the local specializations table.  */
1618
1619 static hashval_t
1620 hash_local_specialization (const void* p1)
1621 {
1622   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1623 }
1624
1625 /* Like register_specialization, but for local declarations.  We are
1626    registering SPEC, an instantiation of TMPL.  */
1627
1628 static void
1629 register_local_specialization (tree spec, tree tmpl)
1630 {
1631   void **slot;
1632
1633   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1634                                    htab_hash_pointer (tmpl), INSERT);
1635   *slot = build_tree_list (spec, tmpl);
1636 }
1637
1638 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1639    specialized class.  */
1640
1641 bool
1642 explicit_class_specialization_p (tree type)
1643 {
1644   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1645     return false;
1646   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1647 }
1648
1649 /* Print the list of overloaded FNS in an error message.   */
1650
1651 static void
1652 print_overloaded_functions (tree fns, const char **str)
1653 {
1654   tree fn;
1655   for (fn = fns; fn; fn = OVL_NEXT (fn))
1656     {
1657       if (TREE_CODE (fn) == TREE_LIST)
1658         print_candidates (fn);
1659       else
1660         error ("%s %+#D", *str, OVL_CURRENT (fn));
1661       *str = "               ";
1662     }
1663 }
1664
1665 /* Print the list of candidate FNS in an error message.  */
1666
1667 void
1668 print_candidates (tree fns)
1669 {
1670   const char *str = "candidates are:";
1671
1672   if (is_overloaded_fn (fns))
1673     print_overloaded_functions (fns, &str);
1674   else
1675     {
1676       tree fn;
1677       for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1678         print_overloaded_functions (TREE_VALUE (fn), &str);
1679     }
1680 }
1681
1682 /* Returns the template (one of the functions given by TEMPLATE_ID)
1683    which can be specialized to match the indicated DECL with the
1684    explicit template args given in TEMPLATE_ID.  The DECL may be
1685    NULL_TREE if none is available.  In that case, the functions in
1686    TEMPLATE_ID are non-members.
1687
1688    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1689    specialization of a member template.
1690
1691    The TEMPLATE_COUNT is the number of references to qualifying
1692    template classes that appeared in the name of the function. See
1693    check_explicit_specialization for a more accurate description.
1694
1695    TSK indicates what kind of template declaration (if any) is being
1696    declared.  TSK_TEMPLATE indicates that the declaration given by
1697    DECL, though a FUNCTION_DECL, has template parameters, and is
1698    therefore a template function.
1699
1700    The template args (those explicitly specified and those deduced)
1701    are output in a newly created vector *TARGS_OUT.
1702
1703    If it is impossible to determine the result, an error message is
1704    issued.  The error_mark_node is returned to indicate failure.  */
1705
1706 static tree
1707 determine_specialization (tree template_id,
1708                           tree decl,
1709                           tree* targs_out,
1710                           int need_member_template,
1711                           int template_count,
1712                           tmpl_spec_kind tsk)
1713 {
1714   tree fns;
1715   tree targs;
1716   tree explicit_targs;
1717   tree candidates = NULL_TREE;
1718   /* A TREE_LIST of templates of which DECL may be a specialization.
1719      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1720      corresponding TREE_PURPOSE is the set of template arguments that,
1721      when used to instantiate the template, would produce a function
1722      with the signature of DECL.  */
1723   tree templates = NULL_TREE;
1724   int header_count;
1725   struct cp_binding_level *b;
1726
1727   *targs_out = NULL_TREE;
1728
1729   if (template_id == error_mark_node || decl == error_mark_node)
1730     return error_mark_node;
1731
1732   fns = TREE_OPERAND (template_id, 0);
1733   explicit_targs = TREE_OPERAND (template_id, 1);
1734
1735   if (fns == error_mark_node)
1736     return error_mark_node;
1737
1738   /* Check for baselinks.  */
1739   if (BASELINK_P (fns))
1740     fns = BASELINK_FUNCTIONS (fns);
1741
1742   if (!is_overloaded_fn (fns))
1743     {
1744       error ("%qD is not a function template", fns);
1745       return error_mark_node;
1746     }
1747
1748   /* Count the number of template headers specified for this
1749      specialization.  */
1750   header_count = 0;
1751   for (b = current_binding_level;
1752        b->kind == sk_template_parms;
1753        b = b->level_chain)
1754     ++header_count;
1755
1756   for (; fns; fns = OVL_NEXT (fns))
1757     {
1758       tree fn = OVL_CURRENT (fns);
1759
1760       if (TREE_CODE (fn) == TEMPLATE_DECL)
1761         {
1762           tree decl_arg_types;
1763           tree fn_arg_types;
1764
1765           /* In case of explicit specialization, we need to check if
1766              the number of template headers appearing in the specialization
1767              is correct. This is usually done in check_explicit_specialization,
1768              but the check done there cannot be exhaustive when specializing
1769              member functions. Consider the following code:
1770
1771              template <> void A<int>::f(int);
1772              template <> template <> void A<int>::f(int);
1773
1774              Assuming that A<int> is not itself an explicit specialization
1775              already, the first line specializes "f" which is a non-template
1776              member function, whilst the second line specializes "f" which
1777              is a template member function. So both lines are syntactically
1778              correct, and check_explicit_specialization does not reject
1779              them.
1780
1781              Here, we can do better, as we are matching the specialization
1782              against the declarations. We count the number of template
1783              headers, and we check if they match TEMPLATE_COUNT + 1
1784              (TEMPLATE_COUNT is the number of qualifying template classes,
1785              plus there must be another header for the member template
1786              itself).
1787
1788              Notice that if header_count is zero, this is not a
1789              specialization but rather a template instantiation, so there
1790              is no check we can perform here.  */
1791           if (header_count && header_count != template_count + 1)
1792             continue;
1793
1794           /* Check that the number of template arguments at the
1795              innermost level for DECL is the same as for FN.  */
1796           if (current_binding_level->kind == sk_template_parms
1797               && !current_binding_level->explicit_spec_p
1798               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1799                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1800                                       (current_template_parms))))
1801             continue;
1802
1803           /* DECL might be a specialization of FN.  */
1804           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1805           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1806
1807           /* For a non-static member function, we need to make sure
1808              that the const qualification is the same.  Since
1809              get_bindings does not try to merge the "this" parameter,
1810              we must do the comparison explicitly.  */
1811           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1812               && !same_type_p (TREE_VALUE (fn_arg_types),
1813                                TREE_VALUE (decl_arg_types)))
1814             continue;
1815
1816           /* Skip the "this" parameter and, for constructors of
1817              classes with virtual bases, the VTT parameter.  A
1818              full specialization of a constructor will have a VTT
1819              parameter, but a template never will.  */ 
1820           decl_arg_types 
1821             = skip_artificial_parms_for (decl, decl_arg_types);
1822           fn_arg_types 
1823             = skip_artificial_parms_for (fn, fn_arg_types);
1824
1825           /* Check that the number of function parameters matches.
1826              For example,
1827                template <class T> void f(int i = 0);
1828                template <> void f<int>();
1829              The specialization f<int> is invalid but is not caught
1830              by get_bindings below.  */
1831           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1832             continue;
1833
1834           /* Function templates cannot be specializations; there are
1835              no partial specializations of functions.  Therefore, if
1836              the type of DECL does not match FN, there is no
1837              match.  */
1838           if (tsk == tsk_template)
1839             {
1840               if (compparms (fn_arg_types, decl_arg_types))
1841                 candidates = tree_cons (NULL_TREE, fn, candidates);
1842               continue;
1843             }
1844
1845           /* See whether this function might be a specialization of this
1846              template.  */
1847           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1848
1849           if (!targs)
1850             /* We cannot deduce template arguments that when used to
1851                specialize TMPL will produce DECL.  */
1852             continue;
1853
1854           /* Save this template, and the arguments deduced.  */
1855           templates = tree_cons (targs, fn, templates);
1856         }
1857       else if (need_member_template)
1858         /* FN is an ordinary member function, and we need a
1859            specialization of a member template.  */
1860         ;
1861       else if (TREE_CODE (fn) != FUNCTION_DECL)
1862         /* We can get IDENTIFIER_NODEs here in certain erroneous
1863            cases.  */
1864         ;
1865       else if (!DECL_FUNCTION_MEMBER_P (fn))
1866         /* This is just an ordinary non-member function.  Nothing can
1867            be a specialization of that.  */
1868         ;
1869       else if (DECL_ARTIFICIAL (fn))
1870         /* Cannot specialize functions that are created implicitly.  */
1871         ;
1872       else
1873         {
1874           tree decl_arg_types;
1875
1876           /* This is an ordinary member function.  However, since
1877              we're here, we can assume it's enclosing class is a
1878              template class.  For example,
1879
1880                template <typename T> struct S { void f(); };
1881                template <> void S<int>::f() {}
1882
1883              Here, S<int>::f is a non-template, but S<int> is a
1884              template class.  If FN has the same type as DECL, we
1885              might be in business.  */
1886
1887           if (!DECL_TEMPLATE_INFO (fn))
1888             /* Its enclosing class is an explicit specialization
1889                of a template class.  This is not a candidate.  */
1890             continue;
1891
1892           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1893                             TREE_TYPE (TREE_TYPE (fn))))
1894             /* The return types differ.  */
1895             continue;
1896
1897           /* Adjust the type of DECL in case FN is a static member.  */
1898           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1899           if (DECL_STATIC_FUNCTION_P (fn)
1900               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1901             decl_arg_types = TREE_CHAIN (decl_arg_types);
1902
1903           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1904                          decl_arg_types))
1905             /* They match!  */
1906             candidates = tree_cons (NULL_TREE, fn, candidates);
1907         }
1908     }
1909
1910   if (templates && TREE_CHAIN (templates))
1911     {
1912       /* We have:
1913
1914            [temp.expl.spec]
1915
1916            It is possible for a specialization with a given function
1917            signature to be instantiated from more than one function
1918            template.  In such cases, explicit specification of the
1919            template arguments must be used to uniquely identify the
1920            function template specialization being specialized.
1921
1922          Note that here, there's no suggestion that we're supposed to
1923          determine which of the candidate templates is most
1924          specialized.  However, we, also have:
1925
1926            [temp.func.order]
1927
1928            Partial ordering of overloaded function template
1929            declarations is used in the following contexts to select
1930            the function template to which a function template
1931            specialization refers:
1932
1933            -- when an explicit specialization refers to a function
1934               template.
1935
1936          So, we do use the partial ordering rules, at least for now.
1937          This extension can only serve to make invalid programs valid,
1938          so it's safe.  And, there is strong anecdotal evidence that
1939          the committee intended the partial ordering rules to apply;
1940          the EDG front end has that behavior, and John Spicer claims
1941          that the committee simply forgot to delete the wording in
1942          [temp.expl.spec].  */
1943       tree tmpl = most_specialized_instantiation (templates);
1944       if (tmpl != error_mark_node)
1945         {
1946           templates = tmpl;
1947           TREE_CHAIN (templates) = NULL_TREE;
1948         }
1949     }
1950
1951   if (templates == NULL_TREE && candidates == NULL_TREE)
1952     {
1953       error ("template-id %qD for %q+D does not match any template "
1954              "declaration", template_id, decl);
1955       if (header_count && header_count != template_count + 1)
1956         inform (input_location, "saw %d %<template<>%>, need %d for "
1957                 "specializing a member function template",
1958                 header_count, template_count + 1);
1959       return error_mark_node;
1960     }
1961   else if ((templates && TREE_CHAIN (templates))
1962            || (candidates && TREE_CHAIN (candidates))
1963            || (templates && candidates))
1964     {
1965       error ("ambiguous template specialization %qD for %q+D",
1966              template_id, decl);
1967       candidates = chainon (candidates, templates);
1968       print_candidates (candidates);
1969       return error_mark_node;
1970     }
1971
1972   /* We have one, and exactly one, match.  */
1973   if (candidates)
1974     {
1975       tree fn = TREE_VALUE (candidates);
1976       *targs_out = copy_node (DECL_TI_ARGS (fn));
1977       /* DECL is a re-declaration or partial instantiation of a template
1978          function.  */
1979       if (TREE_CODE (fn) == TEMPLATE_DECL)
1980         return fn;
1981       /* It was a specialization of an ordinary member function in a
1982          template class.  */
1983       return DECL_TI_TEMPLATE (fn);
1984     }
1985
1986   /* It was a specialization of a template.  */
1987   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1988   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1989     {
1990       *targs_out = copy_node (targs);
1991       SET_TMPL_ARGS_LEVEL (*targs_out,
1992                            TMPL_ARGS_DEPTH (*targs_out),
1993                            TREE_PURPOSE (templates));
1994     }
1995   else
1996     *targs_out = TREE_PURPOSE (templates);
1997   return TREE_VALUE (templates);
1998 }
1999
2000 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2001    but with the default argument values filled in from those in the
2002    TMPL_TYPES.  */
2003
2004 static tree
2005 copy_default_args_to_explicit_spec_1 (tree spec_types,
2006                                       tree tmpl_types)
2007 {
2008   tree new_spec_types;
2009
2010   if (!spec_types)
2011     return NULL_TREE;
2012
2013   if (spec_types == void_list_node)
2014     return void_list_node;
2015
2016   /* Substitute into the rest of the list.  */
2017   new_spec_types =
2018     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2019                                           TREE_CHAIN (tmpl_types));
2020
2021   /* Add the default argument for this parameter.  */
2022   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2023                          TREE_VALUE (spec_types),
2024                          new_spec_types);
2025 }
2026
2027 /* DECL is an explicit specialization.  Replicate default arguments
2028    from the template it specializes.  (That way, code like:
2029
2030      template <class T> void f(T = 3);
2031      template <> void f(double);
2032      void g () { f (); }
2033
2034    works, as required.)  An alternative approach would be to look up
2035    the correct default arguments at the call-site, but this approach
2036    is consistent with how implicit instantiations are handled.  */
2037
2038 static void
2039 copy_default_args_to_explicit_spec (tree decl)
2040 {
2041   tree tmpl;
2042   tree spec_types;
2043   tree tmpl_types;
2044   tree new_spec_types;
2045   tree old_type;
2046   tree new_type;
2047   tree t;
2048   tree object_type = NULL_TREE;
2049   tree in_charge = NULL_TREE;
2050   tree vtt = NULL_TREE;
2051
2052   /* See if there's anything we need to do.  */
2053   tmpl = DECL_TI_TEMPLATE (decl);
2054   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2055   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2056     if (TREE_PURPOSE (t))
2057       break;
2058   if (!t)
2059     return;
2060
2061   old_type = TREE_TYPE (decl);
2062   spec_types = TYPE_ARG_TYPES (old_type);
2063
2064   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2065     {
2066       /* Remove the this pointer, but remember the object's type for
2067          CV quals.  */
2068       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2069       spec_types = TREE_CHAIN (spec_types);
2070       tmpl_types = TREE_CHAIN (tmpl_types);
2071
2072       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2073         {
2074           /* DECL may contain more parameters than TMPL due to the extra
2075              in-charge parameter in constructors and destructors.  */
2076           in_charge = spec_types;
2077           spec_types = TREE_CHAIN (spec_types);
2078         }
2079       if (DECL_HAS_VTT_PARM_P (decl))
2080         {
2081           vtt = spec_types;
2082           spec_types = TREE_CHAIN (spec_types);
2083         }
2084     }
2085
2086   /* Compute the merged default arguments.  */
2087   new_spec_types =
2088     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2089
2090   /* Compute the new FUNCTION_TYPE.  */
2091   if (object_type)
2092     {
2093       if (vtt)
2094         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2095                                          TREE_VALUE (vtt),
2096                                          new_spec_types);
2097
2098       if (in_charge)
2099         /* Put the in-charge parameter back.  */
2100         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2101                                          TREE_VALUE (in_charge),
2102                                          new_spec_types);
2103
2104       new_type = build_method_type_directly (object_type,
2105                                              TREE_TYPE (old_type),
2106                                              new_spec_types);
2107     }
2108   else
2109     new_type = build_function_type (TREE_TYPE (old_type),
2110                                     new_spec_types);
2111   new_type = cp_build_type_attribute_variant (new_type,
2112                                               TYPE_ATTRIBUTES (old_type));
2113   new_type = build_exception_variant (new_type,
2114                                       TYPE_RAISES_EXCEPTIONS (old_type));
2115   TREE_TYPE (decl) = new_type;
2116 }
2117
2118 /* Check to see if the function just declared, as indicated in
2119    DECLARATOR, and in DECL, is a specialization of a function
2120    template.  We may also discover that the declaration is an explicit
2121    instantiation at this point.
2122
2123    Returns DECL, or an equivalent declaration that should be used
2124    instead if all goes well.  Issues an error message if something is
2125    amiss.  Returns error_mark_node if the error is not easily
2126    recoverable.
2127
2128    FLAGS is a bitmask consisting of the following flags:
2129
2130    2: The function has a definition.
2131    4: The function is a friend.
2132
2133    The TEMPLATE_COUNT is the number of references to qualifying
2134    template classes that appeared in the name of the function.  For
2135    example, in
2136
2137      template <class T> struct S { void f(); };
2138      void S<int>::f();
2139
2140    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2141    classes are not counted in the TEMPLATE_COUNT, so that in
2142
2143      template <class T> struct S {};
2144      template <> struct S<int> { void f(); }
2145      template <> void S<int>::f();
2146
2147    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2148    invalid; there should be no template <>.)
2149
2150    If the function is a specialization, it is marked as such via
2151    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2152    is set up correctly, and it is added to the list of specializations
2153    for that template.  */
2154
2155 tree
2156 check_explicit_specialization (tree declarator,
2157                                tree decl,
2158                                int template_count,
2159                                int flags)
2160 {
2161   int have_def = flags & 2;
2162   int is_friend = flags & 4;
2163   int specialization = 0;
2164   int explicit_instantiation = 0;
2165   int member_specialization = 0;
2166   tree ctype = DECL_CLASS_CONTEXT (decl);
2167   tree dname = DECL_NAME (decl);
2168   tmpl_spec_kind tsk;
2169
2170   if (is_friend)
2171     {
2172       if (!processing_specialization)
2173         tsk = tsk_none;
2174       else
2175         tsk = tsk_excessive_parms;
2176     }
2177   else
2178     tsk = current_tmpl_spec_kind (template_count);
2179
2180   switch (tsk)
2181     {
2182     case tsk_none:
2183       if (processing_specialization)
2184         {
2185           specialization = 1;
2186           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2187         }
2188       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2189         {
2190           if (is_friend)
2191             /* This could be something like:
2192
2193                template <class T> void f(T);
2194                class S { friend void f<>(int); }  */
2195             specialization = 1;
2196           else
2197             {
2198               /* This case handles bogus declarations like template <>
2199                  template <class T> void f<int>(); */
2200
2201               error ("template-id %qD in declaration of primary template",
2202                      declarator);
2203               return decl;
2204             }
2205         }
2206       break;
2207
2208     case tsk_invalid_member_spec:
2209       /* The error has already been reported in
2210          check_specialization_scope.  */
2211       return error_mark_node;
2212
2213     case tsk_invalid_expl_inst:
2214       error ("template parameter list used in explicit instantiation");
2215
2216       /* Fall through.  */
2217
2218     case tsk_expl_inst:
2219       if (have_def)
2220         error ("definition provided for explicit instantiation");
2221
2222       explicit_instantiation = 1;
2223       break;
2224
2225     case tsk_excessive_parms:
2226     case tsk_insufficient_parms:
2227       if (tsk == tsk_excessive_parms)
2228         error ("too many template parameter lists in declaration of %qD",
2229                decl);
2230       else if (template_header_count)
2231         error("too few template parameter lists in declaration of %qD", decl);
2232       else
2233         error("explicit specialization of %qD must be introduced by "
2234               "%<template <>%>", decl);
2235
2236       /* Fall through.  */
2237     case tsk_expl_spec:
2238       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2239       if (ctype)
2240         member_specialization = 1;
2241       else
2242         specialization = 1;
2243       break;
2244
2245     case tsk_template:
2246       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2247         {
2248           /* This case handles bogus declarations like template <>
2249              template <class T> void f<int>(); */
2250
2251           if (uses_template_parms (declarator))
2252             error ("function template partial specialization %qD "
2253                    "is not allowed", declarator);
2254           else
2255             error ("template-id %qD in declaration of primary template",
2256                    declarator);
2257           return decl;
2258         }
2259
2260       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2261         /* This is a specialization of a member template, without
2262            specialization the containing class.  Something like:
2263
2264              template <class T> struct S {
2265                template <class U> void f (U);
2266              };
2267              template <> template <class U> void S<int>::f(U) {}
2268
2269            That's a specialization -- but of the entire template.  */
2270         specialization = 1;
2271       break;
2272
2273     default:
2274       gcc_unreachable ();
2275     }
2276
2277   if (specialization || member_specialization)
2278     {
2279       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2280       for (; t; t = TREE_CHAIN (t))
2281         if (TREE_PURPOSE (t))
2282           {
2283             permerror (input_location, 
2284                        "default argument specified in explicit specialization");
2285             break;
2286           }
2287     }
2288
2289   if (specialization || member_specialization || explicit_instantiation)
2290     {
2291       tree tmpl = NULL_TREE;
2292       tree targs = NULL_TREE;
2293
2294       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2295       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2296         {
2297           tree fns;
2298
2299           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2300           if (ctype)
2301             fns = dname;
2302           else
2303             {
2304               /* If there is no class context, the explicit instantiation
2305                  must be at namespace scope.  */
2306               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2307
2308               /* Find the namespace binding, using the declaration
2309                  context.  */
2310               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2311                                            false, true);
2312               if (fns == error_mark_node || !is_overloaded_fn (fns))
2313                 {
2314                   error ("%qD is not a template function", dname);
2315                   fns = error_mark_node;
2316                 }
2317               else
2318                 {
2319                   tree fn = OVL_CURRENT (fns);
2320                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2321                                                 CP_DECL_CONTEXT (fn)))
2322                     error ("%qD is not declared in %qD",
2323                            decl, current_namespace);
2324                 }
2325             }
2326
2327           declarator = lookup_template_function (fns, NULL_TREE);
2328         }
2329
2330       if (declarator == error_mark_node)
2331         return error_mark_node;
2332
2333       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2334         {
2335           if (!explicit_instantiation)
2336             /* A specialization in class scope.  This is invalid,
2337                but the error will already have been flagged by
2338                check_specialization_scope.  */
2339             return error_mark_node;
2340           else
2341             {
2342               /* It's not valid to write an explicit instantiation in
2343                  class scope, e.g.:
2344
2345                    class C { template void f(); }
2346
2347                    This case is caught by the parser.  However, on
2348                    something like:
2349
2350                    template class C { void f(); };
2351
2352                    (which is invalid) we can get here.  The error will be
2353                    issued later.  */
2354               ;
2355             }
2356
2357           return decl;
2358         }
2359       else if (ctype != NULL_TREE
2360                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2361                    IDENTIFIER_NODE))
2362         {
2363           /* Find the list of functions in ctype that have the same
2364              name as the declared function.  */
2365           tree name = TREE_OPERAND (declarator, 0);
2366           tree fns = NULL_TREE;
2367           int idx;
2368
2369           if (constructor_name_p (name, ctype))
2370             {
2371               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2372
2373               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2374                   : !CLASSTYPE_DESTRUCTORS (ctype))
2375                 {
2376                   /* From [temp.expl.spec]:
2377
2378                      If such an explicit specialization for the member
2379                      of a class template names an implicitly-declared
2380                      special member function (clause _special_), the
2381                      program is ill-formed.
2382
2383                      Similar language is found in [temp.explicit].  */
2384                   error ("specialization of implicitly-declared special member function");
2385                   return error_mark_node;
2386                 }
2387
2388               name = is_constructor ? ctor_identifier : dtor_identifier;
2389             }
2390
2391           if (!DECL_CONV_FN_P (decl))
2392             {
2393               idx = lookup_fnfields_1 (ctype, name);
2394               if (idx >= 0)
2395                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2396             }
2397           else
2398             {
2399               VEC(tree,gc) *methods;
2400               tree ovl;
2401
2402               /* For a type-conversion operator, we cannot do a
2403                  name-based lookup.  We might be looking for `operator
2404                  int' which will be a specialization of `operator T'.
2405                  So, we find *all* the conversion operators, and then
2406                  select from them.  */
2407               fns = NULL_TREE;
2408
2409               methods = CLASSTYPE_METHOD_VEC (ctype);
2410               if (methods)
2411                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2412                      VEC_iterate (tree, methods, idx, ovl);
2413                      ++idx)
2414                   {
2415                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2416                       /* There are no more conversion functions.  */
2417                       break;
2418
2419                     /* Glue all these conversion functions together
2420                        with those we already have.  */
2421                     for (; ovl; ovl = OVL_NEXT (ovl))
2422                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2423                   }
2424             }
2425
2426           if (fns == NULL_TREE)
2427             {
2428               error ("no member function %qD declared in %qT", name, ctype);
2429               return error_mark_node;
2430             }
2431           else
2432             TREE_OPERAND (declarator, 0) = fns;
2433         }
2434
2435       /* Figure out what exactly is being specialized at this point.
2436          Note that for an explicit instantiation, even one for a
2437          member function, we cannot tell apriori whether the
2438          instantiation is for a member template, or just a member
2439          function of a template class.  Even if a member template is
2440          being instantiated, the member template arguments may be
2441          elided if they can be deduced from the rest of the
2442          declaration.  */
2443       tmpl = determine_specialization (declarator, decl,
2444                                        &targs,
2445                                        member_specialization,
2446                                        template_count,
2447                                        tsk);
2448
2449       if (!tmpl || tmpl == error_mark_node)
2450         /* We couldn't figure out what this declaration was
2451            specializing.  */
2452         return error_mark_node;
2453       else
2454         {
2455           tree gen_tmpl = most_general_template (tmpl);
2456
2457           if (explicit_instantiation)
2458             {
2459               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2460                  is done by do_decl_instantiation later.  */
2461
2462               int arg_depth = TMPL_ARGS_DEPTH (targs);
2463               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2464
2465               if (arg_depth > parm_depth)
2466                 {
2467                   /* If TMPL is not the most general template (for
2468                      example, if TMPL is a friend template that is
2469                      injected into namespace scope), then there will
2470                      be too many levels of TARGS.  Remove some of them
2471                      here.  */
2472                   int i;
2473                   tree new_targs;
2474
2475                   new_targs = make_tree_vec (parm_depth);
2476                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2477                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2478                       = TREE_VEC_ELT (targs, i);
2479                   targs = new_targs;
2480                 }
2481
2482               return instantiate_template (tmpl, targs, tf_error);
2483             }
2484
2485           /* If we thought that the DECL was a member function, but it
2486              turns out to be specializing a static member function,
2487              make DECL a static member function as well.  */
2488           if (DECL_STATIC_FUNCTION_P (tmpl)
2489               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2490             revert_static_member_fn (decl);
2491
2492           /* If this is a specialization of a member template of a
2493              template class, we want to return the TEMPLATE_DECL, not
2494              the specialization of it.  */
2495           if (tsk == tsk_template)
2496             {
2497               tree result = DECL_TEMPLATE_RESULT (tmpl);
2498               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2499               DECL_INITIAL (result) = NULL_TREE;
2500               if (have_def)
2501                 {
2502                   tree parm;
2503                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2504                   DECL_SOURCE_LOCATION (result)
2505                     = DECL_SOURCE_LOCATION (decl);
2506                   /* We want to use the argument list specified in the
2507                      definition, not in the original declaration.  */
2508                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2509                   for (parm = DECL_ARGUMENTS (result); parm;
2510                        parm = TREE_CHAIN (parm))
2511                     DECL_CONTEXT (parm) = result;
2512                 }
2513               return register_specialization (tmpl, gen_tmpl, targs,
2514                                               is_friend, 0);
2515             }
2516
2517           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2518           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2519
2520           /* Inherit default function arguments from the template
2521              DECL is specializing.  */
2522           copy_default_args_to_explicit_spec (decl);
2523
2524           /* This specialization has the same protection as the
2525              template it specializes.  */
2526           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2527           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2528
2529           /* 7.1.1-1 [dcl.stc]
2530
2531              A storage-class-specifier shall not be specified in an
2532              explicit specialization...
2533
2534              The parser rejects these, so unless action is taken here,
2535              explicit function specializations will always appear with
2536              global linkage.
2537
2538              The action recommended by the C++ CWG in response to C++
2539              defect report 605 is to make the storage class and linkage
2540              of the explicit specialization match the templated function:
2541
2542              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2543            */
2544           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2545             {
2546               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2547               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2548
2549               /* This specialization has the same linkage and visibility as
2550                  the function template it specializes.  */
2551               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2552               if (! TREE_PUBLIC (decl))
2553                 {
2554                   DECL_INTERFACE_KNOWN (decl) = 1;
2555                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2556                 }
2557               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2558               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2559                 {
2560                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2561                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2562                 }
2563             }
2564
2565           /* If DECL is a friend declaration, declared using an
2566              unqualified name, the namespace associated with DECL may
2567              have been set incorrectly.  For example, in:
2568
2569                template <typename T> void f(T);
2570                namespace N {
2571                  struct S { friend void f<int>(int); }
2572                }
2573
2574              we will have set the DECL_CONTEXT for the friend
2575              declaration to N, rather than to the global namespace.  */
2576           if (DECL_NAMESPACE_SCOPE_P (decl))
2577             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2578
2579           if (is_friend && !have_def)
2580             /* This is not really a declaration of a specialization.
2581                It's just the name of an instantiation.  But, it's not
2582                a request for an instantiation, either.  */
2583             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2584           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2585             /* This is indeed a specialization.  In case of constructors
2586                and destructors, we need in-charge and not-in-charge
2587                versions in V3 ABI.  */
2588             clone_function_decl (decl, /*update_method_vec_p=*/0);
2589
2590           /* Register this specialization so that we can find it
2591              again.  */
2592           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2593         }
2594     }
2595
2596   return decl;
2597 }
2598
2599 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2600    parameters.  These are represented in the same format used for
2601    DECL_TEMPLATE_PARMS.  */
2602
2603 int
2604 comp_template_parms (const_tree parms1, const_tree parms2)
2605 {
2606   const_tree p1;
2607   const_tree p2;
2608
2609   if (parms1 == parms2)
2610     return 1;
2611
2612   for (p1 = parms1, p2 = parms2;
2613        p1 != NULL_TREE && p2 != NULL_TREE;
2614        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2615     {
2616       tree t1 = TREE_VALUE (p1);
2617       tree t2 = TREE_VALUE (p2);
2618       int i;
2619
2620       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2621       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2622
2623       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2624         return 0;
2625
2626       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2627         {
2628           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2629           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2630
2631           /* If either of the template parameters are invalid, assume
2632              they match for the sake of error recovery. */
2633           if (parm1 == error_mark_node || parm2 == error_mark_node)
2634             return 1;
2635
2636           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2637             return 0;
2638
2639           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2640               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2641                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2642             continue;
2643           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2644             return 0;
2645         }
2646     }
2647
2648   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2649     /* One set of parameters has more parameters lists than the
2650        other.  */
2651     return 0;
2652
2653   return 1;
2654 }
2655
2656 /* Determine whether PARM is a parameter pack.  */
2657
2658 bool 
2659 template_parameter_pack_p (const_tree parm)
2660 {
2661   /* Determine if we have a non-type template parameter pack.  */
2662   if (TREE_CODE (parm) == PARM_DECL)
2663     return (DECL_TEMPLATE_PARM_P (parm) 
2664             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2665
2666   /* If this is a list of template parameters, we could get a
2667      TYPE_DECL or a TEMPLATE_DECL.  */ 
2668   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2669     parm = TREE_TYPE (parm);
2670
2671   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2672            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2673           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2674 }
2675
2676 /* Determine if T is a function parameter pack.  */
2677
2678 bool
2679 function_parameter_pack_p (const_tree t)
2680 {
2681   if (t && TREE_CODE (t) == PARM_DECL)
2682     return FUNCTION_PARAMETER_PACK_P (t);
2683   return false;
2684 }
2685
2686 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2687    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2688
2689 tree
2690 get_function_template_decl (const_tree primary_func_tmpl_inst)
2691 {
2692   if (! primary_func_tmpl_inst
2693       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2694       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2695     return NULL;
2696
2697   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2698 }
2699
2700 /* Return true iff the function parameter PARAM_DECL was expanded
2701    from the function parameter pack PACK.  */
2702
2703 bool
2704 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2705 {
2706     if (DECL_ARTIFICIAL (param_decl)
2707         || !function_parameter_pack_p (pack))
2708       return false;
2709
2710     gcc_assert (DECL_NAME (param_decl) && DECL_NAME (pack));
2711
2712     /* The parameter pack and its pack arguments have the same
2713        DECL_PARM_INDEX.  */
2714     return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2715 }
2716
2717 /* Determine whether ARGS describes a variadic template args list,
2718    i.e., one that is terminated by a template argument pack.  */
2719
2720 static bool 
2721 template_args_variadic_p (tree args)
2722 {
2723   int nargs;
2724   tree last_parm;
2725
2726   if (args == NULL_TREE)
2727     return false;
2728
2729   args = INNERMOST_TEMPLATE_ARGS (args);
2730   nargs = TREE_VEC_LENGTH (args);
2731
2732   if (nargs == 0)
2733     return false;
2734
2735   last_parm = TREE_VEC_ELT (args, nargs - 1);
2736
2737   return ARGUMENT_PACK_P (last_parm);
2738 }
2739
2740 /* Generate a new name for the parameter pack name NAME (an
2741    IDENTIFIER_NODE) that incorporates its */
2742
2743 static tree
2744 make_ith_pack_parameter_name (tree name, int i)
2745 {
2746   /* Munge the name to include the parameter index.  */
2747 #define NUMBUF_LEN 128
2748   char numbuf[NUMBUF_LEN];
2749   char* newname;
2750   int newname_len;
2751
2752   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2753   newname_len = IDENTIFIER_LENGTH (name)
2754                 + strlen (numbuf) + 2;
2755   newname = (char*)alloca (newname_len);
2756   snprintf (newname, newname_len,
2757             "%s#%i", IDENTIFIER_POINTER (name), i);
2758   return get_identifier (newname);
2759 }
2760
2761 /* Return true if T is a primary function
2762    or class template instantiation.  */
2763
2764 bool
2765 primary_template_instantiation_p (const_tree t)
2766 {
2767   if (!t)
2768     return false;
2769
2770   if (TREE_CODE (t) == FUNCTION_DECL)
2771     return DECL_LANG_SPECIFIC (t)
2772            && DECL_TEMPLATE_INSTANTIATION (t)
2773            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2774   else if (CLASS_TYPE_P (t))
2775     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2776            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2777   return false;
2778 }
2779
2780 /* Return true if PARM is a template template parameter.  */
2781
2782 bool
2783 template_template_parameter_p (const_tree parm)
2784 {
2785   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2786 }
2787
2788 /* Return the template parameters of T if T is a
2789    primary template instantiation, NULL otherwise.  */
2790
2791 tree
2792 get_primary_template_innermost_parameters (const_tree t)
2793 {
2794   tree parms = NULL, template_info = NULL;
2795
2796   if ((template_info = get_template_info (t))
2797       && primary_template_instantiation_p (t))
2798     parms = INNERMOST_TEMPLATE_PARMS
2799         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2800
2801   return parms;
2802 }
2803
2804 /* Returns the template arguments of T if T is a template instantiation,
2805    NULL otherwise.  */
2806
2807 tree
2808 get_template_innermost_arguments (const_tree t)
2809 {
2810   tree args = NULL, template_info = NULL;
2811
2812   if ((template_info = get_template_info (t))
2813       && TI_ARGS (template_info))
2814     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2815
2816   return args;
2817 }
2818
2819 /* Return the argument pack elements of T if T is a template argument pack,
2820    NULL otherwise.  */
2821
2822 tree
2823 get_template_argument_pack_elems (const_tree t)
2824 {
2825   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2826       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2827     return NULL;
2828
2829   return ARGUMENT_PACK_ARGS (t);
2830 }
2831
2832 /* Structure used to track the progress of find_parameter_packs_r.  */
2833 struct find_parameter_pack_data 
2834 {
2835   /* TREE_LIST that will contain all of the parameter packs found by
2836      the traversal.  */
2837   tree* parameter_packs;
2838
2839   /* Set of AST nodes that have been visited by the traversal.  */
2840   struct pointer_set_t *visited;
2841 };
2842
2843 /* Identifies all of the argument packs that occur in a template
2844    argument and appends them to the TREE_LIST inside DATA, which is a
2845    find_parameter_pack_data structure. This is a subroutine of
2846    make_pack_expansion and uses_parameter_packs.  */
2847 static tree
2848 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2849 {
2850   tree t = *tp;
2851   struct find_parameter_pack_data* ppd = 
2852     (struct find_parameter_pack_data*)data;
2853   bool parameter_pack_p = false;
2854
2855   /* Identify whether this is a parameter pack or not.  */
2856   switch (TREE_CODE (t))
2857     {
2858     case TEMPLATE_PARM_INDEX:
2859       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2860         parameter_pack_p = true;
2861       break;
2862
2863     case TEMPLATE_TYPE_PARM:
2864     case TEMPLATE_TEMPLATE_PARM:
2865       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2866         parameter_pack_p = true;
2867       break;
2868
2869     case PARM_DECL:
2870       if (FUNCTION_PARAMETER_PACK_P (t))
2871         {
2872           /* We don't want to walk into the type of a PARM_DECL,
2873              because we don't want to see the type parameter pack.  */
2874           *walk_subtrees = 0;
2875           parameter_pack_p = true;
2876         }
2877       break;
2878
2879     default:
2880       /* Not a parameter pack.  */
2881       break;
2882     }
2883
2884   if (parameter_pack_p)
2885     {
2886       /* Add this parameter pack to the list.  */
2887       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2888     }
2889
2890   if (TYPE_P (t))
2891     cp_walk_tree (&TYPE_CONTEXT (t), 
2892                   &find_parameter_packs_r, ppd, ppd->visited);
2893
2894   /* This switch statement will return immediately if we don't find a
2895      parameter pack.  */
2896   switch (TREE_CODE (t)) 
2897     {
2898     case TEMPLATE_PARM_INDEX:
2899       return NULL_TREE;
2900
2901     case BOUND_TEMPLATE_TEMPLATE_PARM:
2902       /* Check the template itself.  */
2903       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2904                     &find_parameter_packs_r, ppd, ppd->visited);
2905       /* Check the template arguments.  */
2906       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2907                     ppd->visited);
2908       *walk_subtrees = 0;
2909       return NULL_TREE;
2910
2911     case TEMPLATE_TYPE_PARM:
2912     case TEMPLATE_TEMPLATE_PARM:
2913       return NULL_TREE;
2914
2915     case PARM_DECL:
2916       return NULL_TREE;
2917
2918     case RECORD_TYPE:
2919       if (TYPE_PTRMEMFUNC_P (t))
2920         return NULL_TREE;
2921       /* Fall through.  */
2922
2923     case UNION_TYPE:
2924     case ENUMERAL_TYPE:
2925       if (TYPE_TEMPLATE_INFO (t))
2926         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2927                       &find_parameter_packs_r, ppd, ppd->visited);
2928
2929       *walk_subtrees = 0;
2930       return NULL_TREE;
2931
2932     case TEMPLATE_DECL:
2933       cp_walk_tree (&TREE_TYPE (t),
2934                     &find_parameter_packs_r, ppd, ppd->visited);
2935       return NULL_TREE;
2936  
2937     case TYPENAME_TYPE:
2938       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2939                    ppd, ppd->visited);
2940       *walk_subtrees = 0;
2941       return NULL_TREE;
2942       
2943     case TYPE_PACK_EXPANSION:
2944     case EXPR_PACK_EXPANSION:
2945       *walk_subtrees = 0;
2946       return NULL_TREE;
2947
2948     case INTEGER_TYPE:
2949       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2950                     ppd, ppd->visited);
2951       *walk_subtrees = 0;
2952       return NULL_TREE;
2953
2954     case IDENTIFIER_NODE:
2955       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2956                     ppd->visited);
2957       *walk_subtrees = 0;
2958       return NULL_TREE;
2959
2960     default:
2961       return NULL_TREE;
2962     }
2963
2964   return NULL_TREE;
2965 }
2966
2967 /* Determines if the expression or type T uses any parameter packs.  */
2968 bool
2969 uses_parameter_packs (tree t)
2970 {
2971   tree parameter_packs = NULL_TREE;
2972   struct find_parameter_pack_data ppd;
2973   ppd.parameter_packs = &parameter_packs;
2974   ppd.visited = pointer_set_create ();
2975   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2976   pointer_set_destroy (ppd.visited);
2977   return parameter_packs != NULL_TREE;
2978 }
2979
2980 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2981    representation a base-class initializer into a parameter pack
2982    expansion. If all goes well, the resulting node will be an
2983    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2984    respectively.  */
2985 tree 
2986 make_pack_expansion (tree arg)
2987 {
2988   tree result;
2989   tree parameter_packs = NULL_TREE;
2990   bool for_types = false;
2991   struct find_parameter_pack_data ppd;
2992
2993   if (!arg || arg == error_mark_node)
2994     return arg;
2995
2996   if (TREE_CODE (arg) == TREE_LIST)
2997     {
2998       /* The only time we will see a TREE_LIST here is for a base
2999          class initializer.  In this case, the TREE_PURPOSE will be a
3000          _TYPE node (representing the base class expansion we're
3001          initializing) and the TREE_VALUE will be a TREE_LIST
3002          containing the initialization arguments. 
3003
3004          The resulting expansion looks somewhat different from most
3005          expansions. Rather than returning just one _EXPANSION, we
3006          return a TREE_LIST whose TREE_PURPOSE is a
3007          TYPE_PACK_EXPANSION containing the bases that will be
3008          initialized.  The TREE_VALUE will be identical to the
3009          original TREE_VALUE, which is a list of arguments that will
3010          be passed to each base.  We do not introduce any new pack
3011          expansion nodes into the TREE_VALUE (although it is possible
3012          that some already exist), because the TREE_PURPOSE and
3013          TREE_VALUE all need to be expanded together with the same
3014          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3015          resulting TREE_PURPOSE will mention the parameter packs in
3016          both the bases and the arguments to the bases.  */
3017       tree purpose;
3018       tree value;
3019       tree parameter_packs = NULL_TREE;
3020
3021       /* Determine which parameter packs will be used by the base
3022          class expansion.  */
3023       ppd.visited = pointer_set_create ();
3024       ppd.parameter_packs = &parameter_packs;
3025       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3026                     &ppd, ppd.visited);
3027
3028       if (parameter_packs == NULL_TREE)
3029         {
3030           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3031           pointer_set_destroy (ppd.visited);
3032           return error_mark_node;
3033         }
3034
3035       if (TREE_VALUE (arg) != void_type_node)
3036         {
3037           /* Collect the sets of parameter packs used in each of the
3038              initialization arguments.  */
3039           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3040             {
3041               /* Determine which parameter packs will be expanded in this
3042                  argument.  */
3043               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3044                             &ppd, ppd.visited);
3045             }
3046         }
3047
3048       pointer_set_destroy (ppd.visited);
3049
3050       /* Create the pack expansion type for the base type.  */
3051       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3052       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3053       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3054
3055       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3056          they will rarely be compared to anything.  */
3057       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3058
3059       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3060     }
3061
3062   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3063     for_types = true;
3064
3065   /* Build the PACK_EXPANSION_* node.  */
3066   result = for_types
3067      ? cxx_make_type (TYPE_PACK_EXPANSION)
3068      : make_node (EXPR_PACK_EXPANSION);
3069   SET_PACK_EXPANSION_PATTERN (result, arg);
3070   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3071     {
3072       /* Propagate type and const-expression information.  */
3073       TREE_TYPE (result) = TREE_TYPE (arg);
3074       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3075     }
3076   else
3077     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3078        they will rarely be compared to anything.  */
3079     SET_TYPE_STRUCTURAL_EQUALITY (result);
3080
3081   /* Determine which parameter packs will be expanded.  */
3082   ppd.parameter_packs = &parameter_packs;
3083   ppd.visited = pointer_set_create ();
3084   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3085   pointer_set_destroy (ppd.visited);
3086
3087   /* Make sure we found some parameter packs.  */
3088   if (parameter_packs == NULL_TREE)
3089     {
3090       if (TYPE_P (arg))
3091         error ("expansion pattern %<%T%> contains no argument packs", arg);
3092       else
3093         error ("expansion pattern %<%E%> contains no argument packs", arg);
3094       return error_mark_node;
3095     }
3096   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3097
3098   return result;
3099 }
3100
3101 /* Checks T for any "bare" parameter packs, which have not yet been
3102    expanded, and issues an error if any are found. This operation can
3103    only be done on full expressions or types (e.g., an expression
3104    statement, "if" condition, etc.), because we could have expressions like:
3105
3106      foo(f(g(h(args)))...)
3107
3108    where "args" is a parameter pack. check_for_bare_parameter_packs
3109    should not be called for the subexpressions args, h(args),
3110    g(h(args)), or f(g(h(args))), because we would produce erroneous
3111    error messages. 
3112
3113    Returns TRUE and emits an error if there were bare parameter packs,
3114    returns FALSE otherwise.  */
3115 bool 
3116 check_for_bare_parameter_packs (tree t)
3117 {
3118   tree parameter_packs = NULL_TREE;
3119   struct find_parameter_pack_data ppd;
3120
3121   if (!processing_template_decl || !t || t == error_mark_node)
3122     return false;
3123
3124   if (TREE_CODE (t) == TYPE_DECL)
3125     t = TREE_TYPE (t);
3126
3127   ppd.parameter_packs = &parameter_packs;
3128   ppd.visited = pointer_set_create ();
3129   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3130   pointer_set_destroy (ppd.visited);
3131
3132   if (parameter_packs) 
3133     {
3134       error ("parameter packs not expanded with %<...%>:");
3135       while (parameter_packs)
3136         {
3137           tree pack = TREE_VALUE (parameter_packs);
3138           tree name = NULL_TREE;
3139
3140           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3141               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3142             name = TYPE_NAME (pack);
3143           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3144             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3145           else
3146             name = DECL_NAME (pack);
3147
3148           if (name)
3149             inform (input_location, "        %qD", name);
3150           else
3151             inform (input_location, "        <anonymous>");
3152
3153           parameter_packs = TREE_CHAIN (parameter_packs);
3154         }
3155
3156       return true;
3157     }
3158
3159   return false;
3160 }
3161
3162 /* Expand any parameter packs that occur in the template arguments in
3163    ARGS.  */
3164 tree
3165 expand_template_argument_pack (tree args)
3166 {
3167   tree result_args = NULL_TREE;
3168   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3169   int num_result_args = -1;
3170
3171   /* First, determine if we need to expand anything, and the number of
3172      slots we'll need.  */
3173   for (in_arg = 0; in_arg < nargs; ++in_arg)
3174     {
3175       tree arg = TREE_VEC_ELT (args, in_arg);
3176       if (arg == NULL_TREE)
3177         return args;
3178       if (ARGUMENT_PACK_P (arg))
3179         {
3180           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3181           if (num_result_args < 0)
3182             num_result_args = in_arg + num_packed;
3183           else
3184             num_result_args += num_packed;
3185         }
3186       else
3187         {
3188           if (num_result_args >= 0)
3189             num_result_args++;
3190         }
3191     }
3192
3193   /* If no expansion is necessary, we're done.  */
3194   if (num_result_args < 0)
3195     return args;
3196
3197   /* Expand arguments.  */
3198   result_args = make_tree_vec (num_result_args);
3199   for (in_arg = 0; in_arg < nargs; ++in_arg)
3200     {
3201       tree arg = TREE_VEC_ELT (args, in_arg);
3202       if (ARGUMENT_PACK_P (arg))
3203         {
3204           tree packed = ARGUMENT_PACK_ARGS (arg);
3205           int i, num_packed = TREE_VEC_LENGTH (packed);
3206           for (i = 0; i < num_packed; ++i, ++out_arg)
3207             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3208         }
3209       else
3210         {
3211           TREE_VEC_ELT (result_args, out_arg) = arg;
3212           ++out_arg;
3213         }
3214     }
3215
3216   return result_args;
3217 }
3218
3219 /* Checks if DECL shadows a template parameter.
3220
3221    [temp.local]: A template-parameter shall not be redeclared within its
3222    scope (including nested scopes).
3223
3224    Emits an error and returns TRUE if the DECL shadows a parameter,
3225    returns FALSE otherwise.  */
3226
3227 bool
3228 check_template_shadow (tree decl)
3229 {
3230   tree olddecl;
3231
3232   /* If we're not in a template, we can't possibly shadow a template
3233      parameter.  */
3234   if (!current_template_parms)
3235     return true;
3236
3237   /* Figure out what we're shadowing.  */
3238   if (TREE_CODE (decl) == OVERLOAD)
3239     decl = OVL_CURRENT (decl);
3240   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3241
3242   /* If there's no previous binding for this name, we're not shadowing
3243      anything, let alone a template parameter.  */
3244   if (!olddecl)
3245     return true;
3246
3247   /* If we're not shadowing a template parameter, we're done.  Note
3248      that OLDDECL might be an OVERLOAD (or perhaps even an
3249      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3250      node.  */
3251   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3252     return true;
3253
3254   /* We check for decl != olddecl to avoid bogus errors for using a
3255      name inside a class.  We check TPFI to avoid duplicate errors for
3256      inline member templates.  */
3257   if (decl == olddecl
3258       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3259     return true;
3260
3261   error ("declaration of %q+#D", decl);
3262   error (" shadows template parm %q+#D", olddecl);
3263   return false;
3264 }
3265
3266 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3267    ORIG_LEVEL, DECL, and TYPE.  */
3268
3269 static tree
3270 build_template_parm_index (int index,
3271                            int level,
3272                            int orig_level,
3273                            tree decl,
3274                            tree type)
3275 {
3276   tree t = make_node (TEMPLATE_PARM_INDEX);
3277   TEMPLATE_PARM_IDX (t) = index;
3278   TEMPLATE_PARM_LEVEL (t) = level;
3279   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3280   TEMPLATE_PARM_DECL (t) = decl;
3281   TREE_TYPE (t) = type;
3282   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3283   TREE_READONLY (t) = TREE_READONLY (decl);
3284
3285   return t;
3286 }
3287
3288 /* Find the canonical type parameter for the given template type
3289    parameter.  Returns the canonical type parameter, which may be TYPE
3290    if no such parameter existed.  */
3291 static tree
3292 canonical_type_parameter (tree type)
3293 {
3294   tree list;
3295   int idx = TEMPLATE_TYPE_IDX (type);
3296   if (!canonical_template_parms)
3297     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3298
3299   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3300     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3301
3302   list = VEC_index (tree, canonical_template_parms, idx);
3303   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3304     list = TREE_CHAIN (list);
3305
3306   if (list)
3307     return TREE_VALUE (list);
3308   else
3309     {
3310       VEC_replace(tree, canonical_template_parms, idx,
3311                   tree_cons (NULL_TREE, type, 
3312                              VEC_index (tree, canonical_template_parms, idx)));
3313       return type;
3314     }
3315 }
3316
3317 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3318    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3319    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3320    new one is created.  */
3321
3322 static tree
3323 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3324                             tsubst_flags_t complain)
3325 {
3326   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3327       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3328           != TEMPLATE_PARM_LEVEL (index) - levels))
3329     {
3330       tree orig_decl = TEMPLATE_PARM_DECL (index);
3331       tree decl, t;
3332
3333       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3334                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3335       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3336       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3337       DECL_ARTIFICIAL (decl) = 1;
3338       SET_DECL_TEMPLATE_PARM_P (decl);
3339
3340       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3341                                      TEMPLATE_PARM_LEVEL (index) - levels,
3342                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3343                                      decl, type);
3344       TEMPLATE_PARM_DESCENDANTS (index) = t;
3345       TEMPLATE_PARM_PARAMETER_PACK (t) 
3346         = TEMPLATE_PARM_PARAMETER_PACK (index);
3347
3348         /* Template template parameters need this.  */
3349       if (TREE_CODE (decl) == TEMPLATE_DECL)
3350         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3351           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3352            args, complain);
3353     }
3354
3355   return TEMPLATE_PARM_DESCENDANTS (index);
3356 }
3357
3358 /* Process information from new template parameter PARM and append it to the
3359    LIST being built.  This new parameter is a non-type parameter iff
3360    IS_NON_TYPE is true. This new parameter is a parameter
3361    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3362    PARM_LOC.  */
3363
3364 tree
3365 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3366                        bool is_parameter_pack)
3367 {
3368   tree decl = 0;
3369   tree defval;
3370   tree err_parm_list;
3371   int idx = 0;
3372
3373   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3374   defval = TREE_PURPOSE (parm);
3375
3376   if (list)
3377     {
3378       tree p = tree_last (list);
3379
3380       if (p && TREE_VALUE (p) != error_mark_node)
3381         {
3382           p = TREE_VALUE (p);
3383           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3384             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3385           else
3386             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3387         }
3388
3389       ++idx;
3390     }
3391   else
3392     idx = 0;
3393
3394   if (is_non_type)
3395     {
3396       parm = TREE_VALUE (parm);
3397
3398       SET_DECL_TEMPLATE_PARM_P (parm);
3399
3400       if (TREE_TYPE (parm) == error_mark_node)
3401         {
3402           err_parm_list = build_tree_list (defval, parm);
3403           TREE_VALUE (err_parm_list) = error_mark_node;
3404            return chainon (list, err_parm_list);
3405         }
3406       else
3407       {
3408         /* [temp.param]
3409
3410            The top-level cv-qualifiers on the template-parameter are
3411            ignored when determining its type.  */
3412         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3413         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3414           {
3415             err_parm_list = build_tree_list (defval, parm);
3416             TREE_VALUE (err_parm_list) = error_mark_node;
3417              return chainon (list, err_parm_list);
3418           }
3419
3420         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3421           {
3422             /* This template parameter is not a parameter pack, but it
3423                should be. Complain about "bare" parameter packs.  */
3424             check_for_bare_parameter_packs (TREE_TYPE (parm));
3425             
3426             /* Recover by calling this a parameter pack.  */
3427             is_parameter_pack = true;
3428           }
3429       }
3430
3431       /* A template parameter is not modifiable.  */
3432       TREE_CONSTANT (parm) = 1;
3433       TREE_READONLY (parm) = 1;
3434       decl = build_decl (parm_loc,
3435                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3436       TREE_CONSTANT (decl) = 1;
3437       TREE_READONLY (decl) = 1;
3438       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3439         = build_template_parm_index (idx, processing_template_decl,
3440                                      processing_template_decl,
3441                                      decl, TREE_TYPE (parm));
3442
3443       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3444         = is_parameter_pack;
3445     }
3446   else
3447     {
3448       tree t;
3449       parm = TREE_VALUE (TREE_VALUE (parm));
3450
3451       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3452         {
3453           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3454           /* This is for distinguishing between real templates and template
3455              template parameters */
3456           TREE_TYPE (parm) = t;
3457           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3458           decl = parm;
3459         }
3460       else
3461         {
3462           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3463           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3464           decl = build_decl (parm_loc,
3465                              TYPE_DECL, parm, t);
3466         }
3467
3468       TYPE_NAME (t) = decl;
3469       TYPE_STUB_DECL (t) = decl;
3470       parm = decl;
3471       TEMPLATE_TYPE_PARM_INDEX (t)
3472         = build_template_parm_index (idx, processing_template_decl,
3473                                      processing_template_decl,
3474                                      decl, TREE_TYPE (parm));
3475       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3476       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3477     }
3478   DECL_ARTIFICIAL (decl) = 1;
3479   SET_DECL_TEMPLATE_PARM_P (decl);
3480   pushdecl (decl);
3481   parm = build_tree_list (defval, parm);
3482   return chainon (list, parm);
3483 }
3484
3485 /* The end of a template parameter list has been reached.  Process the
3486    tree list into a parameter vector, converting each parameter into a more
3487    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3488    as PARM_DECLs.  */
3489
3490 tree
3491 end_template_parm_list (tree parms)
3492 {
3493   int nparms;
3494   tree parm, next;
3495   tree saved_parmlist = make_tree_vec (list_length (parms));
3496
3497   current_template_parms
3498     = tree_cons (size_int (processing_template_decl),
3499                  saved_parmlist, current_template_parms);
3500
3501   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3502     {
3503       next = TREE_CHAIN (parm);
3504       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3505       TREE_CHAIN (parm) = NULL_TREE;
3506     }
3507
3508   --processing_template_parmlist;
3509
3510   return saved_parmlist;
3511 }
3512
3513 /* end_template_decl is called after a template declaration is seen.  */
3514
3515 void
3516 end_template_decl (void)
3517 {
3518   reset_specialization ();
3519
3520   if (! processing_template_decl)
3521     return;
3522
3523   /* This matches the pushlevel in begin_template_parm_list.  */
3524   finish_scope ();
3525
3526   --processing_template_decl;
3527   current_template_parms = TREE_CHAIN (current_template_parms);
3528 }
3529
3530 /* Within the declaration of a template, return all levels of template
3531    parameters that apply.  The template parameters are represented as
3532    a TREE_VEC, in the form documented in cp-tree.h for template
3533    arguments.  */
3534
3535 static tree
3536 current_template_args (void)
3537 {
3538   tree header;
3539   tree args = NULL_TREE;
3540   int length = TMPL_PARMS_DEPTH (current_template_parms);
3541   int l = length;
3542
3543   /* If there is only one level of template parameters, we do not
3544      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3545      TREE_VEC containing the arguments.  */
3546   if (length > 1)
3547     args = make_tree_vec (length);
3548
3549   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3550     {
3551       tree a = copy_node (TREE_VALUE (header));
3552       int i;
3553
3554       TREE_TYPE (a) = NULL_TREE;
3555       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3556         {
3557           tree t = TREE_VEC_ELT (a, i);
3558
3559           /* T will be a list if we are called from within a
3560              begin/end_template_parm_list pair, but a vector directly
3561              if within a begin/end_member_template_processing pair.  */
3562           if (TREE_CODE (t) == TREE_LIST)
3563             {
3564               t = TREE_VALUE (t);
3565
3566               if (!error_operand_p (t))
3567                 {
3568                   if (TREE_CODE (t) == TYPE_DECL
3569                       || TREE_CODE (t) == TEMPLATE_DECL)
3570                     {
3571                       t = TREE_TYPE (t);
3572                       
3573                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3574                         {
3575                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3576                              with a single element, which expands T.  */
3577                           tree vec = make_tree_vec (1);
3578                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3579                           
3580                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3581                           SET_ARGUMENT_PACK_ARGS (t, vec);
3582                         }
3583                     }
3584                   else
3585                     {
3586                       t = DECL_INITIAL (t);
3587                       
3588                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3589                         {
3590                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3591                              with a single element, which expands T.  */
3592                           tree vec = make_tree_vec (1);
3593                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3594                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3595                           
3596                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3597                           SET_ARGUMENT_PACK_ARGS (t, vec);
3598                           TREE_TYPE (t) = type;
3599                         }
3600                     }
3601                   TREE_VEC_ELT (a, i) = t;
3602                 }
3603             }
3604         }
3605
3606       if (length > 1)
3607         TREE_VEC_ELT (args, --l) = a;
3608       else
3609         args = a;
3610     }
3611
3612   return args;
3613 }
3614
3615 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3616    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3617    a member template.  Used by push_template_decl below.  */
3618
3619 static tree
3620 build_template_decl (tree decl, tree parms, bool member_template_p)
3621 {
3622   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3623   DECL_TEMPLATE_PARMS (tmpl) = parms;
3624   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3625   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3626
3627   return tmpl;
3628 }
3629
3630 struct template_parm_data
3631 {
3632   /* The level of the template parameters we are currently
3633      processing.  */
3634   int level;
3635
3636   /* The index of the specialization argument we are currently
3637      processing.  */
3638   int current_arg;
3639
3640   /* An array whose size is the number of template parameters.  The
3641      elements are nonzero if the parameter has been used in any one
3642      of the arguments processed so far.  */
3643   int* parms;
3644
3645   /* An array whose size is the number of template arguments.  The
3646      elements are nonzero if the argument makes use of template
3647      parameters of this level.  */
3648   int* arg_uses_template_parms;
3649 };
3650
3651 /* Subroutine of push_template_decl used to see if each template
3652    parameter in a partial specialization is used in the explicit
3653    argument list.  If T is of the LEVEL given in DATA (which is
3654    treated as a template_parm_data*), then DATA->PARMS is marked
3655    appropriately.  */
3656
3657 static int
3658 mark_template_parm (tree t, void* data)
3659 {
3660   int level;
3661   int idx;
3662   struct template_parm_data* tpd = (struct template_parm_data*) data;
3663
3664   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3665     {
3666       level = TEMPLATE_PARM_LEVEL (t);
3667       idx = TEMPLATE_PARM_IDX (t);
3668     }
3669   else
3670     {
3671       level = TEMPLATE_TYPE_LEVEL (t);
3672       idx = TEMPLATE_TYPE_IDX (t);
3673     }
3674
3675   if (level == tpd->level)
3676     {
3677       tpd->parms[idx] = 1;
3678       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3679     }
3680
3681   /* Return zero so that for_each_template_parm will continue the
3682      traversal of the tree; we want to mark *every* template parm.  */
3683   return 0;
3684 }
3685
3686 /* Process the partial specialization DECL.  */
3687
3688 static tree
3689 process_partial_specialization (tree decl)
3690 {
3691   tree type = TREE_TYPE (decl);
3692   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3693   tree specargs = CLASSTYPE_TI_ARGS (type);
3694   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3695   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3696   tree inner_parms;
3697   int nargs = TREE_VEC_LENGTH (inner_args);
3698   int ntparms;
3699   int  i;
3700   int did_error_intro = 0;
3701   struct template_parm_data tpd;
3702   struct template_parm_data tpd2;
3703
3704   gcc_assert (current_template_parms);
3705
3706   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3707   ntparms = TREE_VEC_LENGTH (inner_parms);
3708
3709   /* We check that each of the template parameters given in the
3710      partial specialization is used in the argument list to the
3711      specialization.  For example:
3712
3713        template <class T> struct S;
3714        template <class T> struct S<T*>;
3715
3716      The second declaration is OK because `T*' uses the template
3717      parameter T, whereas
3718
3719        template <class T> struct S<int>;
3720
3721      is no good.  Even trickier is:
3722
3723        template <class T>
3724        struct S1
3725        {
3726           template <class U>
3727           struct S2;
3728           template <class U>
3729           struct S2<T>;
3730        };
3731
3732      The S2<T> declaration is actually invalid; it is a
3733      full-specialization.  Of course,
3734
3735           template <class U>
3736           struct S2<T (*)(U)>;
3737
3738      or some such would have been OK.  */
3739   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3740   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3741   memset (tpd.parms, 0, sizeof (int) * ntparms);
3742
3743   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3744   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3745   for (i = 0; i < nargs; ++i)
3746     {
3747       tpd.current_arg = i;
3748       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3749                               &mark_template_parm,
3750                               &tpd,
3751                               NULL,
3752                               /*include_nondeduced_p=*/false);
3753     }
3754   for (i = 0; i < ntparms; ++i)
3755     if (tpd.parms[i] == 0)
3756       {
3757         /* One of the template parms was not used in the
3758            specialization.  */
3759         if (!did_error_intro)
3760           {
3761             error ("template parameters not used in partial specialization:");
3762             did_error_intro = 1;
3763           }
3764
3765         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3766       }
3767
3768   /* [temp.class.spec]
3769
3770      The argument list of the specialization shall not be identical to
3771      the implicit argument list of the primary template.  */
3772   if (comp_template_args
3773       (inner_args,
3774        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3775                                                    (maintmpl)))))
3776     error ("partial specialization %qT does not specialize any template arguments", type);
3777
3778   /* [temp.class.spec]
3779
3780      A partially specialized non-type argument expression shall not
3781      involve template parameters of the partial specialization except
3782      when the argument expression is a simple identifier.
3783
3784      The type of a template parameter corresponding to a specialized
3785      non-type argument shall not be dependent on a parameter of the
3786      specialization. 
3787
3788      Also, we verify that pack expansions only occur at the
3789      end of the argument list.  */
3790   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3791   tpd2.parms = 0;
3792   for (i = 0; i < nargs; ++i)
3793     {
3794       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3795       tree arg = TREE_VEC_ELT (inner_args, i);
3796       tree packed_args = NULL_TREE;
3797       int j, len = 1;
3798
3799       if (ARGUMENT_PACK_P (arg))
3800         {
3801           /* Extract the arguments from the argument pack. We'll be
3802              iterating over these in the following loop.  */
3803           packed_args = ARGUMENT_PACK_ARGS (arg);
3804           len = TREE_VEC_LENGTH (packed_args);
3805         }
3806
3807       for (j = 0; j < len; j++)
3808         {
3809           if (packed_args)
3810             /* Get the Jth argument in the parameter pack.  */
3811             arg = TREE_VEC_ELT (packed_args, j);
3812
3813           if (PACK_EXPANSION_P (arg))
3814             {
3815               /* Pack expansions must come at the end of the
3816                  argument list.  */
3817               if ((packed_args && j < len - 1)
3818                   || (!packed_args && i < nargs - 1))
3819                 {
3820                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3821                     error ("parameter pack argument %qE must be at the "
3822                            "end of the template argument list", arg);
3823                   else
3824                     error ("parameter pack argument %qT must be at the "
3825                            "end of the template argument list", arg);
3826                 }
3827             }
3828
3829           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3830             /* We only care about the pattern.  */
3831             arg = PACK_EXPANSION_PATTERN (arg);
3832
3833           if (/* These first two lines are the `non-type' bit.  */
3834               !TYPE_P (arg)
3835               && TREE_CODE (arg) != TEMPLATE_DECL
3836               /* This next line is the `argument expression is not just a
3837                  simple identifier' condition and also the `specialized
3838                  non-type argument' bit.  */
3839               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3840             {
3841               if ((!packed_args && tpd.arg_uses_template_parms[i])
3842                   || (packed_args && uses_template_parms (arg)))
3843                 error ("template argument %qE involves template parameter(s)",
3844                        arg);
3845               else 
3846                 {
3847                   /* Look at the corresponding template parameter,
3848                      marking which template parameters its type depends
3849                      upon.  */
3850                   tree type = TREE_TYPE (parm);
3851
3852                   if (!tpd2.parms)
3853                     {
3854                       /* We haven't yet initialized TPD2.  Do so now.  */
3855                       tpd2.arg_uses_template_parms 
3856                         = (int *) alloca (sizeof (int) * nargs);
3857                       /* The number of parameters here is the number in the
3858                          main template, which, as checked in the assertion
3859                          above, is NARGS.  */
3860                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3861                       tpd2.level = 
3862                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3863                     }
3864
3865                   /* Mark the template parameters.  But this time, we're
3866                      looking for the template parameters of the main
3867                      template, not in the specialization.  */
3868                   tpd2.current_arg = i;
3869                   tpd2.arg_uses_template_parms[i] = 0;
3870                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3871                   for_each_template_parm (type,
3872                                           &mark_template_parm,
3873                                           &tpd2,
3874                                           NULL,
3875                                           /*include_nondeduced_p=*/false);
3876
3877                   if (tpd2.arg_uses_template_parms [i])
3878                     {
3879                       /* The type depended on some template parameters.
3880                          If they are fully specialized in the
3881                          specialization, that's OK.  */
3882                       int j;
3883                       for (j = 0; j < nargs; ++j)
3884                         if (tpd2.parms[j] != 0
3885                             && tpd.arg_uses_template_parms [j])
3886                           {
3887                             error ("type %qT of template argument %qE depends "
3888                                    "on template parameter(s)", 
3889                                    type,
3890                                    arg);
3891                             break;
3892                           }
3893                     }
3894                 }
3895             }
3896         }
3897     }
3898
3899   /* We should only get here once.  */
3900   gcc_assert (!COMPLETE_TYPE_P (type));
3901
3902   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3903     = tree_cons (specargs, inner_parms,
3904                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3905   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3906   return decl;
3907 }
3908
3909 /* Check that a template declaration's use of default arguments and
3910    parameter packs is not invalid.  Here, PARMS are the template
3911    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3912    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3913    specialization.
3914    
3915
3916    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3917    declaration (but not a definition); 1 indicates a declaration, 2
3918    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3919    emitted for extraneous default arguments.
3920
3921    Returns TRUE if there were no errors found, FALSE otherwise. */
3922
3923 bool
3924 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3925                          int is_partial, int is_friend_decl)
3926 {
3927   const char *msg;
3928   int last_level_to_check;
3929   tree parm_level;
3930   bool no_errors = true;
3931
3932   /* [temp.param]
3933
3934      A default template-argument shall not be specified in a
3935      function template declaration or a function template definition, nor
3936      in the template-parameter-list of the definition of a member of a
3937      class template.  */
3938
3939   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3940     /* You can't have a function template declaration in a local
3941        scope, nor you can you define a member of a class template in a
3942        local scope.  */
3943     return true;
3944
3945   if (current_class_type
3946       && !TYPE_BEING_DEFINED (current_class_type)
3947       && DECL_LANG_SPECIFIC (decl)
3948       && DECL_DECLARES_FUNCTION_P (decl)
3949       /* If this is either a friend defined in the scope of the class
3950          or a member function.  */
3951       && (DECL_FUNCTION_MEMBER_P (decl)
3952           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3953           : DECL_FRIEND_CONTEXT (decl)
3954           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3955           : false)
3956       /* And, if it was a member function, it really was defined in
3957          the scope of the class.  */
3958       && (!DECL_FUNCTION_MEMBER_P (decl)
3959           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3960     /* We already checked these parameters when the template was
3961        declared, so there's no need to do it again now.  This function
3962        was defined in class scope, but we're processing it's body now
3963        that the class is complete.  */
3964     return true;
3965
3966   /* Core issue 226 (C++0x only): the following only applies to class
3967      templates.  */
3968   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3969     {
3970       /* [temp.param]
3971
3972          If a template-parameter has a default template-argument, all
3973          subsequent template-parameters shall have a default
3974          template-argument supplied.  */
3975       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3976         {
3977           tree inner_parms = TREE_VALUE (parm_level);
3978           int ntparms = TREE_VEC_LENGTH (inner_parms);
3979           int seen_def_arg_p = 0;
3980           int i;
3981
3982           for (i = 0; i < ntparms; ++i)
3983             {
3984               tree parm = TREE_VEC_ELT (inner_parms, i);
3985
3986               if (parm == error_mark_node)
3987                 continue;
3988
3989               if (TREE_PURPOSE (parm))
3990                 seen_def_arg_p = 1;
3991               else if (seen_def_arg_p
3992                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3993                 {
3994                   error ("no default argument for %qD", TREE_VALUE (parm));
3995                   /* For better subsequent error-recovery, we indicate that
3996                      there should have been a default argument.  */
3997                   TREE_PURPOSE (parm) = error_mark_node;
3998                   no_errors = false;
3999                 }
4000               else if (is_primary
4001                        && !is_partial
4002                        && !is_friend_decl
4003                        /* Don't complain about an enclosing partial
4004                           specialization.  */
4005                        && parm_level == parms
4006                        && TREE_CODE (decl) == TYPE_DECL
4007                        && i < ntparms - 1
4008                        && template_parameter_pack_p (TREE_VALUE (parm)))
4009                 {
4010                   /* A primary class template can only have one
4011                      parameter pack, at the end of the template
4012                      parameter list.  */
4013
4014                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4015                     error ("parameter pack %qE must be at the end of the"
4016                            " template parameter list", TREE_VALUE (parm));
4017                   else
4018                     error ("parameter pack %qT must be at the end of the"
4019                            " template parameter list", 
4020                            TREE_TYPE (TREE_VALUE (parm)));
4021
4022                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4023                     = error_mark_node;
4024                   no_errors = false;
4025                 }
4026             }
4027         }
4028     }
4029
4030   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4031       || is_partial 
4032       || !is_primary
4033       || is_friend_decl)
4034     /* For an ordinary class template, default template arguments are
4035        allowed at the innermost level, e.g.:
4036          template <class T = int>
4037          struct S {};
4038        but, in a partial specialization, they're not allowed even
4039        there, as we have in [temp.class.spec]:
4040
4041          The template parameter list of a specialization shall not
4042          contain default template argument values.
4043
4044        So, for a partial specialization, or for a function template
4045        (in C++98/C++03), we look at all of them.  */
4046     ;
4047   else
4048     /* But, for a primary class template that is not a partial
4049        specialization we look at all template parameters except the
4050        innermost ones.  */
4051     parms = TREE_CHAIN (parms);
4052
4053   /* Figure out what error message to issue.  */
4054   if (is_friend_decl == 2)
4055     msg = "default template arguments may not be used in function template friend re-declaration";
4056   else if (is_friend_decl)
4057     msg = "default template arguments may not be used in function template friend declarations";
4058   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4059     msg = ("default template arguments may not be used in function templates "
4060            "without -std=c++0x or -std=gnu++0x");
4061   else if (is_partial)
4062     msg = "default template arguments may not be used in partial specializations";
4063   else
4064     msg = "default argument for template parameter for class enclosing %qD";
4065
4066   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4067     /* If we're inside a class definition, there's no need to
4068        examine the parameters to the class itself.  On the one
4069        hand, they will be checked when the class is defined, and,
4070        on the other, default arguments are valid in things like:
4071          template <class T = double>
4072          struct S { template <class U> void f(U); };
4073        Here the default argument for `S' has no bearing on the
4074        declaration of `f'.  */
4075     last_level_to_check = template_class_depth (current_class_type) + 1;
4076   else
4077     /* Check everything.  */
4078     last_level_to_check = 0;
4079
4080   for (parm_level = parms;
4081        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4082        parm_level = TREE_CHAIN (parm_level))
4083     {
4084       tree inner_parms = TREE_VALUE (parm_level);
4085       int i;
4086       int ntparms;
4087
4088       ntparms = TREE_VEC_LENGTH (inner_parms);
4089       for (i = 0; i < ntparms; ++i)
4090         {
4091           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4092             continue;
4093
4094           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4095             {
4096               if (msg)
4097                 {
4098                   no_errors = false;
4099                   if (is_friend_decl == 2)
4100                     return no_errors;
4101
4102                   error (msg, decl);
4103                   msg = 0;
4104                 }
4105
4106               /* Clear out the default argument so that we are not
4107                  confused later.  */
4108               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4109             }
4110         }
4111
4112       /* At this point, if we're still interested in issuing messages,
4113          they must apply to classes surrounding the object declared.  */
4114       if (msg)
4115         msg = "default argument for template parameter for class enclosing %qD";
4116     }
4117
4118   return no_errors;
4119 }
4120
4121 /* Worker for push_template_decl_real, called via
4122    for_each_template_parm.  DATA is really an int, indicating the
4123    level of the parameters we are interested in.  If T is a template
4124    parameter of that level, return nonzero.  */
4125
4126 static int
4127 template_parm_this_level_p (tree t, void* data)
4128 {
4129   int this_level = *(int *)data;
4130   int level;
4131
4132   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4133     level = TEMPLATE_PARM_LEVEL (t);
4134   else
4135     level = TEMPLATE_TYPE_LEVEL (t);
4136   return level == this_level;
4137 }
4138
4139 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4140    parameters given by current_template_args, or reuses a
4141    previously existing one, if appropriate.  Returns the DECL, or an
4142    equivalent one, if it is replaced via a call to duplicate_decls.
4143
4144    If IS_FRIEND is true, DECL is a friend declaration.  */
4145
4146 tree
4147 push_template_decl_real (tree decl, bool is_friend)
4148 {
4149   tree tmpl;
4150   tree args;
4151   tree info;
4152   tree ctx;
4153   int primary;
4154   int is_partial;
4155   int new_template_p = 0;
4156   /* True if the template is a member template, in the sense of
4157      [temp.mem].  */
4158   bool member_template_p = false;
4159
4160   if (decl == error_mark_node || !current_template_parms)
4161     return error_mark_node;
4162
4163   /* See if this is a partial specialization.  */
4164   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4165                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4166                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4167
4168   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4169     is_friend = true;
4170
4171   if (is_friend)
4172     /* For a friend, we want the context of the friend function, not
4173        the type of which it is a friend.  */
4174     ctx = DECL_CONTEXT (decl);
4175   else if (CP_DECL_CONTEXT (decl)
4176            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4177     /* In the case of a virtual function, we want the class in which
4178        it is defined.  */
4179     ctx = CP_DECL_CONTEXT (decl);
4180   else
4181     /* Otherwise, if we're currently defining some class, the DECL
4182        is assumed to be a member of the class.  */
4183     ctx = current_scope ();
4184
4185   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4186     ctx = NULL_TREE;
4187
4188   if (!DECL_CONTEXT (decl))
4189     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4190
4191   /* See if this is a primary template.  */
4192   if (is_friend && ctx)
4193     /* A friend template that specifies a class context, i.e.
4194          template <typename T> friend void A<T>::f();
4195        is not primary.  */
4196     primary = 0;
4197   else
4198     primary = template_parm_scope_p ();
4199
4200   if (primary)
4201     {
4202       if (DECL_CLASS_SCOPE_P (decl))
4203         member_template_p = true;
4204       if (TREE_CODE (decl) == TYPE_DECL
4205           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4206         {
4207           error ("template class without a name");
4208           return error_mark_node;
4209         }
4210       else if (TREE_CODE (decl) == FUNCTION_DECL)
4211         {
4212           if (DECL_DESTRUCTOR_P (decl))
4213             {
4214               /* [temp.mem]
4215
4216                  A destructor shall not be a member template.  */
4217               error ("destructor %qD declared as member template", decl);
4218               return error_mark_node;
4219             }
4220           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4221               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4222                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4223                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4224                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4225                       == void_list_node)))
4226             {
4227               /* [basic.stc.dynamic.allocation]
4228
4229                  An allocation function can be a function
4230                  template. ... Template allocation functions shall
4231                  have two or more parameters.  */
4232               error ("invalid template declaration of %qD", decl);
4233               return error_mark_node;
4234             }
4235         }
4236       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4237                && CLASS_TYPE_P (TREE_TYPE (decl)))
4238         /* OK */;
4239       else
4240         {
4241           error ("template declaration of %q#D", decl);
4242           return error_mark_node;
4243         }
4244     }
4245
4246   /* Check to see that the rules regarding the use of default
4247      arguments are not being violated.  */
4248   check_default_tmpl_args (decl, current_template_parms,
4249                            primary, is_partial, /*is_friend_decl=*/0);
4250
4251   /* Ensure that there are no parameter packs in the type of this
4252      declaration that have not been expanded.  */
4253   if (TREE_CODE (decl) == FUNCTION_DECL)
4254     {
4255       /* Check each of the arguments individually to see if there are
4256          any bare parameter packs.  */
4257       tree type = TREE_TYPE (decl);
4258       tree arg = DECL_ARGUMENTS (decl);
4259       tree argtype = TYPE_ARG_TYPES (type);
4260
4261       while (arg && argtype)
4262         {
4263           if (!FUNCTION_PARAMETER_PACK_P (arg)
4264               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4265             {
4266             /* This is a PARM_DECL that contains unexpanded parameter
4267                packs. We have already complained about this in the
4268                check_for_bare_parameter_packs call, so just replace
4269                these types with ERROR_MARK_NODE.  */
4270               TREE_TYPE (arg) = error_mark_node;
4271               TREE_VALUE (argtype) = error_mark_node;
4272             }
4273
4274           arg = TREE_CHAIN (arg);
4275           argtype = TREE_CHAIN (argtype);
4276         }
4277
4278       /* Check for bare parameter packs in the return type and the
4279          exception specifiers.  */
4280       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4281         /* Errors were already issued, set return type to int
4282            as the frontend doesn't expect error_mark_node as
4283            the return type.  */
4284         TREE_TYPE (type) = integer_type_node;
4285       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4286         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4287     }
4288   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4289     {
4290       TREE_TYPE (decl) = error_mark_node;
4291       return error_mark_node;
4292     }
4293
4294   if (is_partial)
4295     return process_partial_specialization (decl);
4296
4297   args = current_template_args ();
4298
4299   if (!ctx
4300       || TREE_CODE (ctx) == FUNCTION_DECL
4301       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4302       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4303     {
4304       if (DECL_LANG_SPECIFIC (decl)
4305           && DECL_TEMPLATE_INFO (decl)
4306           && DECL_TI_TEMPLATE (decl))
4307         tmpl = DECL_TI_TEMPLATE (decl);
4308       /* If DECL is a TYPE_DECL for a class-template, then there won't
4309          be DECL_LANG_SPECIFIC.  The information equivalent to
4310          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4311       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4312                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4313                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4314         {
4315           /* Since a template declaration already existed for this
4316              class-type, we must be redeclaring it here.  Make sure
4317              that the redeclaration is valid.  */
4318           redeclare_class_template (TREE_TYPE (decl),
4319                                     current_template_parms);
4320           /* We don't need to create a new TEMPLATE_DECL; just use the
4321              one we already had.  */
4322           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4323         }
4324       else
4325         {
4326           tmpl = build_template_decl (decl, current_template_parms,
4327                                       member_template_p);
4328           new_template_p = 1;
4329
4330           if (DECL_LANG_SPECIFIC (decl)
4331               && DECL_TEMPLATE_SPECIALIZATION (decl))
4332             {
4333               /* A specialization of a member template of a template
4334                  class.  */
4335               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4336               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4337               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4338             }
4339         }
4340     }
4341   else
4342     {
4343       tree a, t, current, parms;
4344       int i;
4345       tree tinfo = get_template_info (decl);
4346
4347       if (!tinfo)
4348         {
4349           error ("template definition of non-template %q#D", decl);
4350           return error_mark_node;
4351         }
4352
4353       tmpl = TI_TEMPLATE (tinfo);
4354
4355       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4356           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4357           && DECL_TEMPLATE_SPECIALIZATION (decl)
4358           && DECL_MEMBER_TEMPLATE_P (tmpl))
4359         {
4360           tree new_tmpl;
4361
4362           /* The declaration is a specialization of a member
4363              template, declared outside the class.  Therefore, the
4364              innermost template arguments will be NULL, so we
4365              replace them with the arguments determined by the
4366              earlier call to check_explicit_specialization.  */
4367           args = DECL_TI_ARGS (decl);
4368
4369           new_tmpl
4370             = build_template_decl (decl, current_template_parms,
4371                                    member_template_p);
4372           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4373           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4374           DECL_TI_TEMPLATE (decl) = new_tmpl;
4375           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4376           DECL_TEMPLATE_INFO (new_tmpl)
4377             = build_template_info (tmpl, args);
4378
4379           register_specialization (new_tmpl,
4380                                    most_general_template (tmpl),
4381                                    args,
4382                                    is_friend, 0);
4383           return decl;
4384         }
4385
4386       /* Make sure the template headers we got make sense.  */
4387
4388       parms = DECL_TEMPLATE_PARMS (tmpl);
4389       i = TMPL_PARMS_DEPTH (parms);
4390       if (TMPL_ARGS_DEPTH (args) != i)
4391         {
4392           error ("expected %d levels of template parms for %q#D, got %d",
4393                  i, decl, TMPL_ARGS_DEPTH (args));
4394         }
4395       else
4396         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4397           {
4398             a = TMPL_ARGS_LEVEL (args, i);
4399             t = INNERMOST_TEMPLATE_PARMS (parms);
4400
4401             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4402               {
4403                 if (current == decl)
4404                   error ("got %d template parameters for %q#D",
4405                          TREE_VEC_LENGTH (a), decl);
4406                 else
4407                   error ("got %d template parameters for %q#T",
4408                          TREE_VEC_LENGTH (a), current);
4409                 error ("  but %d required", TREE_VEC_LENGTH (t));
4410                 return error_mark_node;
4411               }
4412
4413             if (current == decl)
4414               current = ctx;
4415             else
4416               current = (TYPE_P (current)
4417                          ? TYPE_CONTEXT (current)
4418                          : DECL_CONTEXT (current));
4419           }
4420
4421       /* Check that the parms are used in the appropriate qualifying scopes
4422          in the declarator.  */
4423       if (!comp_template_args
4424           (TI_ARGS (tinfo),
4425            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4426         {
4427           error ("\
4428 template arguments to %qD do not match original template %qD",
4429                  decl, DECL_TEMPLATE_RESULT (tmpl));
4430           if (!uses_template_parms (TI_ARGS (tinfo)))
4431             inform (input_location, "use template<> for an explicit specialization");
4432           /* Avoid crash in import_export_decl.  */
4433           DECL_INTERFACE_KNOWN (decl) = 1;
4434           return error_mark_node;
4435         }
4436     }
4437
4438   DECL_TEMPLATE_RESULT (tmpl) = decl;
4439   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4440
4441   /* Push template declarations for global functions and types.  Note
4442      that we do not try to push a global template friend declared in a
4443      template class; such a thing may well depend on the template
4444      parameters of the class.  */
4445   if (new_template_p && !ctx
4446       && !(is_friend && template_class_depth (current_class_type) > 0))
4447     {
4448       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4449       if (tmpl == error_mark_node)
4450         return error_mark_node;
4451
4452       /* Hide template friend classes that haven't been declared yet.  */
4453       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4454         {
4455           DECL_ANTICIPATED (tmpl) = 1;
4456           DECL_FRIEND_P (tmpl) = 1;
4457         }
4458     }
4459
4460   if (primary)
4461     {
4462       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4463       int i;
4464
4465       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4466       if (DECL_CONV_FN_P (tmpl))
4467         {
4468           int depth = TMPL_PARMS_DEPTH (parms);
4469
4470           /* It is a conversion operator. See if the type converted to
4471              depends on innermost template operands.  */
4472
4473           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4474                                          depth))
4475             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4476         }
4477
4478       /* Give template template parms a DECL_CONTEXT of the template
4479          for which they are a parameter.  */
4480       parms = INNERMOST_TEMPLATE_PARMS (parms);
4481       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4482         {
4483           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4484           if (TREE_CODE (parm) == TEMPLATE_DECL)
4485             DECL_CONTEXT (parm) = tmpl;
4486         }
4487     }
4488
4489   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4490      back to its most general template.  If TMPL is a specialization,
4491      ARGS may only have the innermost set of arguments.  Add the missing
4492      argument levels if necessary.  */
4493   if (DECL_TEMPLATE_INFO (tmpl))
4494     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4495
4496   info = build_template_info (tmpl, args);
4497
4498   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4499     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4500   else if (DECL_LANG_SPECIFIC (decl))
4501     DECL_TEMPLATE_INFO (decl) = info;
4502
4503   return DECL_TEMPLATE_RESULT (tmpl);
4504 }
4505
4506 tree
4507 push_template_decl (tree decl)
4508 {
4509   return push_template_decl_real (decl, false);
4510 }
4511
4512 /* Called when a class template TYPE is redeclared with the indicated
4513    template PARMS, e.g.:
4514
4515      template <class T> struct S;
4516      template <class T> struct S {};  */
4517
4518 bool
4519 redeclare_class_template (tree type, tree parms)
4520 {
4521   tree tmpl;
4522   tree tmpl_parms;
4523   int i;
4524
4525   if (!TYPE_TEMPLATE_INFO (type))
4526     {
4527       error ("%qT is not a template type", type);
4528       return false;
4529     }
4530
4531   tmpl = TYPE_TI_TEMPLATE (type);
4532   if (!PRIMARY_TEMPLATE_P (tmpl))
4533     /* The type is nested in some template class.  Nothing to worry
4534        about here; there are no new template parameters for the nested
4535        type.  */
4536     return true;
4537
4538   if (!parms)
4539     {
4540       error ("template specifiers not specified in declaration of %qD",
4541              tmpl);
4542       return false;
4543     }
4544
4545   parms = INNERMOST_TEMPLATE_PARMS (parms);
4546   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4547
4548   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4549     {
4550       error ("redeclared with %d template parameter(s)", 
4551              TREE_VEC_LENGTH (parms));
4552       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4553              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4554       return false;
4555     }
4556
4557   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4558     {
4559       tree tmpl_parm;
4560       tree parm;
4561       tree tmpl_default;
4562       tree parm_default;
4563
4564       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4565           || TREE_VEC_ELT (parms, i) == error_mark_node)
4566         continue;
4567
4568       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4569       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4570       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4571       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4572
4573       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4574          TEMPLATE_DECL.  */
4575       if (tmpl_parm != error_mark_node
4576           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4577               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4578                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4579               || (TREE_CODE (tmpl_parm) != PARM_DECL
4580                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4581                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4582               || (TREE_CODE (tmpl_parm) == PARM_DECL
4583                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4584                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4585         {
4586           error ("template parameter %q+#D", tmpl_parm);
4587           error ("redeclared here as %q#D", parm);
4588           return false;
4589         }
4590
4591       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4592         {
4593           /* We have in [temp.param]:
4594
4595              A template-parameter may not be given default arguments
4596              by two different declarations in the same scope.  */
4597           error_at (input_location, "redefinition of default argument for %q#D", parm);
4598           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4599                   "original definition appeared here");
4600           return false;
4601         }
4602
4603       if (parm_default != NULL_TREE)
4604         /* Update the previous template parameters (which are the ones
4605            that will really count) with the new default value.  */
4606         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4607       else if (tmpl_default != NULL_TREE)
4608         /* Update the new parameters, too; they'll be used as the
4609            parameters for any members.  */
4610         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4611     }
4612
4613     return true;
4614 }
4615
4616 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4617    (possibly simplified) expression.  */
4618
4619 tree
4620 fold_non_dependent_expr (tree expr)
4621 {
4622   if (expr == NULL_TREE)
4623     return NULL_TREE;
4624
4625   /* If we're in a template, but EXPR isn't value dependent, simplify
4626      it.  We're supposed to treat:
4627
4628        template <typename T> void f(T[1 + 1]);
4629        template <typename T> void f(T[2]);
4630
4631      as two declarations of the same function, for example.  */
4632   if (processing_template_decl
4633       && !type_dependent_expression_p (expr)
4634       && !value_dependent_expression_p (expr))
4635     {
4636       HOST_WIDE_INT saved_processing_template_decl;
4637
4638       saved_processing_template_decl = processing_template_decl;
4639       processing_template_decl = 0;
4640       expr = tsubst_copy_and_build (expr,
4641                                     /*args=*/NULL_TREE,
4642                                     tf_error,
4643                                     /*in_decl=*/NULL_TREE,
4644                                     /*function_p=*/false,
4645                                     /*integral_constant_expression_p=*/true);
4646       processing_template_decl = saved_processing_template_decl;
4647     }
4648   return expr;
4649 }
4650
4651 /* EXPR is an expression which is used in a constant-expression context.
4652    For instance, it could be a VAR_DECL with a constant initializer.
4653    Extract the innermost constant expression.
4654
4655    This is basically a more powerful version of
4656    integral_constant_value, which can be used also in templates where
4657    initializers can maintain a syntactic rather than semantic form
4658    (even if they are non-dependent, for access-checking purposes).  */
4659
4660 static tree
4661 fold_decl_constant_value (tree expr)
4662 {
4663   tree const_expr = expr;
4664   do
4665     {
4666       expr = fold_non_dependent_expr (const_expr);
4667       const_expr = integral_constant_value (expr);
4668     }
4669   while (expr != const_expr);
4670
4671   return expr;
4672 }
4673
4674 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4675    must be a function or a pointer-to-function type, as specified
4676    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4677    and check that the resulting function has external linkage.  */
4678
4679 static tree
4680 convert_nontype_argument_function (tree type, tree expr)
4681 {
4682   tree fns = expr;
4683   tree fn, fn_no_ptr;
4684
4685   fn = instantiate_type (type, fns, tf_none);
4686   if (fn == error_mark_node)
4687     return error_mark_node;
4688
4689   fn_no_ptr = fn;
4690   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4691     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4692   if (TREE_CODE (fn_no_ptr) == BASELINK)
4693     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4694  
4695   /* [temp.arg.nontype]/1
4696
4697      A template-argument for a non-type, non-template template-parameter
4698      shall be one of:
4699      [...]
4700      -- the address of an object or function with external linkage.  */
4701   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4702     {
4703       error ("%qE is not a valid template argument for type %qT "
4704              "because function %qD has not external linkage",
4705              expr, type, fn_no_ptr);
4706       return NULL_TREE;
4707     }
4708
4709   return fn;
4710 }
4711
4712 /* Subroutine of convert_nontype_argument.
4713    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4714    Emit an error otherwise.  */
4715
4716 static bool
4717 check_valid_ptrmem_cst_expr (tree type, tree expr)
4718 {
4719   STRIP_NOPS (expr);
4720   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4721     return true;
4722   error ("%qE is not a valid template argument for type %qT",
4723          expr, type);
4724   error ("it must be a pointer-to-member of the form `&X::Y'");
4725   return false;
4726 }
4727
4728 /* Attempt to convert the non-type template parameter EXPR to the
4729    indicated TYPE.  If the conversion is successful, return the
4730    converted value.  If the conversion is unsuccessful, return
4731    NULL_TREE if we issued an error message, or error_mark_node if we
4732    did not.  We issue error messages for out-and-out bad template
4733    parameters, but not simply because the conversion failed, since we
4734    might be just trying to do argument deduction.  Both TYPE and EXPR
4735    must be non-dependent.
4736
4737    The conversion follows the special rules described in
4738    [temp.arg.nontype], and it is much more strict than an implicit
4739    conversion.
4740
4741    This function is called twice for each template argument (see
4742    lookup_template_class for a more accurate description of this
4743    problem). This means that we need to handle expressions which
4744    are not valid in a C++ source, but can be created from the
4745    first call (for instance, casts to perform conversions). These
4746    hacks can go away after we fix the double coercion problem.  */
4747
4748 static tree
4749 convert_nontype_argument (tree type, tree expr)
4750 {
4751   tree expr_type;
4752
4753   /* Detect immediately string literals as invalid non-type argument.
4754      This special-case is not needed for correctness (we would easily
4755      catch this later), but only to provide better diagnostic for this
4756      common user mistake. As suggested by DR 100, we do not mention
4757      linkage issues in the diagnostic as this is not the point.  */
4758   if (TREE_CODE (expr) == STRING_CST)
4759     {
4760       error ("%qE is not a valid template argument for type %qT "
4761              "because string literals can never be used in this context",
4762              expr, type);
4763       return NULL_TREE;
4764     }
4765
4766   /* If we are in a template, EXPR may be non-dependent, but still
4767      have a syntactic, rather than semantic, form.  For example, EXPR
4768      might be a SCOPE_REF, rather than the VAR_DECL to which the
4769      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4770      so that access checking can be performed when the template is
4771      instantiated -- but here we need the resolved form so that we can
4772      convert the argument.  */
4773   expr = fold_non_dependent_expr (expr);
4774   if (error_operand_p (expr))
4775     return error_mark_node;
4776   expr_type = TREE_TYPE (expr);
4777
4778   /* HACK: Due to double coercion, we can get a
4779      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4780      which is the tree that we built on the first call (see
4781      below when coercing to reference to object or to reference to
4782      function). We just strip everything and get to the arg.
4783      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4784      for examples.  */
4785   if (TREE_CODE (expr) == NOP_EXPR)
4786     {
4787       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4788         {
4789           /* ??? Maybe we could use convert_from_reference here, but we
4790              would need to relax its constraints because the NOP_EXPR
4791              could actually change the type to something more cv-qualified,
4792              and this is not folded by convert_from_reference.  */
4793           tree addr = TREE_OPERAND (expr, 0);
4794           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4795           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4796           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4797           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4798                       (TREE_TYPE (expr_type),
4799                        TREE_TYPE (TREE_TYPE (addr))));
4800
4801           expr = TREE_OPERAND (addr, 0);
4802           expr_type = TREE_TYPE (expr);
4803         }
4804
4805       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4806          parameter is a pointer to object, through decay and
4807          qualification conversion. Let's strip everything.  */
4808       else if (TYPE_PTROBV_P (type))
4809         {
4810           STRIP_NOPS (expr);
4811           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4812           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4813           /* Skip the ADDR_EXPR only if it is part of the decay for
4814              an array. Otherwise, it is part of the original argument
4815              in the source code.  */
4816           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4817             expr = TREE_OPERAND (expr, 0);
4818           expr_type = TREE_TYPE (expr);
4819         }
4820     }
4821
4822   /* [temp.arg.nontype]/5, bullet 1
4823
4824      For a non-type template-parameter of integral or enumeration type,
4825      integral promotions (_conv.prom_) and integral conversions
4826      (_conv.integral_) are applied.  */
4827   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4828     {
4829       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4830         return error_mark_node;
4831
4832       expr = fold_decl_constant_value (expr);
4833       /* Notice that there are constant expressions like '4 % 0' which
4834          do not fold into integer constants.  */
4835       if (TREE_CODE (expr) != INTEGER_CST)
4836         {
4837           error ("%qE is not a valid template argument for type %qT "
4838                  "because it is a non-constant expression", expr, type);
4839           return NULL_TREE;
4840         }
4841
4842       /* At this point, an implicit conversion does what we want,
4843          because we already know that the expression is of integral
4844          type.  */
4845       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4846       if (expr == error_mark_node)
4847         return error_mark_node;
4848
4849       /* Conversion was allowed: fold it to a bare integer constant.  */
4850       expr = fold (expr);
4851     }
4852   /* [temp.arg.nontype]/5, bullet 2
4853
4854      For a non-type template-parameter of type pointer to object,
4855      qualification conversions (_conv.qual_) and the array-to-pointer
4856      conversion (_conv.array_) are applied.  */
4857   else if (TYPE_PTROBV_P (type))
4858     {
4859       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4860
4861          A template-argument for a non-type, non-template template-parameter
4862          shall be one of: [...]
4863
4864          -- the name of a non-type template-parameter;
4865          -- the address of an object or function with external linkage, [...]
4866             expressed as "& id-expression" where the & is optional if the name
4867             refers to a function or array, or if the corresponding
4868             template-parameter is a reference.
4869
4870         Here, we do not care about functions, as they are invalid anyway
4871         for a parameter of type pointer-to-object.  */
4872
4873       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4874         /* Non-type template parameters are OK.  */
4875         ;
4876       else if (TREE_CODE (expr) != ADDR_EXPR
4877                && TREE_CODE (expr_type) != ARRAY_TYPE)
4878         {
4879           if (TREE_CODE (expr) == VAR_DECL)
4880             {
4881               error ("%qD is not a valid template argument "
4882                      "because %qD is a variable, not the address of "
4883                      "a variable",
4884                      expr, expr);
4885               return NULL_TREE;
4886             }
4887           /* Other values, like integer constants, might be valid
4888              non-type arguments of some other type.  */
4889           return error_mark_node;
4890         }
4891       else
4892         {
4893           tree decl;
4894
4895           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4896                   ? TREE_OPERAND (expr, 0) : expr);
4897           if (TREE_CODE (decl) != VAR_DECL)
4898             {
4899               error ("%qE is not a valid template argument of type %qT "
4900                      "because %qE is not a variable",
4901                      expr, type, decl);
4902               return NULL_TREE;
4903             }
4904           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4905             {
4906               error ("%qE is not a valid template argument of type %qT "
4907                      "because %qD does not have external linkage",
4908                      expr, type, decl);
4909               return NULL_TREE;
4910             }
4911         }
4912
4913       expr = decay_conversion (expr);
4914       if (expr == error_mark_node)
4915         return error_mark_node;
4916
4917       expr = perform_qualification_conversions (type, expr);
4918       if (expr == error_mark_node)
4919         return error_mark_node;
4920     }
4921   /* [temp.arg.nontype]/5, bullet 3
4922
4923      For a non-type template-parameter of type reference to object, no
4924      conversions apply. The type referred to by the reference may be more
4925      cv-qualified than the (otherwise identical) type of the
4926      template-argument. The template-parameter is bound directly to the
4927      template-argument, which must be an lvalue.  */
4928   else if (TYPE_REF_OBJ_P (type))
4929     {
4930       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4931                                                       expr_type))
4932         return error_mark_node;
4933
4934       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4935         {
4936           error ("%qE is not a valid template argument for type %qT "
4937                  "because of conflicts in cv-qualification", expr, type);
4938           return NULL_TREE;
4939         }
4940
4941       if (!real_lvalue_p (expr))
4942         {
4943           error ("%qE is not a valid template argument for type %qT "
4944                  "because it is not an lvalue", expr, type);
4945           return NULL_TREE;
4946         }
4947
4948       /* [temp.arg.nontype]/1
4949
4950          A template-argument for a non-type, non-template template-parameter
4951          shall be one of: [...]
4952
4953          -- the address of an object or function with external linkage.  */
4954       if (TREE_CODE (expr) == INDIRECT_REF
4955           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
4956         {
4957           expr = TREE_OPERAND (expr, 0);
4958           if (DECL_P (expr))
4959             {
4960               error ("%q#D is not a valid template argument for type %qT "
4961                      "because a reference variable does not have a constant "
4962                      "address", expr, type);
4963               return NULL_TREE;
4964             }
4965         }
4966
4967       if (!DECL_P (expr))
4968         {
4969           error ("%qE is not a valid template argument for type %qT "
4970                  "because it is not an object with external linkage",
4971                  expr, type);
4972           return NULL_TREE;
4973         }
4974
4975       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4976         {
4977           error ("%qE is not a valid template argument for type %qT "
4978                  "because object %qD has not external linkage",
4979                  expr, type, expr);
4980           return NULL_TREE;
4981         }
4982
4983       expr = build_nop (type, build_address (expr));
4984     }
4985   /* [temp.arg.nontype]/5, bullet 4
4986
4987      For a non-type template-parameter of type pointer to function, only
4988      the function-to-pointer conversion (_conv.func_) is applied. If the
4989      template-argument represents a set of overloaded functions (or a
4990      pointer to such), the matching function is selected from the set
4991      (_over.over_).  */
4992   else if (TYPE_PTRFN_P (type))
4993     {
4994       /* If the argument is a template-id, we might not have enough
4995          context information to decay the pointer.  */
4996       if (!type_unknown_p (expr_type))
4997         {
4998           expr = decay_conversion (expr);
4999           if (expr == error_mark_node)
5000             return error_mark_node;
5001         }
5002
5003       expr = convert_nontype_argument_function (type, expr);
5004       if (!expr || expr == error_mark_node)
5005         return expr;
5006
5007       if (TREE_CODE (expr) != ADDR_EXPR)
5008         {
5009           error ("%qE is not a valid template argument for type %qT", expr, type);
5010           error ("it must be the address of a function with external linkage");
5011           return NULL_TREE;
5012         }
5013     }
5014   /* [temp.arg.nontype]/5, bullet 5
5015
5016      For a non-type template-parameter of type reference to function, no
5017      conversions apply. If the template-argument represents a set of
5018      overloaded functions, the matching function is selected from the set
5019      (_over.over_).  */
5020   else if (TYPE_REFFN_P (type))
5021     {
5022       if (TREE_CODE (expr) == ADDR_EXPR)
5023         {
5024           error ("%qE is not a valid template argument for type %qT "
5025                  "because it is a pointer", expr, type);
5026           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5027           return NULL_TREE;
5028         }
5029
5030       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5031       if (!expr || expr == error_mark_node)
5032         return expr;
5033
5034       expr = build_nop (type, build_address (expr));
5035     }
5036   /* [temp.arg.nontype]/5, bullet 6
5037
5038      For a non-type template-parameter of type pointer to member function,
5039      no conversions apply. If the template-argument represents a set of
5040      overloaded member functions, the matching member function is selected
5041      from the set (_over.over_).  */
5042   else if (TYPE_PTRMEMFUNC_P (type))
5043     {
5044       expr = instantiate_type (type, expr, tf_none);
5045       if (expr == error_mark_node)
5046         return error_mark_node;
5047
5048       /* [temp.arg.nontype] bullet 1 says the pointer to member
5049          expression must be a pointer-to-member constant.  */
5050       if (!check_valid_ptrmem_cst_expr (type, expr))
5051         return error_mark_node;
5052
5053       /* There is no way to disable standard conversions in
5054          resolve_address_of_overloaded_function (called by
5055          instantiate_type). It is possible that the call succeeded by
5056          converting &B::I to &D::I (where B is a base of D), so we need
5057          to reject this conversion here.
5058
5059          Actually, even if there was a way to disable standard conversions,
5060          it would still be better to reject them here so that we can
5061          provide a superior diagnostic.  */
5062       if (!same_type_p (TREE_TYPE (expr), type))
5063         {
5064           /* Make sure we are just one standard conversion off.  */
5065           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5066           error ("%qE is not a valid template argument for type %qT "
5067                  "because it is of type %qT", expr, type,
5068                  TREE_TYPE (expr));
5069           inform (input_location, "standard conversions are not allowed in this context");
5070           return NULL_TREE;
5071         }
5072     }
5073   /* [temp.arg.nontype]/5, bullet 7
5074
5075      For a non-type template-parameter of type pointer to data member,
5076      qualification conversions (_conv.qual_) are applied.  */
5077   else if (TYPE_PTRMEM_P (type))
5078     {
5079       /* [temp.arg.nontype] bullet 1 says the pointer to member
5080          expression must be a pointer-to-member constant.  */
5081       if (!check_valid_ptrmem_cst_expr (type, expr))
5082         return error_mark_node;
5083
5084       expr = perform_qualification_conversions (type, expr);
5085       if (expr == error_mark_node)
5086         return expr;
5087     }
5088   /* A template non-type parameter must be one of the above.  */
5089   else
5090     gcc_unreachable ();
5091
5092   /* Sanity check: did we actually convert the argument to the
5093      right type?  */
5094   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5095   return expr;
5096 }
5097
5098 /* Subroutine of coerce_template_template_parms, which returns 1 if
5099    PARM_PARM and ARG_PARM match using the rule for the template
5100    parameters of template template parameters. Both PARM and ARG are
5101    template parameters; the rest of the arguments are the same as for
5102    coerce_template_template_parms.
5103  */
5104 static int
5105 coerce_template_template_parm (tree parm,
5106                               tree arg,
5107                               tsubst_flags_t complain,
5108                               tree in_decl,
5109                               tree outer_args)
5110 {
5111   if (arg == NULL_TREE || arg == error_mark_node
5112       || parm == NULL_TREE || parm == error_mark_node)
5113     return 0;
5114   
5115   if (TREE_CODE (arg) != TREE_CODE (parm))
5116     return 0;
5117   
5118   switch (TREE_CODE (parm))
5119     {
5120     case TEMPLATE_DECL:
5121       /* We encounter instantiations of templates like
5122          template <template <template <class> class> class TT>
5123          class C;  */
5124       {
5125         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5126         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5127         
5128         if (!coerce_template_template_parms
5129             (parmparm, argparm, complain, in_decl, outer_args))
5130           return 0;
5131       }
5132       /* Fall through.  */
5133       
5134     case TYPE_DECL:
5135       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5136           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5137         /* Argument is a parameter pack but parameter is not.  */
5138         return 0;
5139       break;
5140       
5141     case PARM_DECL:
5142       /* The tsubst call is used to handle cases such as
5143          
5144            template <int> class C {};
5145            template <class T, template <T> class TT> class D {};
5146            D<int, C> d;
5147
5148          i.e. the parameter list of TT depends on earlier parameters.  */
5149       if (!uses_template_parms (TREE_TYPE (arg))
5150           && !same_type_p
5151                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5152                  TREE_TYPE (arg)))
5153         return 0;
5154       
5155       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5156           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5157         /* Argument is a parameter pack but parameter is not.  */
5158         return 0;
5159       
5160       break;
5161
5162     default:
5163       gcc_unreachable ();
5164     }
5165
5166   return 1;
5167 }
5168
5169
5170 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5171    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5172    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5173    or PARM_DECL.
5174
5175    Consider the example:
5176      template <class T> class A;
5177      template<template <class U> class TT> class B;
5178
5179    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5180    the parameters to A, and OUTER_ARGS contains A.  */
5181
5182 static int
5183 coerce_template_template_parms (tree parm_parms,
5184                                 tree arg_parms,
5185                                 tsubst_flags_t complain,
5186                                 tree in_decl,
5187                                 tree outer_args)
5188 {
5189   int nparms, nargs, i;
5190   tree parm, arg;
5191   int variadic_p = 0;
5192
5193   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5194   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5195
5196   nparms = TREE_VEC_LENGTH (parm_parms);
5197   nargs = TREE_VEC_LENGTH (arg_parms);
5198
5199   /* Determine whether we have a parameter pack at the end of the
5200      template template parameter's template parameter list.  */
5201   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5202     {
5203       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5204       
5205       if (parm == error_mark_node)
5206         return 0;
5207
5208       switch (TREE_CODE (parm))
5209         {
5210         case TEMPLATE_DECL:
5211         case TYPE_DECL:
5212           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5213             variadic_p = 1;
5214           break;
5215           
5216         case PARM_DECL:
5217           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5218             variadic_p = 1;
5219           break;
5220           
5221         default:
5222           gcc_unreachable ();
5223         }
5224     }
5225  
5226   if (nargs != nparms
5227       && !(variadic_p && nargs >= nparms - 1))
5228     return 0;
5229
5230   /* Check all of the template parameters except the parameter pack at
5231      the end (if any).  */
5232   for (i = 0; i < nparms - variadic_p; ++i)
5233     {
5234       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5235           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5236         continue;
5237
5238       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5239       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5240
5241       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5242                                           outer_args))
5243         return 0;
5244
5245     }
5246
5247   if (variadic_p)
5248     {
5249       /* Check each of the template parameters in the template
5250          argument against the template parameter pack at the end of
5251          the template template parameter.  */
5252       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5253         return 0;
5254
5255       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5256
5257       for (; i < nargs; ++i)
5258         {
5259           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5260             continue;
5261  
5262           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5263  
5264           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5265                                               outer_args))
5266             return 0;
5267         }
5268     }
5269
5270   return 1;
5271 }
5272
5273 /* Verifies that the deduced template arguments (in TARGS) for the
5274    template template parameters (in TPARMS) represent valid bindings,
5275    by comparing the template parameter list of each template argument
5276    to the template parameter list of its corresponding template
5277    template parameter, in accordance with DR150. This
5278    routine can only be called after all template arguments have been
5279    deduced. It will return TRUE if all of the template template
5280    parameter bindings are okay, FALSE otherwise.  */
5281 bool 
5282 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5283 {
5284   int i, ntparms = TREE_VEC_LENGTH (tparms);
5285   bool ret = true;
5286
5287   /* We're dealing with template parms in this process.  */
5288   ++processing_template_decl;
5289
5290   targs = INNERMOST_TEMPLATE_ARGS (targs);
5291
5292   for (i = 0; i < ntparms; ++i)
5293     {
5294       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5295       tree targ = TREE_VEC_ELT (targs, i);
5296
5297       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5298         {
5299           tree packed_args = NULL_TREE;
5300           int idx, len = 1;
5301
5302           if (ARGUMENT_PACK_P (targ))
5303             {
5304               /* Look inside the argument pack.  */
5305               packed_args = ARGUMENT_PACK_ARGS (targ);
5306               len = TREE_VEC_LENGTH (packed_args);
5307             }
5308
5309           for (idx = 0; idx < len; ++idx)
5310             {
5311               tree targ_parms = NULL_TREE;
5312
5313               if (packed_args)
5314                 /* Extract the next argument from the argument
5315                    pack.  */
5316                 targ = TREE_VEC_ELT (packed_args, idx);
5317
5318               if (PACK_EXPANSION_P (targ))
5319                 /* Look at the pattern of the pack expansion.  */
5320                 targ = PACK_EXPANSION_PATTERN (targ);
5321
5322               /* Extract the template parameters from the template
5323                  argument.  */
5324               if (TREE_CODE (targ) == TEMPLATE_DECL)
5325                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5326               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5327                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5328
5329               /* Verify that we can coerce the template template
5330                  parameters from the template argument to the template
5331                  parameter.  This requires an exact match.  */
5332               if (targ_parms
5333                   && !coerce_template_template_parms
5334                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5335                         targ_parms,
5336                         tf_none,
5337                         tparm,
5338                         targs))
5339                 {
5340                   ret = false;
5341                   goto out;
5342                 }
5343             }
5344         }
5345     }
5346
5347  out:
5348
5349   --processing_template_decl;
5350   return ret;
5351 }
5352
5353 /* Convert the indicated template ARG as necessary to match the
5354    indicated template PARM.  Returns the converted ARG, or
5355    error_mark_node if the conversion was unsuccessful.  Error and
5356    warning messages are issued under control of COMPLAIN.  This
5357    conversion is for the Ith parameter in the parameter list.  ARGS is
5358    the full set of template arguments deduced so far.  */
5359
5360 static tree
5361 convert_template_argument (tree parm,
5362                            tree arg,
5363                            tree args,
5364                            tsubst_flags_t complain,
5365                            int i,
5366                            tree in_decl)
5367 {
5368   tree orig_arg;
5369   tree val;
5370   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5371
5372   if (TREE_CODE (arg) == TREE_LIST
5373       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5374     {
5375       /* The template argument was the name of some
5376          member function.  That's usually
5377          invalid, but static members are OK.  In any
5378          case, grab the underlying fields/functions
5379          and issue an error later if required.  */
5380       orig_arg = TREE_VALUE (arg);
5381       TREE_TYPE (arg) = unknown_type_node;
5382     }
5383
5384   orig_arg = arg;
5385
5386   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5387   requires_type = (TREE_CODE (parm) == TYPE_DECL
5388                    || requires_tmpl_type);
5389
5390   /* When determining whether an argument pack expansion is a template,
5391      look at the pattern.  */
5392   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5393     arg = PACK_EXPANSION_PATTERN (arg);
5394
5395   /* Deal with an injected-class-name used as a template template arg.  */
5396   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5397     {
5398       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5399       if (TREE_CODE (t) == TEMPLATE_DECL)
5400         {
5401           if (complain & tf_warning_or_error)
5402             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5403                      " used as template template argument", TYPE_NAME (arg));
5404           else if (flag_pedantic_errors)
5405             t = arg;
5406
5407           arg = t;
5408         }
5409     }
5410
5411   is_tmpl_type = 
5412     ((TREE_CODE (arg) == TEMPLATE_DECL
5413       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5414      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5415      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5416
5417   if (is_tmpl_type
5418       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5419           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5420     arg = TYPE_STUB_DECL (arg);
5421
5422   is_type = TYPE_P (arg) || is_tmpl_type;
5423
5424   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5425       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5426     {
5427       permerror (input_location, "to refer to a type member of a template parameter, "
5428                  "use %<typename %E%>", orig_arg);
5429
5430       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5431                                      TREE_OPERAND (arg, 1),
5432                                      typename_type,
5433                                      complain & tf_error);
5434       arg = orig_arg;
5435       is_type = 1;
5436     }
5437   if (is_type != requires_type)
5438     {
5439       if (in_decl)
5440         {
5441           if (complain & tf_error)
5442             {
5443               error ("type/value mismatch at argument %d in template "
5444                      "parameter list for %qD",
5445                      i + 1, in_decl);
5446               if (is_type)
5447                 error ("  expected a constant of type %qT, got %qT",
5448                        TREE_TYPE (parm),
5449                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5450               else if (requires_tmpl_type)
5451                 error ("  expected a class template, got %qE", orig_arg);
5452               else
5453                 error ("  expected a type, got %qE", orig_arg);
5454             }
5455         }
5456       return error_mark_node;
5457     }
5458   if (is_tmpl_type ^ requires_tmpl_type)
5459     {
5460       if (in_decl && (complain & tf_error))
5461         {
5462           error ("type/value mismatch at argument %d in template "
5463                  "parameter list for %qD",
5464                  i + 1, in_decl);
5465           if (is_tmpl_type)
5466             error ("  expected a type, got %qT", DECL_NAME (arg));
5467           else
5468             error ("  expected a class template, got %qT", orig_arg);
5469         }
5470       return error_mark_node;
5471     }
5472
5473   if (is_type)
5474     {
5475       if (requires_tmpl_type)
5476         {
5477           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5478             /* The number of argument required is not known yet.
5479                Just accept it for now.  */
5480             val = TREE_TYPE (arg);
5481           else
5482             {
5483               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5484               tree argparm;
5485
5486               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5487
5488               if (coerce_template_template_parms (parmparm, argparm,
5489                                                   complain, in_decl,
5490                                                   args))
5491                 {
5492                   val = arg;
5493
5494                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5495                      TEMPLATE_DECL.  */
5496                   if (val != error_mark_node)
5497                     {
5498                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5499                         val = TREE_TYPE (val);
5500                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5501                         val = make_pack_expansion (val);
5502                     }
5503                 }
5504               else
5505                 {
5506                   if (in_decl && (complain & tf_error))
5507                     {
5508                       error ("type/value mismatch at argument %d in "
5509                              "template parameter list for %qD",
5510                              i + 1, in_decl);
5511                       error ("  expected a template of type %qD, got %qT",
5512                              parm, orig_arg);
5513                     }
5514
5515                   val = error_mark_node;
5516                 }
5517             }
5518         }
5519       else
5520         val = orig_arg;
5521       /* We only form one instance of each template specialization.
5522          Therefore, if we use a non-canonical variant (i.e., a
5523          typedef), any future messages referring to the type will use
5524          the typedef, which is confusing if those future uses do not
5525          themselves also use the typedef.  */
5526       if (TYPE_P (val))
5527         val = strip_typedefs (val);
5528     }
5529   else
5530     {
5531       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5532
5533       if (invalid_nontype_parm_type_p (t, complain))
5534         return error_mark_node;
5535
5536       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5537         {
5538           if (same_type_p (t, TREE_TYPE (orig_arg)))
5539             val = orig_arg;
5540           else
5541             {
5542               /* Not sure if this is reachable, but it doesn't hurt
5543                  to be robust.  */
5544               error ("type mismatch in nontype parameter pack");
5545               val = error_mark_node;
5546             }
5547         }
5548       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5549         /* We used to call digest_init here.  However, digest_init
5550            will report errors, which we don't want when complain
5551            is zero.  More importantly, digest_init will try too
5552            hard to convert things: for example, `0' should not be
5553            converted to pointer type at this point according to
5554            the standard.  Accepting this is not merely an
5555            extension, since deciding whether or not these
5556            conversions can occur is part of determining which
5557            function template to call, or whether a given explicit
5558            argument specification is valid.  */
5559         val = convert_nontype_argument (t, orig_arg);
5560       else
5561         val = orig_arg;
5562
5563       if (val == NULL_TREE)
5564         val = error_mark_node;
5565       else if (val == error_mark_node && (complain & tf_error))
5566         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5567     }
5568
5569   return val;
5570 }
5571
5572 /* Coerces the remaining template arguments in INNER_ARGS (from
5573    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5574    Returns the coerced argument pack. PARM_IDX is the position of this
5575    parameter in the template parameter list. ARGS is the original
5576    template argument list.  */
5577 static tree
5578 coerce_template_parameter_pack (tree parms,
5579                                 int parm_idx,
5580                                 tree args,
5581                                 tree inner_args,
5582                                 int arg_idx,
5583                                 tree new_args,
5584                                 int* lost,
5585                                 tree in_decl,
5586                                 tsubst_flags_t complain)
5587 {
5588   tree parm = TREE_VEC_ELT (parms, parm_idx);
5589   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5590   tree packed_args;
5591   tree argument_pack;
5592   tree packed_types = NULL_TREE;
5593
5594   if (arg_idx > nargs)
5595     arg_idx = nargs;
5596
5597   packed_args = make_tree_vec (nargs - arg_idx);
5598
5599   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5600       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5601     {
5602       /* When the template parameter is a non-type template
5603          parameter pack whose type uses parameter packs, we need
5604          to look at each of the template arguments
5605          separately. Build a vector of the types for these
5606          non-type template parameters in PACKED_TYPES.  */
5607       tree expansion 
5608         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5609       packed_types = tsubst_pack_expansion (expansion, args,
5610                                             complain, in_decl);
5611
5612       if (packed_types == error_mark_node)
5613         return error_mark_node;
5614
5615       /* Check that we have the right number of arguments.  */
5616       if (arg_idx < nargs
5617           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5618           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5619         {
5620           int needed_parms 
5621             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5622           error ("wrong number of template arguments (%d, should be %d)",
5623                  nargs, needed_parms);
5624           return error_mark_node;
5625         }
5626
5627       /* If we aren't able to check the actual arguments now
5628          (because they haven't been expanded yet), we can at least
5629          verify that all of the types used for the non-type
5630          template parameter pack are, in fact, valid for non-type
5631          template parameters.  */
5632       if (arg_idx < nargs 
5633           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5634         {
5635           int j, len = TREE_VEC_LENGTH (packed_types);
5636           for (j = 0; j < len; ++j)
5637             {
5638               tree t = TREE_VEC_ELT (packed_types, j);
5639               if (invalid_nontype_parm_type_p (t, complain))
5640                 return error_mark_node;
5641             }
5642         }
5643     }
5644
5645   /* Convert the remaining arguments, which will be a part of the
5646      parameter pack "parm".  */
5647   for (; arg_idx < nargs; ++arg_idx)
5648     {
5649       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5650       tree actual_parm = TREE_VALUE (parm);
5651
5652       if (packed_types && !PACK_EXPANSION_P (arg))
5653         {
5654           /* When we have a vector of types (corresponding to the
5655              non-type template parameter pack that uses parameter
5656              packs in its type, as mention above), and the
5657              argument is not an expansion (which expands to a
5658              currently unknown number of arguments), clone the
5659              parm and give it the next type in PACKED_TYPES.  */
5660           actual_parm = copy_node (actual_parm);
5661           TREE_TYPE (actual_parm) = 
5662             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5663         }
5664
5665       if (arg != error_mark_node)
5666         arg = convert_template_argument (actual_parm, 
5667                                          arg, new_args, complain, parm_idx,
5668                                          in_decl);
5669       if (arg == error_mark_node)
5670         (*lost)++;
5671       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5672     }
5673
5674   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5675       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5676     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5677   else
5678     {
5679       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5680       TREE_TYPE (argument_pack) 
5681         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5682       TREE_CONSTANT (argument_pack) = 1;
5683     }
5684
5685   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5686   return argument_pack;
5687 }
5688
5689 /* Convert all template arguments to their appropriate types, and
5690    return a vector containing the innermost resulting template
5691    arguments.  If any error occurs, return error_mark_node. Error and
5692    warning messages are issued under control of COMPLAIN.
5693
5694    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5695    for arguments not specified in ARGS.  Otherwise, if
5696    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5697    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5698    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5699    ARGS.  */
5700
5701 static tree
5702 coerce_template_parms (tree parms,
5703                        tree args,
5704                        tree in_decl,
5705                        tsubst_flags_t complain,
5706                        bool require_all_args,
5707                        bool use_default_args)
5708 {
5709   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5710   tree inner_args;
5711   tree new_args;
5712   tree new_inner_args;
5713   int saved_unevaluated_operand;
5714   int saved_inhibit_evaluation_warnings;
5715
5716   /* When used as a boolean value, indicates whether this is a
5717      variadic template parameter list. Since it's an int, we can also
5718      subtract it from nparms to get the number of non-variadic
5719      parameters.  */
5720   int variadic_p = 0;
5721
5722   nparms = TREE_VEC_LENGTH (parms);
5723
5724   /* Determine if there are any parameter packs.  */
5725   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5726     {
5727       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5728       if (template_parameter_pack_p (tparm))
5729         ++variadic_p;
5730     }
5731
5732   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5733   /* If there are 0 or 1 parameter packs, we need to expand any argument
5734      packs so that we can deduce a parameter pack from some non-packed args
5735      followed by an argument pack, as in variadic85.C.  If there are more
5736      than that, we need to leave argument packs intact so the arguments are
5737      assigned to the right parameter packs.  This should only happen when
5738      dealing with a nested class inside a partial specialization of a class
5739      template, as in variadic92.C.  */
5740   if (variadic_p <= 1)
5741     inner_args = expand_template_argument_pack (inner_args);
5742
5743   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5744   if ((nargs > nparms && !variadic_p)
5745       || (nargs < nparms - variadic_p
5746           && require_all_args
5747           && (!use_default_args
5748               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5749                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5750     {
5751       if (complain & tf_error)
5752         {
5753           const char *or_more = "";
5754           if (variadic_p)
5755             {
5756               or_more = " or more";
5757               --nparms;
5758             }
5759
5760           error ("wrong number of template arguments (%d, should be %d%s)",
5761                  nargs, nparms, or_more);
5762
5763           if (in_decl)
5764             error ("provided for %q+D", in_decl);
5765         }
5766
5767       return error_mark_node;
5768     }
5769
5770   /* We need to evaluate the template arguments, even though this
5771      template-id may be nested within a "sizeof".  */
5772   saved_unevaluated_operand = cp_unevaluated_operand;
5773   cp_unevaluated_operand = 0;
5774   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5775   c_inhibit_evaluation_warnings = 0;
5776   new_inner_args = make_tree_vec (nparms);
5777   new_args = add_outermost_template_args (args, new_inner_args);
5778   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5779     {
5780       tree arg;
5781       tree parm;
5782
5783       /* Get the Ith template parameter.  */
5784       parm = TREE_VEC_ELT (parms, parm_idx);
5785  
5786       if (parm == error_mark_node)
5787       {
5788         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5789         continue;
5790       }
5791
5792       /* Calculate the next argument.  */
5793       if (arg_idx < nargs)
5794         arg = TREE_VEC_ELT (inner_args, arg_idx);
5795       else
5796         arg = NULL_TREE;
5797
5798       if (template_parameter_pack_p (TREE_VALUE (parm))
5799           && !(arg && ARGUMENT_PACK_P (arg)))
5800         {
5801           /* All remaining arguments will be placed in the
5802              template parameter pack PARM.  */
5803           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5804                                                 inner_args, arg_idx,
5805                                                 new_args, &lost,
5806                                                 in_decl, complain);
5807
5808           /* Store this argument.  */
5809           if (arg == error_mark_node)
5810             lost++;
5811           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5812
5813           /* We are done with all of the arguments.  */
5814           arg_idx = nargs;
5815           
5816           continue;
5817         }
5818       else if (arg)
5819         {
5820           if (PACK_EXPANSION_P (arg))
5821             {
5822               if (complain & tf_error)
5823                 {
5824                   /* FIXME this restriction was removed by N2555; see
5825                      bug 35722.  */
5826                   /* If ARG is a pack expansion, but PARM is not a
5827                      template parameter pack (if it were, we would have
5828                      handled it above), we're trying to expand into a
5829                      fixed-length argument list.  */
5830                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5831                     sorry ("cannot expand %<%E%> into a fixed-length "
5832                            "argument list", arg);
5833                   else
5834                     sorry ("cannot expand %<%T%> into a fixed-length "
5835                            "argument list", arg);
5836                 }
5837               return error_mark_node;
5838             }
5839         }
5840       else if (require_all_args)
5841         /* There must be a default arg in this case.  */
5842         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5843                                    complain, in_decl);
5844       else
5845         break;
5846
5847       if (arg == error_mark_node)
5848         {
5849           if (complain & tf_error)
5850             error ("template argument %d is invalid", arg_idx + 1);
5851         }
5852       else if (!arg)
5853         /* This only occurs if there was an error in the template
5854            parameter list itself (which we would already have
5855            reported) that we are trying to recover from, e.g., a class
5856            template with a parameter list such as
5857            template<typename..., typename>.  */
5858         return error_mark_node;
5859       else
5860         arg = convert_template_argument (TREE_VALUE (parm),
5861                                          arg, new_args, complain, 
5862                                          parm_idx, in_decl);
5863
5864       if (arg == error_mark_node)
5865         lost++;
5866       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5867     }
5868   cp_unevaluated_operand = saved_unevaluated_operand;
5869   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5870
5871   if (lost)
5872     return error_mark_node;
5873
5874   return new_inner_args;
5875 }
5876
5877 /* Returns 1 if template args OT and NT are equivalent.  */
5878
5879 static int
5880 template_args_equal (tree ot, tree nt)
5881 {
5882   if (nt == ot)
5883     return 1;
5884
5885   if (TREE_CODE (nt) == TREE_VEC)
5886     /* For member templates */
5887     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5888   else if (PACK_EXPANSION_P (ot))
5889     return PACK_EXPANSION_P (nt) 
5890       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5891                               PACK_EXPANSION_PATTERN (nt));
5892   else if (ARGUMENT_PACK_P (ot))
5893     {
5894       int i, len;
5895       tree opack, npack;
5896
5897       if (!ARGUMENT_PACK_P (nt))
5898         return 0;
5899
5900       opack = ARGUMENT_PACK_ARGS (ot);
5901       npack = ARGUMENT_PACK_ARGS (nt);
5902       len = TREE_VEC_LENGTH (opack);
5903       if (TREE_VEC_LENGTH (npack) != len)
5904         return 0;
5905       for (i = 0; i < len; ++i)
5906         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5907                                   TREE_VEC_ELT (npack, i)))
5908           return 0;
5909       return 1;
5910     }
5911   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5912     {
5913       /* We get here probably because we are in the middle of substituting
5914          into the pattern of a pack expansion. In that case the
5915          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5916          interested in. So we want to use the initial pack argument for
5917          the comparison.  */
5918       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5919       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5920         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5921       return template_args_equal (ot, nt);
5922     }
5923   else if (TYPE_P (nt))
5924     return TYPE_P (ot) && same_type_p (ot, nt);
5925   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5926     return 0;
5927   else
5928     return cp_tree_equal (ot, nt);
5929 }
5930
5931 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5932    of template arguments.  Returns 0 otherwise.  */
5933
5934 int
5935 comp_template_args (tree oldargs, tree newargs)
5936 {
5937   int i;
5938
5939   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5940     return 0;
5941
5942   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5943     {
5944       tree nt = TREE_VEC_ELT (newargs, i);
5945       tree ot = TREE_VEC_ELT (oldargs, i);
5946
5947       if (! template_args_equal (ot, nt))
5948         return 0;
5949     }
5950   return 1;
5951 }
5952
5953 static void
5954 add_pending_template (tree d)
5955 {
5956   tree ti = (TYPE_P (d)
5957              ? CLASSTYPE_TEMPLATE_INFO (d)
5958              : DECL_TEMPLATE_INFO (d));
5959   struct pending_template *pt;
5960   int level;
5961
5962   if (TI_PENDING_TEMPLATE_FLAG (ti))
5963     return;
5964
5965   /* We are called both from instantiate_decl, where we've already had a
5966      tinst_level pushed, and instantiate_template, where we haven't.
5967      Compensate.  */
5968   level = !current_tinst_level || current_tinst_level->decl != d;
5969
5970   if (level)
5971     push_tinst_level (d);
5972
5973   pt = GGC_NEW (struct pending_template);
5974   pt->next = NULL;
5975   pt->tinst = current_tinst_level;
5976   if (last_pending_template)
5977     last_pending_template->next = pt;
5978   else
5979     pending_templates = pt;
5980
5981   last_pending_template = pt;
5982
5983   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5984
5985   if (level)
5986     pop_tinst_level ();
5987 }
5988
5989
5990 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5991    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5992    documentation for TEMPLATE_ID_EXPR.  */
5993
5994 tree
5995 lookup_template_function (tree fns, tree arglist)
5996 {
5997   tree type;
5998
5999   if (fns == error_mark_node || arglist == error_mark_node)
6000     return error_mark_node;
6001
6002   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6003   gcc_assert (fns && (is_overloaded_fn (fns)
6004                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6005
6006   if (BASELINK_P (fns))
6007     {
6008       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6009                                          unknown_type_node,
6010                                          BASELINK_FUNCTIONS (fns),
6011                                          arglist);
6012       return fns;
6013     }
6014
6015   type = TREE_TYPE (fns);
6016   if (TREE_CODE (fns) == OVERLOAD || !type)
6017     type = unknown_type_node;
6018
6019   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6020 }
6021
6022 /* Within the scope of a template class S<T>, the name S gets bound
6023    (in build_self_reference) to a TYPE_DECL for the class, not a
6024    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6025    or one of its enclosing classes, and that type is a template,
6026    return the associated TEMPLATE_DECL.  Otherwise, the original
6027    DECL is returned.
6028
6029    Also handle the case when DECL is a TREE_LIST of ambiguous
6030    injected-class-names from different bases.  */
6031
6032 tree
6033 maybe_get_template_decl_from_type_decl (tree decl)
6034 {
6035   if (decl == NULL_TREE)
6036     return decl;
6037
6038   /* DR 176: A lookup that finds an injected-class-name (10.2
6039      [class.member.lookup]) can result in an ambiguity in certain cases
6040      (for example, if it is found in more than one base class). If all of
6041      the injected-class-names that are found refer to specializations of
6042      the same class template, and if the name is followed by a
6043      template-argument-list, the reference refers to the class template
6044      itself and not a specialization thereof, and is not ambiguous.  */
6045   if (TREE_CODE (decl) == TREE_LIST)
6046     {
6047       tree t, tmpl = NULL_TREE;
6048       for (t = decl; t; t = TREE_CHAIN (t))
6049         {
6050           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6051           if (!tmpl)
6052             tmpl = elt;
6053           else if (tmpl != elt)
6054             break;
6055         }
6056       if (tmpl && t == NULL_TREE)
6057         return tmpl;
6058       else
6059         return decl;
6060     }
6061
6062   return (decl != NULL_TREE
6063           && DECL_SELF_REFERENCE_P (decl)
6064           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6065     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6066 }
6067
6068 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6069    parameters, find the desired type.
6070
6071    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6072
6073    IN_DECL, if non-NULL, is the template declaration we are trying to
6074    instantiate.
6075
6076    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6077    the class we are looking up.
6078
6079    Issue error and warning messages under control of COMPLAIN.
6080
6081    If the template class is really a local class in a template
6082    function, then the FUNCTION_CONTEXT is the function in which it is
6083    being instantiated.
6084
6085    ??? Note that this function is currently called *twice* for each
6086    template-id: the first time from the parser, while creating the
6087    incomplete type (finish_template_type), and the second type during the
6088    real instantiation (instantiate_template_class). This is surely something
6089    that we want to avoid. It also causes some problems with argument
6090    coercion (see convert_nontype_argument for more information on this).  */
6091
6092 tree
6093 lookup_template_class (tree d1,
6094                        tree arglist,
6095                        tree in_decl,
6096                        tree context,
6097                        int entering_scope,
6098                        tsubst_flags_t complain)
6099 {
6100   tree templ = NULL_TREE, parmlist;
6101   tree t;
6102   spec_entry **slot;
6103   spec_entry *entry;
6104   spec_entry elt;
6105   hashval_t hash;
6106
6107   timevar_push (TV_NAME_LOOKUP);
6108
6109   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6110     {
6111       tree value = innermost_non_namespace_value (d1);
6112       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6113         templ = value;
6114       else
6115         {
6116           if (context)
6117             push_decl_namespace (context);
6118           templ = lookup_name (d1);
6119           templ = maybe_get_template_decl_from_type_decl (templ);
6120           if (context)
6121             pop_decl_namespace ();
6122         }
6123       if (templ)
6124         context = DECL_CONTEXT (templ);
6125     }
6126   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6127     {
6128       tree type = TREE_TYPE (d1);
6129
6130       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6131          an implicit typename for the second A.  Deal with it.  */
6132       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6133         type = TREE_TYPE (type);
6134
6135       if (CLASSTYPE_TEMPLATE_INFO (type))
6136         {
6137           templ = CLASSTYPE_TI_TEMPLATE (type);
6138           d1 = DECL_NAME (templ);
6139         }
6140     }
6141   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6142            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6143     {
6144       templ = TYPE_TI_TEMPLATE (d1);
6145       d1 = DECL_NAME (templ);
6146     }
6147   else if (TREE_CODE (d1) == TEMPLATE_DECL
6148            && DECL_TEMPLATE_RESULT (d1)
6149            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6150     {
6151       templ = d1;
6152       d1 = DECL_NAME (templ);
6153       context = DECL_CONTEXT (templ);
6154     }
6155
6156   /* Issue an error message if we didn't find a template.  */
6157   if (! templ)
6158     {
6159       if (complain & tf_error)
6160         error ("%qT is not a template", d1);
6161       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6162     }
6163
6164   if (TREE_CODE (templ) != TEMPLATE_DECL
6165          /* Make sure it's a user visible template, if it was named by
6166             the user.  */
6167       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6168           && !PRIMARY_TEMPLATE_P (templ)))
6169     {
6170       if (complain & tf_error)
6171         {
6172           error ("non-template type %qT used as a template", d1);
6173           if (in_decl)
6174             error ("for template declaration %q+D", in_decl);
6175         }
6176       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6177     }
6178
6179   complain &= ~tf_user;
6180
6181   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6182     {
6183       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6184          template arguments */
6185
6186       tree parm;
6187       tree arglist2;
6188       tree outer;
6189
6190       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6191
6192       /* Consider an example where a template template parameter declared as
6193
6194            template <class T, class U = std::allocator<T> > class TT
6195
6196          The template parameter level of T and U are one level larger than
6197          of TT.  To proper process the default argument of U, say when an
6198          instantiation `TT<int>' is seen, we need to build the full
6199          arguments containing {int} as the innermost level.  Outer levels,
6200          available when not appearing as default template argument, can be
6201          obtained from the arguments of the enclosing template.
6202
6203          Suppose that TT is later substituted with std::vector.  The above
6204          instantiation is `TT<int, std::allocator<T> >' with TT at
6205          level 1, and T at level 2, while the template arguments at level 1
6206          becomes {std::vector} and the inner level 2 is {int}.  */
6207
6208       outer = DECL_CONTEXT (templ);
6209       if (outer)
6210         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6211       else if (current_template_parms)
6212         /* This is an argument of the current template, so we haven't set
6213            DECL_CONTEXT yet.  */
6214         outer = current_template_args ();
6215
6216       if (outer)
6217         arglist = add_to_template_args (outer, arglist);
6218
6219       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6220                                         complain,
6221                                         /*require_all_args=*/true,
6222                                         /*use_default_args=*/true);
6223       if (arglist2 == error_mark_node
6224           || (!uses_template_parms (arglist2)
6225               && check_instantiated_args (templ, arglist2, complain)))
6226         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6227
6228       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6229       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6230     }
6231   else
6232     {
6233       tree template_type = TREE_TYPE (templ);
6234       tree gen_tmpl;
6235       tree type_decl;
6236       tree found = NULL_TREE;
6237       int arg_depth;
6238       int parm_depth;
6239       int is_partial_instantiation;
6240
6241       gen_tmpl = most_general_template (templ);
6242       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6243       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6244       arg_depth = TMPL_ARGS_DEPTH (arglist);
6245
6246       if (arg_depth == 1 && parm_depth > 1)
6247         {
6248           /* We've been given an incomplete set of template arguments.
6249              For example, given:
6250
6251                template <class T> struct S1 {
6252                  template <class U> struct S2 {};
6253                  template <class U> struct S2<U*> {};
6254                 };
6255
6256              we will be called with an ARGLIST of `U*', but the
6257              TEMPLATE will be `template <class T> template
6258              <class U> struct S1<T>::S2'.  We must fill in the missing
6259              arguments.  */
6260           arglist
6261             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6262                                            arglist);
6263           arg_depth = TMPL_ARGS_DEPTH (arglist);
6264         }
6265
6266       /* Now we should have enough arguments.  */
6267       gcc_assert (parm_depth == arg_depth);
6268
6269       /* From here on, we're only interested in the most general
6270          template.  */
6271
6272       /* Calculate the BOUND_ARGS.  These will be the args that are
6273          actually tsubst'd into the definition to create the
6274          instantiation.  */
6275       if (parm_depth > 1)
6276         {
6277           /* We have multiple levels of arguments to coerce, at once.  */
6278           int i;
6279           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6280
6281           tree bound_args = make_tree_vec (parm_depth);
6282
6283           for (i = saved_depth,
6284                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6285                i > 0 && t != NULL_TREE;
6286                --i, t = TREE_CHAIN (t))
6287             {
6288               tree a = coerce_template_parms (TREE_VALUE (t),
6289                                               arglist, gen_tmpl,
6290                                               complain,
6291                                               /*require_all_args=*/true,
6292                                               /*use_default_args=*/true);
6293
6294               /* Don't process further if one of the levels fails.  */
6295               if (a == error_mark_node)
6296                 {
6297                   /* Restore the ARGLIST to its full size.  */
6298                   TREE_VEC_LENGTH (arglist) = saved_depth;
6299                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6300                 }
6301
6302               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6303
6304               /* We temporarily reduce the length of the ARGLIST so
6305                  that coerce_template_parms will see only the arguments
6306                  corresponding to the template parameters it is
6307                  examining.  */
6308               TREE_VEC_LENGTH (arglist)--;
6309             }
6310
6311           /* Restore the ARGLIST to its full size.  */
6312           TREE_VEC_LENGTH (arglist) = saved_depth;
6313
6314           arglist = bound_args;
6315         }
6316       else
6317         arglist
6318           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6319                                    INNERMOST_TEMPLATE_ARGS (arglist),
6320                                    gen_tmpl,
6321                                    complain,
6322                                    /*require_all_args=*/true,
6323                                    /*use_default_args=*/true);
6324
6325       if (arglist == error_mark_node)
6326         /* We were unable to bind the arguments.  */
6327         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6328
6329       /* In the scope of a template class, explicit references to the
6330          template class refer to the type of the template, not any
6331          instantiation of it.  For example, in:
6332
6333            template <class T> class C { void f(C<T>); }
6334
6335          the `C<T>' is just the same as `C'.  Outside of the
6336          class, however, such a reference is an instantiation.  */
6337       if ((entering_scope
6338            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6339            || currently_open_class (template_type))
6340           /* comp_template_args is expensive, check it last.  */
6341           && comp_template_args (TYPE_TI_ARGS (template_type),
6342                                  arglist))
6343         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6344
6345       /* If we already have this specialization, return it.  */
6346       elt.tmpl = gen_tmpl;
6347       elt.args = arglist;
6348       hash = hash_specialization (&elt);
6349       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6350                                                   &elt, hash);
6351
6352       if (entry)
6353         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6354
6355       /* This type is a "partial instantiation" if any of the template
6356          arguments still involve template parameters.  Note that we set
6357          IS_PARTIAL_INSTANTIATION for partial specializations as
6358          well.  */
6359       is_partial_instantiation = uses_template_parms (arglist);
6360
6361       /* If the deduced arguments are invalid, then the binding
6362          failed.  */
6363       if (!is_partial_instantiation
6364           && check_instantiated_args (gen_tmpl,
6365                                       INNERMOST_TEMPLATE_ARGS (arglist),
6366                                       complain))
6367         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6368
6369       if (!is_partial_instantiation
6370           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6371           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6372           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6373         {
6374           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6375                                       DECL_NAME (gen_tmpl),
6376                                       /*tag_scope=*/ts_global);
6377           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6378         }
6379
6380       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6381                         complain, in_decl);
6382       if (!context)
6383         context = global_namespace;
6384
6385       /* Create the type.  */
6386       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6387         {
6388           if (!is_partial_instantiation)
6389             {
6390               set_current_access_from_decl (TYPE_NAME (template_type));
6391               t = start_enum (TYPE_IDENTIFIER (template_type),
6392                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6393                                       arglist, complain, in_decl),
6394                               SCOPED_ENUM_P (template_type));
6395             }
6396           else
6397             {
6398               /* We don't want to call start_enum for this type, since
6399                  the values for the enumeration constants may involve
6400                  template parameters.  And, no one should be interested
6401                  in the enumeration constants for such a type.  */
6402               t = cxx_make_type (ENUMERAL_TYPE);
6403               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6404             }
6405         }
6406       else
6407         {
6408           t = make_class_type (TREE_CODE (template_type));
6409           CLASSTYPE_DECLARED_CLASS (t)
6410             = CLASSTYPE_DECLARED_CLASS (template_type);
6411           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6412           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6413
6414           /* A local class.  Make sure the decl gets registered properly.  */
6415           if (context == current_function_decl)
6416             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6417
6418           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6419             /* This instantiation is another name for the primary
6420                template type. Set the TYPE_CANONICAL field
6421                appropriately. */
6422             TYPE_CANONICAL (t) = template_type;
6423           else if (any_template_arguments_need_structural_equality_p (arglist))
6424             /* Some of the template arguments require structural
6425                equality testing, so this template class requires
6426                structural equality testing. */
6427             SET_TYPE_STRUCTURAL_EQUALITY (t);
6428         }
6429
6430       /* If we called start_enum or pushtag above, this information
6431          will already be set up.  */
6432       if (!TYPE_NAME (t))
6433         {
6434           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6435
6436           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6437           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6438           DECL_SOURCE_LOCATION (type_decl)
6439             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6440         }
6441       else
6442         type_decl = TYPE_NAME (t);
6443
6444       TREE_PRIVATE (type_decl)
6445         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6446       TREE_PROTECTED (type_decl)
6447         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6448       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6449         {
6450           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6451           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6452         }
6453
6454       /* Set up the template information.  We have to figure out which
6455          template is the immediate parent if this is a full
6456          instantiation.  */
6457       if (parm_depth == 1 || is_partial_instantiation
6458           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6459         /* This case is easy; there are no member templates involved.  */
6460         found = gen_tmpl;
6461       else
6462         {
6463           /* This is a full instantiation of a member template.  Find
6464              the partial instantiation of which this is an instance.  */
6465
6466           /* Temporarily reduce by one the number of levels in the ARGLIST
6467              so as to avoid comparing the last set of arguments.  */
6468           TREE_VEC_LENGTH (arglist)--;
6469           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6470           TREE_VEC_LENGTH (arglist)++;
6471           found = CLASSTYPE_TI_TEMPLATE (found);
6472         }
6473
6474       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6475
6476       elt.spec = t;
6477       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6478                                                        &elt, hash, INSERT);
6479       *slot = GGC_NEW (spec_entry);
6480       **slot = elt;
6481
6482       /* Note this use of the partial instantiation so we can check it
6483          later in maybe_process_partial_specialization.  */
6484       DECL_TEMPLATE_INSTANTIATIONS (templ)
6485         = tree_cons (arglist, t,
6486                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6487
6488       if (TREE_CODE (t) == ENUMERAL_TYPE
6489           && !is_partial_instantiation)
6490         /* Now that the type has been registered on the instantiations
6491            list, we set up the enumerators.  Because the enumeration
6492            constants may involve the enumeration type itself, we make
6493            sure to register the type first, and then create the
6494            constants.  That way, doing tsubst_expr for the enumeration
6495            constants won't result in recursive calls here; we'll find
6496            the instantiation and exit above.  */
6497         tsubst_enum (template_type, t, arglist);
6498
6499       if (is_partial_instantiation)
6500         /* If the type makes use of template parameters, the
6501            code that generates debugging information will crash.  */
6502         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6503
6504       /* Possibly limit visibility based on template args.  */
6505       TREE_PUBLIC (type_decl) = 1;
6506       determine_visibility (type_decl);
6507
6508       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6509     }
6510   timevar_pop (TV_NAME_LOOKUP);
6511 }
6512 \f
6513 struct pair_fn_data
6514 {
6515   tree_fn_t fn;
6516   void *data;
6517   /* True when we should also visit template parameters that occur in
6518      non-deduced contexts.  */
6519   bool include_nondeduced_p;
6520   struct pointer_set_t *visited;
6521 };
6522
6523 /* Called from for_each_template_parm via walk_tree.  */
6524
6525 static tree
6526 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6527 {
6528   tree t = *tp;
6529   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6530   tree_fn_t fn = pfd->fn;
6531   void *data = pfd->data;
6532
6533   if (TYPE_P (t)
6534       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6535       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6536                                  pfd->include_nondeduced_p))
6537     return error_mark_node;
6538
6539   switch (TREE_CODE (t))
6540     {
6541     case RECORD_TYPE:
6542       if (TYPE_PTRMEMFUNC_P (t))
6543         break;
6544       /* Fall through.  */
6545
6546     case UNION_TYPE:
6547     case ENUMERAL_TYPE:
6548       if (!TYPE_TEMPLATE_INFO (t))
6549         *walk_subtrees = 0;
6550       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6551                                        fn, data, pfd->visited, 
6552                                        pfd->include_nondeduced_p))
6553         return error_mark_node;
6554       break;
6555
6556     case INTEGER_TYPE:
6557       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6558                                   fn, data, pfd->visited, 
6559                                   pfd->include_nondeduced_p)
6560           || for_each_template_parm (TYPE_MAX_VALUE (t),
6561                                      fn, data, pfd->visited,
6562                                      pfd->include_nondeduced_p))
6563         return error_mark_node;
6564       break;
6565
6566     case METHOD_TYPE:
6567       /* Since we're not going to walk subtrees, we have to do this
6568          explicitly here.  */
6569       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6570                                   pfd->visited, pfd->include_nondeduced_p))
6571         return error_mark_node;
6572       /* Fall through.  */
6573
6574     case FUNCTION_TYPE:
6575       /* Check the return type.  */
6576       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6577                                   pfd->include_nondeduced_p))
6578         return error_mark_node;
6579
6580       /* Check the parameter types.  Since default arguments are not
6581          instantiated until they are needed, the TYPE_ARG_TYPES may
6582          contain expressions that involve template parameters.  But,
6583          no-one should be looking at them yet.  And, once they're
6584          instantiated, they don't contain template parameters, so
6585          there's no point in looking at them then, either.  */
6586       {
6587         tree parm;
6588
6589         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6590           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6591                                       pfd->visited, pfd->include_nondeduced_p))
6592             return error_mark_node;
6593
6594         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6595            want walk_tree walking into them itself.  */
6596         *walk_subtrees = 0;
6597       }
6598       break;
6599
6600     case TYPEOF_TYPE:
6601       if (pfd->include_nondeduced_p
6602           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6603                                      pfd->visited, 
6604                                      pfd->include_nondeduced_p))
6605         return error_mark_node;
6606       break;
6607
6608     case FUNCTION_DECL:
6609     case VAR_DECL:
6610       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6611           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6612                                      pfd->visited, pfd->include_nondeduced_p))
6613         return error_mark_node;
6614       /* Fall through.  */
6615
6616     case PARM_DECL:
6617     case CONST_DECL:
6618       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6619           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6620                                      pfd->visited, pfd->include_nondeduced_p))
6621         return error_mark_node;
6622       if (DECL_CONTEXT (t)
6623           && pfd->include_nondeduced_p
6624           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6625                                      pfd->visited, pfd->include_nondeduced_p))
6626         return error_mark_node;
6627       break;
6628
6629     case BOUND_TEMPLATE_TEMPLATE_PARM:
6630       /* Record template parameters such as `T' inside `TT<T>'.  */
6631       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6632                                   pfd->include_nondeduced_p))
6633         return error_mark_node;
6634       /* Fall through.  */
6635
6636     case TEMPLATE_TEMPLATE_PARM:
6637     case TEMPLATE_TYPE_PARM:
6638     case TEMPLATE_PARM_INDEX:
6639       if (fn && (*fn)(t, data))
6640         return error_mark_node;
6641       else if (!fn)
6642         return error_mark_node;
6643       break;
6644
6645     case TEMPLATE_DECL:
6646       /* A template template parameter is encountered.  */
6647       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6648           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6649                                      pfd->include_nondeduced_p))
6650         return error_mark_node;
6651
6652       /* Already substituted template template parameter */
6653       *walk_subtrees = 0;
6654       break;
6655
6656     case TYPENAME_TYPE:
6657       if (!fn
6658           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6659                                      data, pfd->visited, 
6660                                      pfd->include_nondeduced_p))
6661         return error_mark_node;
6662       break;
6663
6664     case CONSTRUCTOR:
6665       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6666           && pfd->include_nondeduced_p
6667           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6668                                      (TREE_TYPE (t)), fn, data,
6669                                      pfd->visited, pfd->include_nondeduced_p))
6670         return error_mark_node;
6671       break;
6672
6673     case INDIRECT_REF:
6674     case COMPONENT_REF:
6675       /* If there's no type, then this thing must be some expression
6676          involving template parameters.  */
6677       if (!fn && !TREE_TYPE (t))
6678         return error_mark_node;
6679       break;
6680
6681     case MODOP_EXPR:
6682     case CAST_EXPR:
6683     case REINTERPRET_CAST_EXPR:
6684     case CONST_CAST_EXPR:
6685     case STATIC_CAST_EXPR:
6686     case DYNAMIC_CAST_EXPR:
6687     case ARROW_EXPR:
6688     case DOTSTAR_EXPR:
6689     case TYPEID_EXPR:
6690     case PSEUDO_DTOR_EXPR:
6691       if (!fn)
6692         return error_mark_node;
6693       break;
6694
6695     default:
6696       break;
6697     }
6698
6699   /* We didn't find any template parameters we liked.  */
6700   return NULL_TREE;
6701 }
6702
6703 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6704    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6705    call FN with the parameter and the DATA.
6706    If FN returns nonzero, the iteration is terminated, and
6707    for_each_template_parm returns 1.  Otherwise, the iteration
6708    continues.  If FN never returns a nonzero value, the value
6709    returned by for_each_template_parm is 0.  If FN is NULL, it is
6710    considered to be the function which always returns 1.
6711
6712    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6713    parameters that occur in non-deduced contexts.  When false, only
6714    visits those template parameters that can be deduced.  */
6715
6716 static int
6717 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6718                         struct pointer_set_t *visited,
6719                         bool include_nondeduced_p)
6720 {
6721   struct pair_fn_data pfd;
6722   int result;
6723
6724   /* Set up.  */
6725   pfd.fn = fn;
6726   pfd.data = data;
6727   pfd.include_nondeduced_p = include_nondeduced_p;
6728
6729   /* Walk the tree.  (Conceptually, we would like to walk without
6730      duplicates, but for_each_template_parm_r recursively calls
6731      for_each_template_parm, so we would need to reorganize a fair
6732      bit to use walk_tree_without_duplicates, so we keep our own
6733      visited list.)  */
6734   if (visited)
6735     pfd.visited = visited;
6736   else
6737     pfd.visited = pointer_set_create ();
6738   result = cp_walk_tree (&t,
6739                          for_each_template_parm_r,
6740                          &pfd,
6741                          pfd.visited) != NULL_TREE;
6742
6743   /* Clean up.  */
6744   if (!visited)
6745     {
6746       pointer_set_destroy (pfd.visited);
6747       pfd.visited = 0;
6748     }
6749
6750   return result;
6751 }
6752
6753 /* Returns true if T depends on any template parameter.  */
6754
6755 int
6756 uses_template_parms (tree t)
6757 {
6758   bool dependent_p;
6759   int saved_processing_template_decl;
6760
6761   saved_processing_template_decl = processing_template_decl;
6762   if (!saved_processing_template_decl)
6763     processing_template_decl = 1;
6764   if (TYPE_P (t))
6765     dependent_p = dependent_type_p (t);
6766   else if (TREE_CODE (t) == TREE_VEC)
6767     dependent_p = any_dependent_template_arguments_p (t);
6768   else if (TREE_CODE (t) == TREE_LIST)
6769     dependent_p = (uses_template_parms (TREE_VALUE (t))
6770                    || uses_template_parms (TREE_CHAIN (t)));
6771   else if (TREE_CODE (t) == TYPE_DECL)
6772     dependent_p = dependent_type_p (TREE_TYPE (t));
6773   else if (DECL_P (t)
6774            || EXPR_P (t)
6775            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6776            || TREE_CODE (t) == OVERLOAD
6777            || TREE_CODE (t) == BASELINK
6778            || TREE_CODE (t) == IDENTIFIER_NODE
6779            || TREE_CODE (t) == TRAIT_EXPR
6780            || TREE_CODE (t) == CONSTRUCTOR
6781            || CONSTANT_CLASS_P (t))
6782     dependent_p = (type_dependent_expression_p (t)
6783                    || value_dependent_expression_p (t));
6784   else
6785     {
6786       gcc_assert (t == error_mark_node);
6787       dependent_p = false;
6788     }
6789
6790   processing_template_decl = saved_processing_template_decl;
6791
6792   return dependent_p;
6793 }
6794
6795 /* Returns true if T depends on any template parameter with level LEVEL.  */
6796
6797 int
6798 uses_template_parms_level (tree t, int level)
6799 {
6800   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6801                                  /*include_nondeduced_p=*/true);
6802 }
6803
6804 static int tinst_depth;
6805 extern int max_tinst_depth;
6806 #ifdef GATHER_STATISTICS
6807 int depth_reached;
6808 #endif
6809 static int tinst_level_tick;
6810 static int last_template_error_tick;
6811
6812 /* We're starting to instantiate D; record the template instantiation context
6813    for diagnostics and to restore it later.  */
6814
6815 static int
6816 push_tinst_level (tree d)
6817 {
6818   struct tinst_level *new_level;
6819
6820   if (tinst_depth >= max_tinst_depth)
6821     {
6822       /* If the instantiation in question still has unbound template parms,
6823          we don't really care if we can't instantiate it, so just return.
6824          This happens with base instantiation for implicit `typename'.  */
6825       if (uses_template_parms (d))
6826         return 0;
6827
6828       last_template_error_tick = tinst_level_tick;
6829       error ("template instantiation depth exceeds maximum of %d (use "
6830              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6831              max_tinst_depth, d);
6832
6833       print_instantiation_context ();
6834
6835       return 0;
6836     }
6837
6838   new_level = GGC_NEW (struct tinst_level);
6839   new_level->decl = d;
6840   new_level->locus = input_location;
6841   new_level->in_system_header_p = in_system_header;
6842   new_level->next = current_tinst_level;
6843   current_tinst_level = new_level;
6844
6845   ++tinst_depth;
6846 #ifdef GATHER_STATISTICS
6847   if (tinst_depth > depth_reached)
6848     depth_reached = tinst_depth;
6849 #endif
6850
6851   ++tinst_level_tick;
6852   return 1;
6853 }
6854
6855 /* We're done instantiating this template; return to the instantiation
6856    context.  */
6857
6858 static void
6859 pop_tinst_level (void)
6860 {
6861   /* Restore the filename and line number stashed away when we started
6862      this instantiation.  */
6863   input_location = current_tinst_level->locus;
6864   current_tinst_level = current_tinst_level->next;
6865   --tinst_depth;
6866   ++tinst_level_tick;
6867 }
6868
6869 /* We're instantiating a deferred template; restore the template
6870    instantiation context in which the instantiation was requested, which
6871    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6872
6873 static tree
6874 reopen_tinst_level (struct tinst_level *level)
6875 {
6876   struct tinst_level *t;
6877
6878   tinst_depth = 0;
6879   for (t = level; t; t = t->next)
6880     ++tinst_depth;
6881
6882   current_tinst_level = level;
6883   pop_tinst_level ();
6884   return level->decl;
6885 }
6886
6887 /* Returns the TINST_LEVEL which gives the original instantiation
6888    context.  */
6889
6890 struct tinst_level *
6891 outermost_tinst_level (void)
6892 {
6893   struct tinst_level *level = current_tinst_level;
6894   if (level)
6895     while (level->next)
6896       level = level->next;
6897   return level;
6898 }
6899
6900 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6901
6902 bool
6903 parameter_of_template_p (tree parm, tree templ)
6904 {
6905   tree parms;
6906   int i;
6907
6908   if (!parm || !templ)
6909     return false;
6910
6911   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6912   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6913
6914   parms = DECL_TEMPLATE_PARMS (templ);
6915   parms = INNERMOST_TEMPLATE_PARMS (parms);
6916
6917   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6918     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6919       return true;
6920
6921   return false;
6922 }
6923
6924 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6925    vector of template arguments, as for tsubst.
6926
6927    Returns an appropriate tsubst'd friend declaration.  */
6928
6929 static tree
6930 tsubst_friend_function (tree decl, tree args)
6931 {
6932   tree new_friend;
6933
6934   if (TREE_CODE (decl) == FUNCTION_DECL
6935       && DECL_TEMPLATE_INSTANTIATION (decl)
6936       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6937     /* This was a friend declared with an explicit template
6938        argument list, e.g.:
6939
6940        friend void f<>(T);
6941
6942        to indicate that f was a template instantiation, not a new
6943        function declaration.  Now, we have to figure out what
6944        instantiation of what template.  */
6945     {
6946       tree template_id, arglist, fns;
6947       tree new_args;
6948       tree tmpl;
6949       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6950
6951       /* Friend functions are looked up in the containing namespace scope.
6952          We must enter that scope, to avoid finding member functions of the
6953          current class with same name.  */
6954       push_nested_namespace (ns);
6955       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6956                          tf_warning_or_error, NULL_TREE,
6957                          /*integral_constant_expression_p=*/false);
6958       pop_nested_namespace (ns);
6959       arglist = tsubst (DECL_TI_ARGS (decl), args,
6960                         tf_warning_or_error, NULL_TREE);
6961       template_id = lookup_template_function (fns, arglist);
6962
6963       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6964       tmpl = determine_specialization (template_id, new_friend,
6965                                        &new_args,
6966                                        /*need_member_template=*/0,
6967                                        TREE_VEC_LENGTH (args),
6968                                        tsk_none);
6969       return instantiate_template (tmpl, new_args, tf_error);
6970     }
6971
6972   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6973
6974   /* The NEW_FRIEND will look like an instantiation, to the
6975      compiler, but is not an instantiation from the point of view of
6976      the language.  For example, we might have had:
6977
6978      template <class T> struct S {
6979        template <class U> friend void f(T, U);
6980      };
6981
6982      Then, in S<int>, template <class U> void f(int, U) is not an
6983      instantiation of anything.  */
6984   if (new_friend == error_mark_node)
6985     return error_mark_node;
6986
6987   DECL_USE_TEMPLATE (new_friend) = 0;
6988   if (TREE_CODE (decl) == TEMPLATE_DECL)
6989     {
6990       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6991       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6992         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6993     }
6994
6995   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6996      is not a template instantiation and should not be mangled like
6997      one.  Therefore, we forget the mangling here; we'll recompute it
6998      later if we need it.  */
6999   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7000     {
7001       SET_DECL_RTL (new_friend, NULL_RTX);
7002       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7003     }
7004
7005   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7006     {
7007       tree old_decl;
7008       tree new_friend_template_info;
7009       tree new_friend_result_template_info;
7010       tree ns;
7011       int  new_friend_is_defn;
7012
7013       /* We must save some information from NEW_FRIEND before calling
7014          duplicate decls since that function will free NEW_FRIEND if
7015          possible.  */
7016       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7017       new_friend_is_defn =
7018             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7019                            (template_for_substitution (new_friend)))
7020              != NULL_TREE);
7021       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7022         {
7023           /* This declaration is a `primary' template.  */
7024           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7025
7026           new_friend_result_template_info
7027             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7028         }
7029       else
7030         new_friend_result_template_info = NULL_TREE;
7031
7032       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7033       if (new_friend_is_defn)
7034         DECL_INITIAL (new_friend) = error_mark_node;
7035
7036       /* Inside pushdecl_namespace_level, we will push into the
7037          current namespace. However, the friend function should go
7038          into the namespace of the template.  */
7039       ns = decl_namespace_context (new_friend);
7040       push_nested_namespace (ns);
7041       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7042       pop_nested_namespace (ns);
7043
7044       if (old_decl == error_mark_node)
7045         return error_mark_node;
7046
7047       if (old_decl != new_friend)
7048         {
7049           /* This new friend declaration matched an existing
7050              declaration.  For example, given:
7051
7052                template <class T> void f(T);
7053                template <class U> class C {
7054                  template <class T> friend void f(T) {}
7055                };
7056
7057              the friend declaration actually provides the definition
7058              of `f', once C has been instantiated for some type.  So,
7059              old_decl will be the out-of-class template declaration,
7060              while new_friend is the in-class definition.
7061
7062              But, if `f' was called before this point, the
7063              instantiation of `f' will have DECL_TI_ARGS corresponding
7064              to `T' but not to `U', references to which might appear
7065              in the definition of `f'.  Previously, the most general
7066              template for an instantiation of `f' was the out-of-class
7067              version; now it is the in-class version.  Therefore, we
7068              run through all specialization of `f', adding to their
7069              DECL_TI_ARGS appropriately.  In particular, they need a
7070              new set of outer arguments, corresponding to the
7071              arguments for this class instantiation.
7072
7073              The same situation can arise with something like this:
7074
7075                friend void f(int);
7076                template <class T> class C {
7077                  friend void f(T) {}
7078                };
7079
7080              when `C<int>' is instantiated.  Now, `f(int)' is defined
7081              in the class.  */
7082
7083           if (!new_friend_is_defn)
7084             /* On the other hand, if the in-class declaration does
7085                *not* provide a definition, then we don't want to alter
7086                existing definitions.  We can just leave everything
7087                alone.  */
7088             ;
7089           else
7090             {
7091               tree new_template = TI_TEMPLATE (new_friend_template_info);
7092               tree new_args = TI_ARGS (new_friend_template_info);
7093
7094               /* Overwrite whatever template info was there before, if
7095                  any, with the new template information pertaining to
7096                  the declaration.  */
7097               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7098
7099               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7100                 /* We should have called reregister_specialization in
7101                    duplicate_decls.  */
7102                 gcc_assert (retrieve_specialization (new_template,
7103                                                      new_args, 0)
7104                             == old_decl);
7105               else
7106                 {
7107                   tree t;
7108
7109                   /* Indicate that the old function template is a partial
7110                      instantiation.  */
7111                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7112                     = new_friend_result_template_info;
7113
7114                   gcc_assert (new_template
7115                               == most_general_template (new_template));
7116                   gcc_assert (new_template != old_decl);
7117
7118                   /* Reassign any specializations already in the hash table
7119                      to the new more general template, and add the
7120                      additional template args.  */
7121                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7122                        t != NULL_TREE;
7123                        t = TREE_CHAIN (t))
7124                     {
7125                       tree spec = TREE_VALUE (t);
7126                       spec_entry elt;
7127
7128                       elt.tmpl = old_decl;
7129                       elt.args = DECL_TI_ARGS (spec);
7130                       elt.spec = NULL_TREE;
7131
7132                       htab_remove_elt (decl_specializations, &elt);
7133
7134                       DECL_TI_ARGS (spec)
7135                         = add_outermost_template_args (new_args,
7136                                                        DECL_TI_ARGS (spec));
7137
7138                       register_specialization
7139                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7140
7141                     }
7142                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7143                 }
7144             }
7145
7146           /* The information from NEW_FRIEND has been merged into OLD_DECL
7147              by duplicate_decls.  */
7148           new_friend = old_decl;
7149         }
7150     }
7151   else
7152     {
7153       tree context = DECL_CONTEXT (new_friend);
7154       bool dependent_p;
7155
7156       /* In the code
7157            template <class T> class C {
7158              template <class U> friend void C1<U>::f (); // case 1
7159              friend void C2<T>::f ();                    // case 2
7160            };
7161          we only need to make sure CONTEXT is a complete type for
7162          case 2.  To distinguish between the two cases, we note that
7163          CONTEXT of case 1 remains dependent type after tsubst while
7164          this isn't true for case 2.  */
7165       ++processing_template_decl;
7166       dependent_p = dependent_type_p (context);
7167       --processing_template_decl;
7168
7169       if (!dependent_p
7170           && !complete_type_or_else (context, NULL_TREE))
7171         return error_mark_node;
7172
7173       if (COMPLETE_TYPE_P (context))
7174         {
7175           /* Check to see that the declaration is really present, and,
7176              possibly obtain an improved declaration.  */
7177           tree fn = check_classfn (context,
7178                                    new_friend, NULL_TREE);
7179
7180           if (fn)
7181             new_friend = fn;
7182         }
7183     }
7184
7185   return new_friend;
7186 }
7187
7188 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7189    template arguments, as for tsubst.
7190
7191    Returns an appropriate tsubst'd friend type or error_mark_node on
7192    failure.  */
7193
7194 static tree
7195 tsubst_friend_class (tree friend_tmpl, tree args)
7196 {
7197   tree friend_type;
7198   tree tmpl;
7199   tree context;
7200
7201   context = DECL_CONTEXT (friend_tmpl);
7202
7203   if (context)
7204     {
7205       if (TREE_CODE (context) == NAMESPACE_DECL)
7206         push_nested_namespace (context);
7207       else
7208         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7209     }
7210
7211   /* Look for a class template declaration.  We look for hidden names
7212      because two friend declarations of the same template are the
7213      same.  For example, in:
7214
7215        struct A { 
7216          template <typename> friend class F;
7217        };
7218        template <typename> struct B { 
7219          template <typename> friend class F;
7220        };
7221
7222      both F templates are the same.  */
7223   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7224                            /*block_p=*/true, 0, 
7225                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7226
7227   /* But, if we don't find one, it might be because we're in a
7228      situation like this:
7229
7230        template <class T>
7231        struct S {
7232          template <class U>
7233          friend struct S;
7234        };
7235
7236      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7237      for `S<int>', not the TEMPLATE_DECL.  */
7238   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7239     {
7240       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7241       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7242     }
7243
7244   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7245     {
7246       /* The friend template has already been declared.  Just
7247          check to see that the declarations match, and install any new
7248          default parameters.  We must tsubst the default parameters,
7249          of course.  We only need the innermost template parameters
7250          because that is all that redeclare_class_template will look
7251          at.  */
7252       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7253           > TMPL_ARGS_DEPTH (args))
7254         {
7255           tree parms;
7256           location_t saved_input_location;
7257           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7258                                          args, tf_warning_or_error);
7259
7260           saved_input_location = input_location;
7261           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7262           redeclare_class_template (TREE_TYPE (tmpl), parms);
7263           input_location = saved_input_location;
7264           
7265         }
7266
7267       friend_type = TREE_TYPE (tmpl);
7268     }
7269   else
7270     {
7271       /* The friend template has not already been declared.  In this
7272          case, the instantiation of the template class will cause the
7273          injection of this template into the global scope.  */
7274       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7275       if (tmpl == error_mark_node)
7276         return error_mark_node;
7277
7278       /* The new TMPL is not an instantiation of anything, so we
7279          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7280          the new type because that is supposed to be the corresponding
7281          template decl, i.e., TMPL.  */
7282       DECL_USE_TEMPLATE (tmpl) = 0;
7283       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7284       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7285       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7286         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7287
7288       /* Inject this template into the global scope.  */
7289       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7290     }
7291
7292   if (context)
7293     {
7294       if (TREE_CODE (context) == NAMESPACE_DECL)
7295         pop_nested_namespace (context);
7296       else
7297         pop_nested_class ();
7298     }
7299
7300   return friend_type;
7301 }
7302
7303 /* Returns zero if TYPE cannot be completed later due to circularity.
7304    Otherwise returns one.  */
7305
7306 static int
7307 can_complete_type_without_circularity (tree type)
7308 {
7309   if (type == NULL_TREE || type == error_mark_node)
7310     return 0;
7311   else if (COMPLETE_TYPE_P (type))
7312     return 1;
7313   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7314     return can_complete_type_without_circularity (TREE_TYPE (type));
7315   else if (CLASS_TYPE_P (type)
7316            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7317     return 0;
7318   else
7319     return 1;
7320 }
7321
7322 /* Apply any attributes which had to be deferred until instantiation
7323    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7324    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7325
7326 static void
7327 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7328                                 tree args, tsubst_flags_t complain, tree in_decl)
7329 {
7330   tree last_dep = NULL_TREE;
7331   tree t;
7332   tree *p;
7333
7334   for (t = attributes; t; t = TREE_CHAIN (t))
7335     if (ATTR_IS_DEPENDENT (t))
7336       {
7337         last_dep = t;
7338         attributes = copy_list (attributes);
7339         break;
7340       }
7341
7342   if (DECL_P (*decl_p))
7343     {
7344       if (TREE_TYPE (*decl_p) == error_mark_node)
7345         return;
7346       p = &DECL_ATTRIBUTES (*decl_p);
7347     }
7348   else
7349     p = &TYPE_ATTRIBUTES (*decl_p);
7350
7351   if (last_dep)
7352     {
7353       tree late_attrs = NULL_TREE;
7354       tree *q = &late_attrs;
7355
7356       for (*p = attributes; *p; )
7357         {
7358           t = *p;
7359           if (ATTR_IS_DEPENDENT (t))
7360             {
7361               *p = TREE_CHAIN (t);
7362               TREE_CHAIN (t) = NULL_TREE;
7363               /* If the first attribute argument is an identifier, don't
7364                  pass it through tsubst.  Attributes like mode, format,
7365                  cleanup and several target specific attributes expect it
7366                  unmodified.  */
7367               if (TREE_VALUE (t)
7368                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7369                   && TREE_VALUE (TREE_VALUE (t))
7370                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7371                       == IDENTIFIER_NODE))
7372                 {
7373                   tree chain
7374                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7375                                    in_decl,
7376                                    /*integral_constant_expression_p=*/false);
7377                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7378                     TREE_VALUE (t)
7379                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7380                                    chain);
7381                 }
7382               else
7383                 TREE_VALUE (t)
7384                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7385                                  /*integral_constant_expression_p=*/false);
7386               *q = t;
7387               q = &TREE_CHAIN (t);
7388             }
7389           else
7390             p = &TREE_CHAIN (t);
7391         }
7392
7393       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7394     }
7395 }
7396
7397 /* Perform (or defer) access check for typedefs that were referenced
7398    from within the template TMPL code.
7399    This is a subroutine of instantiate_template and instantiate_class_template.
7400    TMPL is the template to consider and TARGS is the list of arguments of
7401    that template.  */
7402
7403 static void
7404 perform_typedefs_access_check (tree tmpl, tree targs)
7405 {
7406   location_t saved_location;
7407   int i;
7408   qualified_typedef_usage_t *iter;
7409
7410   if (!tmpl
7411       || (!CLASS_TYPE_P (tmpl)
7412           && TREE_CODE (tmpl) != FUNCTION_DECL))
7413     return;
7414
7415   saved_location = input_location;
7416   for (i = 0;
7417        VEC_iterate (qualified_typedef_usage_t,
7418                     get_types_needing_access_check (tmpl),
7419                     i, iter);
7420         ++i)
7421     {
7422       tree type_decl = iter->typedef_decl;
7423       tree type_scope = iter->context;
7424
7425       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7426         continue;
7427
7428       if (uses_template_parms (type_decl))
7429         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7430       if (uses_template_parms (type_scope))
7431         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7432
7433       /* Make access check error messages point to the location
7434          of the use of the typedef.  */
7435       input_location = iter->locus;
7436       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7437                                      type_decl, type_decl);
7438     }
7439     input_location = saved_location;
7440 }
7441
7442 tree
7443 instantiate_class_template (tree type)
7444 {
7445   tree templ, args, pattern, t, member;
7446   tree typedecl;
7447   tree pbinfo;
7448   tree base_list;
7449   unsigned int saved_maximum_field_alignment;
7450
7451   if (type == error_mark_node)
7452     return error_mark_node;
7453
7454   if (TYPE_BEING_DEFINED (type)
7455       || COMPLETE_TYPE_P (type)
7456       || uses_template_parms (type))
7457     return type;
7458
7459   /* Figure out which template is being instantiated.  */
7460   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7461   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7462
7463   /* Determine what specialization of the original template to
7464      instantiate.  */
7465   t = most_specialized_class (type, templ);
7466   if (t == error_mark_node)
7467     {
7468       TYPE_BEING_DEFINED (type) = 1;
7469       return error_mark_node;
7470     }
7471   else if (t)
7472     {
7473       /* This TYPE is actually an instantiation of a partial
7474          specialization.  We replace the innermost set of ARGS with
7475          the arguments appropriate for substitution.  For example,
7476          given:
7477
7478            template <class T> struct S {};
7479            template <class T> struct S<T*> {};
7480
7481          and supposing that we are instantiating S<int*>, ARGS will
7482          presently be {int*} -- but we need {int}.  */
7483       pattern = TREE_TYPE (t);
7484       args = TREE_PURPOSE (t);
7485     }
7486   else
7487     {
7488       pattern = TREE_TYPE (templ);
7489       args = CLASSTYPE_TI_ARGS (type);
7490     }
7491
7492   /* If the template we're instantiating is incomplete, then clearly
7493      there's nothing we can do.  */
7494   if (!COMPLETE_TYPE_P (pattern))
7495     return type;
7496
7497   /* If we've recursively instantiated too many templates, stop.  */
7498   if (! push_tinst_level (type))
7499     return type;
7500
7501   /* Now we're really doing the instantiation.  Mark the type as in
7502      the process of being defined.  */
7503   TYPE_BEING_DEFINED (type) = 1;
7504
7505   /* We may be in the middle of deferred access check.  Disable
7506      it now.  */
7507   push_deferring_access_checks (dk_no_deferred);
7508
7509   push_to_top_level ();
7510   /* Use #pragma pack from the template context.  */
7511   saved_maximum_field_alignment = maximum_field_alignment;
7512   maximum_field_alignment = TYPE_PRECISION (pattern);
7513
7514   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7515
7516   /* Set the input location to the most specialized template definition.
7517      This is needed if tsubsting causes an error.  */
7518   typedecl = TYPE_MAIN_DECL (pattern);
7519   input_location = DECL_SOURCE_LOCATION (typedecl);
7520
7521   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7522   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7523   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7524   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7525   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7526   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7527   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7528   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7529   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7530   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7531   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7532   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7533   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7534   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7535   if (ANON_AGGR_TYPE_P (pattern))
7536     SET_ANON_AGGR_TYPE_P (type);
7537   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7538     {
7539       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7540       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7541     }
7542
7543   pbinfo = TYPE_BINFO (pattern);
7544
7545   /* We should never instantiate a nested class before its enclosing
7546      class; we need to look up the nested class by name before we can
7547      instantiate it, and that lookup should instantiate the enclosing
7548      class.  */
7549   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7550               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7551               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7552
7553   base_list = NULL_TREE;
7554   if (BINFO_N_BASE_BINFOS (pbinfo))
7555     {
7556       tree pbase_binfo;
7557       tree context = TYPE_CONTEXT (type);
7558       tree pushed_scope;
7559       int i;
7560
7561       /* We must enter the scope containing the type, as that is where
7562          the accessibility of types named in dependent bases are
7563          looked up from.  */
7564       pushed_scope = push_scope (context ? context : global_namespace);
7565
7566       /* Substitute into each of the bases to determine the actual
7567          basetypes.  */
7568       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7569         {
7570           tree base;
7571           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7572           tree expanded_bases = NULL_TREE;
7573           int idx, len = 1;
7574
7575           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7576             {
7577               expanded_bases = 
7578                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7579                                        args, tf_error, NULL_TREE);
7580               if (expanded_bases == error_mark_node)
7581                 continue;
7582
7583               len = TREE_VEC_LENGTH (expanded_bases);
7584             }
7585
7586           for (idx = 0; idx < len; idx++)
7587             {
7588               if (expanded_bases)
7589                 /* Extract the already-expanded base class.  */
7590                 base = TREE_VEC_ELT (expanded_bases, idx);
7591               else
7592                 /* Substitute to figure out the base class.  */
7593                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7594                                NULL_TREE);
7595
7596               if (base == error_mark_node)
7597                 continue;
7598
7599               base_list = tree_cons (access, base, base_list);
7600               if (BINFO_VIRTUAL_P (pbase_binfo))
7601                 TREE_TYPE (base_list) = integer_type_node;
7602             }
7603         }
7604
7605       /* The list is now in reverse order; correct that.  */
7606       base_list = nreverse (base_list);
7607
7608       if (pushed_scope)
7609         pop_scope (pushed_scope);
7610     }
7611   /* Now call xref_basetypes to set up all the base-class
7612      information.  */
7613   xref_basetypes (type, base_list);
7614
7615   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7616                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7617                                   args, tf_error, NULL_TREE);
7618
7619   /* Now that our base classes are set up, enter the scope of the
7620      class, so that name lookups into base classes, etc. will work
7621      correctly.  This is precisely analogous to what we do in
7622      begin_class_definition when defining an ordinary non-template
7623      class, except we also need to push the enclosing classes.  */
7624   push_nested_class (type);
7625
7626   /* Now members are processed in the order of declaration.  */
7627   for (member = CLASSTYPE_DECL_LIST (pattern);
7628        member; member = TREE_CHAIN (member))
7629     {
7630       tree t = TREE_VALUE (member);
7631
7632       if (TREE_PURPOSE (member))
7633         {
7634           if (TYPE_P (t))
7635             {
7636               /* Build new CLASSTYPE_NESTED_UTDS.  */
7637
7638               tree newtag;
7639               bool class_template_p;
7640
7641               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7642                                   && TYPE_LANG_SPECIFIC (t)
7643                                   && CLASSTYPE_IS_TEMPLATE (t));
7644               /* If the member is a class template, then -- even after
7645                  substitution -- there may be dependent types in the
7646                  template argument list for the class.  We increment
7647                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7648                  that function will assume that no types are dependent
7649                  when outside of a template.  */
7650               if (class_template_p)
7651                 ++processing_template_decl;
7652               newtag = tsubst (t, args, tf_error, NULL_TREE);
7653               if (class_template_p)
7654                 --processing_template_decl;
7655               if (newtag == error_mark_node)
7656                 continue;
7657
7658               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7659                 {
7660                   tree name = TYPE_IDENTIFIER (t);
7661
7662                   if (class_template_p)
7663                     /* Unfortunately, lookup_template_class sets
7664                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7665                        instantiation (i.e., for the type of a member
7666                        template class nested within a template class.)
7667                        This behavior is required for
7668                        maybe_process_partial_specialization to work
7669                        correctly, but is not accurate in this case;
7670                        the TAG is not an instantiation of anything.
7671                        (The corresponding TEMPLATE_DECL is an
7672                        instantiation, but the TYPE is not.) */
7673                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7674
7675                   /* Now, we call pushtag to put this NEWTAG into the scope of
7676                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7677                      pushtag calling push_template_decl.  We don't have to do
7678                      this for enums because it will already have been done in
7679                      tsubst_enum.  */
7680                   if (name)
7681                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7682                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7683                 }
7684             }
7685           else if (TREE_CODE (t) == FUNCTION_DECL
7686                    || DECL_FUNCTION_TEMPLATE_P (t))
7687             {
7688               /* Build new TYPE_METHODS.  */
7689               tree r;
7690
7691               if (TREE_CODE (t) == TEMPLATE_DECL)
7692                 ++processing_template_decl;
7693               r = tsubst (t, args, tf_error, NULL_TREE);
7694               if (TREE_CODE (t) == TEMPLATE_DECL)
7695                 --processing_template_decl;
7696               set_current_access_from_decl (r);
7697               finish_member_declaration (r);
7698             }
7699           else
7700             {
7701               /* Build new TYPE_FIELDS.  */
7702               if (TREE_CODE (t) == STATIC_ASSERT)
7703                 {
7704                   tree condition = 
7705                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7706                                  tf_warning_or_error, NULL_TREE,
7707                                  /*integral_constant_expression_p=*/true);
7708                   finish_static_assert (condition,
7709                                         STATIC_ASSERT_MESSAGE (t), 
7710                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7711                                         /*member_p=*/true);
7712                 }
7713               else if (TREE_CODE (t) != CONST_DECL)
7714                 {
7715                   tree r;
7716
7717                   /* The file and line for this declaration, to
7718                      assist in error message reporting.  Since we
7719                      called push_tinst_level above, we don't need to
7720                      restore these.  */
7721                   input_location = DECL_SOURCE_LOCATION (t);
7722
7723                   if (TREE_CODE (t) == TEMPLATE_DECL)
7724                     ++processing_template_decl;
7725                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7726                   if (TREE_CODE (t) == TEMPLATE_DECL)
7727                     --processing_template_decl;
7728                   if (TREE_CODE (r) == VAR_DECL)
7729                     {
7730                       /* In [temp.inst]:
7731
7732                            [t]he initialization (and any associated
7733                            side-effects) of a static data member does
7734                            not occur unless the static data member is
7735                            itself used in a way that requires the
7736                            definition of the static data member to
7737                            exist.
7738
7739                          Therefore, we do not substitute into the
7740                          initialized for the static data member here.  */
7741                       finish_static_data_member_decl
7742                         (r,
7743                          /*init=*/NULL_TREE,
7744                          /*init_const_expr_p=*/false,
7745                          /*asmspec_tree=*/NULL_TREE,
7746                          /*flags=*/0);
7747                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7748                         check_static_variable_definition (r, TREE_TYPE (r));
7749                     }
7750                   else if (TREE_CODE (r) == FIELD_DECL)
7751                     {
7752                       /* Determine whether R has a valid type and can be
7753                          completed later.  If R is invalid, then it is
7754                          replaced by error_mark_node so that it will not be
7755                          added to TYPE_FIELDS.  */
7756                       tree rtype = TREE_TYPE (r);
7757                       if (can_complete_type_without_circularity (rtype))
7758                         complete_type (rtype);
7759
7760                       if (!COMPLETE_TYPE_P (rtype))
7761                         {
7762                           cxx_incomplete_type_error (r, rtype);
7763                           r = error_mark_node;
7764                         }
7765                     }
7766
7767                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7768                      such a thing will already have been added to the field
7769                      list by tsubst_enum in finish_member_declaration in the
7770                      CLASSTYPE_NESTED_UTDS case above.  */
7771                   if (!(TREE_CODE (r) == TYPE_DECL
7772                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7773                         && DECL_ARTIFICIAL (r)))
7774                     {
7775                       set_current_access_from_decl (r);
7776                       finish_member_declaration (r);
7777                     }
7778                 }
7779             }
7780         }
7781       else
7782         {
7783           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7784             {
7785               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7786
7787               tree friend_type = t;
7788               bool adjust_processing_template_decl = false;
7789
7790               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7791                 {
7792                   /* template <class T> friend class C;  */
7793                   friend_type = tsubst_friend_class (friend_type, args);
7794                   adjust_processing_template_decl = true;
7795                 }
7796               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7797                 {
7798                   /* template <class T> friend class C::D;  */
7799                   friend_type = tsubst (friend_type, args,
7800                                         tf_warning_or_error, NULL_TREE);
7801                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7802                     friend_type = TREE_TYPE (friend_type);
7803                   adjust_processing_template_decl = true;
7804                 }
7805               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7806                 {
7807                   /* This could be either
7808
7809                        friend class T::C;
7810
7811                      when dependent_type_p is false or
7812
7813                        template <class U> friend class T::C;
7814
7815                      otherwise.  */
7816                   friend_type = tsubst (friend_type, args,
7817                                         tf_warning_or_error, NULL_TREE);
7818                   /* Bump processing_template_decl for correct
7819                      dependent_type_p calculation.  */
7820                   ++processing_template_decl;
7821                   if (dependent_type_p (friend_type))
7822                     adjust_processing_template_decl = true;
7823                   --processing_template_decl;
7824                 }
7825               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7826                        && hidden_name_p (TYPE_NAME (friend_type)))
7827                 {
7828                   /* friend class C;
7829
7830                      where C hasn't been declared yet.  Let's lookup name
7831                      from namespace scope directly, bypassing any name that
7832                      come from dependent base class.  */
7833                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7834
7835                   /* The call to xref_tag_from_type does injection for friend
7836                      classes.  */
7837                   push_nested_namespace (ns);
7838                   friend_type =
7839                     xref_tag_from_type (friend_type, NULL_TREE,
7840                                         /*tag_scope=*/ts_current);
7841                   pop_nested_namespace (ns);
7842                 }
7843               else if (uses_template_parms (friend_type))
7844                 /* friend class C<T>;  */
7845                 friend_type = tsubst (friend_type, args,
7846                                       tf_warning_or_error, NULL_TREE);
7847               /* Otherwise it's
7848
7849                    friend class C;
7850
7851                  where C is already declared or
7852
7853                    friend class C<int>;
7854
7855                  We don't have to do anything in these cases.  */
7856
7857               if (adjust_processing_template_decl)
7858                 /* Trick make_friend_class into realizing that the friend
7859                    we're adding is a template, not an ordinary class.  It's
7860                    important that we use make_friend_class since it will
7861                    perform some error-checking and output cross-reference
7862                    information.  */
7863                 ++processing_template_decl;
7864
7865               if (friend_type != error_mark_node)
7866                 make_friend_class (type, friend_type, /*complain=*/false);
7867
7868               if (adjust_processing_template_decl)
7869                 --processing_template_decl;
7870             }
7871           else
7872             {
7873               /* Build new DECL_FRIENDLIST.  */
7874               tree r;
7875
7876               /* The file and line for this declaration, to
7877                  assist in error message reporting.  Since we
7878                  called push_tinst_level above, we don't need to
7879                  restore these.  */
7880               input_location = DECL_SOURCE_LOCATION (t);
7881
7882               if (TREE_CODE (t) == TEMPLATE_DECL)
7883                 {
7884                   ++processing_template_decl;
7885                   push_deferring_access_checks (dk_no_check);
7886                 }
7887
7888               r = tsubst_friend_function (t, args);
7889               add_friend (type, r, /*complain=*/false);
7890               if (TREE_CODE (t) == TEMPLATE_DECL)
7891                 {
7892                   pop_deferring_access_checks ();
7893                   --processing_template_decl;
7894                 }
7895             }
7896         }
7897     }
7898
7899   /* Set the file and line number information to whatever is given for
7900      the class itself.  This puts error messages involving generated
7901      implicit functions at a predictable point, and the same point
7902      that would be used for non-template classes.  */
7903   input_location = DECL_SOURCE_LOCATION (typedecl);
7904
7905   unreverse_member_declarations (type);
7906   finish_struct_1 (type);
7907   TYPE_BEING_DEFINED (type) = 0;
7908
7909   /* Now that the class is complete, instantiate default arguments for
7910      any member functions.  We don't do this earlier because the
7911      default arguments may reference members of the class.  */
7912   if (!PRIMARY_TEMPLATE_P (templ))
7913     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7914       if (TREE_CODE (t) == FUNCTION_DECL
7915           /* Implicitly generated member functions will not have template
7916              information; they are not instantiations, but instead are
7917              created "fresh" for each instantiation.  */
7918           && DECL_TEMPLATE_INFO (t))
7919         tsubst_default_arguments (t);
7920
7921   /* Some typedefs referenced from within the template code need to be access
7922      checked at template instantiation time, i.e now. These types were
7923      added to the template at parsing time. Let's get those and perform
7924      the access checks then.  */
7925   perform_typedefs_access_check (pattern, args);
7926   perform_deferred_access_checks ();
7927   pop_nested_class ();
7928   maximum_field_alignment = saved_maximum_field_alignment;
7929   pop_from_top_level ();
7930   pop_deferring_access_checks ();
7931   pop_tinst_level ();
7932
7933   /* The vtable for a template class can be emitted in any translation
7934      unit in which the class is instantiated.  When there is no key
7935      method, however, finish_struct_1 will already have added TYPE to
7936      the keyed_classes list.  */
7937   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7938     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7939
7940   return type;
7941 }
7942
7943 static tree
7944 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7945 {
7946   tree r;
7947
7948   if (!t)
7949     r = t;
7950   else if (TYPE_P (t))
7951     r = tsubst (t, args, complain, in_decl);
7952   else
7953     {
7954       r = tsubst_expr (t, args, complain, in_decl,
7955                        /*integral_constant_expression_p=*/true);
7956       r = fold_non_dependent_expr (r);
7957     }
7958   return r;
7959 }
7960
7961 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7962    NONTYPE_ARGUMENT_PACK.  */
7963
7964 static tree
7965 make_fnparm_pack (tree spec_parm)
7966 {
7967   /* Collect all of the extra "packed" parameters into an
7968      argument pack.  */
7969   tree parmvec;
7970   tree parmtypevec;
7971   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7972   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7973   int i, len = list_length (spec_parm);
7974
7975   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7976   parmvec = make_tree_vec (len);
7977   parmtypevec = make_tree_vec (len);
7978   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7979     {
7980       TREE_VEC_ELT (parmvec, i) = spec_parm;
7981       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7982     }
7983
7984   /* Build the argument packs.  */
7985   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7986   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7987   TREE_TYPE (argpack) = argtypepack;
7988
7989   return argpack;
7990 }        
7991
7992 /* Substitute ARGS into T, which is an pack expansion
7993    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7994    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7995    (if only a partial substitution could be performed) or
7996    ERROR_MARK_NODE if there was an error.  */
7997 tree
7998 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7999                        tree in_decl)
8000 {
8001   tree pattern;
8002   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8003   tree first_arg_pack; int i, len = -1;
8004   tree result;
8005   int incomplete = 0;
8006   bool very_local_specializations = false;
8007
8008   gcc_assert (PACK_EXPANSION_P (t));
8009   pattern = PACK_EXPANSION_PATTERN (t);
8010
8011   /* Determine the argument packs that will instantiate the parameter
8012      packs used in the expansion expression. While we're at it,
8013      compute the number of arguments to be expanded and make sure it
8014      is consistent.  */
8015   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8016        pack = TREE_CHAIN (pack))
8017     {
8018       tree parm_pack = TREE_VALUE (pack);
8019       tree arg_pack = NULL_TREE;
8020       tree orig_arg = NULL_TREE;
8021
8022       if (TREE_CODE (parm_pack) == PARM_DECL)
8023         {
8024           arg_pack = retrieve_local_specialization (parm_pack);
8025           if (arg_pack == NULL_TREE)
8026             {
8027               /* This can happen for a parameter name used later in a function
8028                  declaration (such as in a late-specified return type).  Just
8029                  make a dummy decl, since it's only used for its type.  */
8030               gcc_assert (cp_unevaluated_operand != 0);
8031               arg_pack = tsubst_decl (parm_pack, args, complain);
8032               arg_pack = make_fnparm_pack (arg_pack);
8033             }
8034         }
8035       else
8036         {
8037           int level, idx, levels;
8038           template_parm_level_and_index (parm_pack, &level, &idx);
8039
8040           levels = TMPL_ARGS_DEPTH (args);
8041           if (level <= levels)
8042             arg_pack = TMPL_ARG (args, level, idx);
8043         }
8044
8045       orig_arg = arg_pack;
8046       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8047         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8048       
8049       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8050         /* This can only happen if we forget to expand an argument
8051            pack somewhere else. Just return an error, silently.  */
8052         {
8053           result = make_tree_vec (1);
8054           TREE_VEC_ELT (result, 0) = error_mark_node;
8055           return result;
8056         }
8057
8058       if (arg_pack
8059           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8060           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8061         {
8062           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8063           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8064           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8065               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8066             /* The argument pack that the parameter maps to is just an
8067                expansion of the parameter itself, such as one would
8068                find in the implicit typedef of a class inside the
8069                class itself.  Consider this parameter "unsubstituted",
8070                so that we will maintain the outer pack expansion.  */
8071             arg_pack = NULL_TREE;
8072         }
8073           
8074       if (arg_pack)
8075         {
8076           int my_len = 
8077             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8078
8079           /* It's all-or-nothing with incomplete argument packs.  */
8080           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8081             return error_mark_node;
8082           
8083           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8084             incomplete = 1;
8085
8086           if (len < 0)
8087             {
8088               len = my_len;
8089               first_arg_pack = arg_pack;
8090             }
8091           else if (len != my_len)
8092             {
8093               if (incomplete)
8094                 /* We got explicit args for some packs but not others;
8095                    do nothing now and try again after deduction.  */
8096                 return t;
8097               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8098                 error ("mismatched argument pack lengths while expanding "
8099                        "%<%T%>",
8100                        pattern);
8101               else
8102                 error ("mismatched argument pack lengths while expanding "
8103                        "%<%E%>",
8104                        pattern);
8105               return error_mark_node;
8106             }
8107
8108           /* Keep track of the parameter packs and their corresponding
8109              argument packs.  */
8110           packs = tree_cons (parm_pack, arg_pack, packs);
8111           TREE_TYPE (packs) = orig_arg;
8112         }
8113       else
8114         /* We can't substitute for this parameter pack.  */
8115         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8116                                          TREE_VALUE (pack),
8117                                          unsubstituted_packs);
8118     }
8119
8120   /* We cannot expand this expansion expression, because we don't have
8121      all of the argument packs we need. Substitute into the pattern
8122      and return a PACK_EXPANSION_*. The caller will need to deal with
8123      that.  */
8124   if (unsubstituted_packs)
8125     {
8126       tree new_pat;
8127       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8128         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8129                                /*integral_constant_expression_p=*/false);
8130       else
8131         new_pat = tsubst (pattern, args, complain, in_decl);
8132       return make_pack_expansion (new_pat);
8133     }
8134
8135   /* We could not find any argument packs that work.  */
8136   if (len < 0)
8137     return error_mark_node;
8138
8139   if (!local_specializations)
8140     {
8141       /* We're in a late-specified return type, so we don't have a local
8142          specializations table.  Create one for doing this expansion.  */
8143       very_local_specializations = true;
8144       local_specializations = htab_create (37,
8145                                            hash_local_specialization,
8146                                            eq_local_specializations,
8147                                            NULL);
8148     }
8149
8150   /* For each argument in each argument pack, substitute into the
8151      pattern.  */
8152   result = make_tree_vec (len + incomplete);
8153   for (i = 0; i < len + incomplete; ++i)
8154     {
8155       /* For parameter pack, change the substitution of the parameter
8156          pack to the ith argument in its argument pack, then expand
8157          the pattern.  */
8158       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8159         {
8160           tree parm = TREE_PURPOSE (pack);
8161
8162           if (TREE_CODE (parm) == PARM_DECL)
8163             {
8164               /* Select the Ith argument from the pack.  */
8165               tree arg = make_node (ARGUMENT_PACK_SELECT);
8166               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8167               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8168               mark_used (parm);
8169               register_local_specialization (arg, parm);
8170             }
8171           else
8172             {
8173               tree value = parm;
8174               int idx, level;
8175               template_parm_level_and_index (parm, &level, &idx);
8176               
8177               if (i < len) 
8178                 {
8179                   /* Select the Ith argument from the pack. */
8180                   value = make_node (ARGUMENT_PACK_SELECT);
8181                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8182                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8183                 }
8184
8185               /* Update the corresponding argument.  */
8186               TMPL_ARG (args, level, idx) = value;
8187             }
8188         }
8189
8190       /* Substitute into the PATTERN with the altered arguments.  */
8191       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8192         TREE_VEC_ELT (result, i) = 
8193           tsubst_expr (pattern, args, complain, in_decl,
8194                        /*integral_constant_expression_p=*/false);
8195       else
8196         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8197
8198       if (i == len)
8199         /* When we have incomplete argument packs, the last "expanded"
8200            result is itself a pack expansion, which allows us
8201            to deduce more arguments.  */
8202         TREE_VEC_ELT (result, i) = 
8203           make_pack_expansion (TREE_VEC_ELT (result, i));
8204
8205       if (TREE_VEC_ELT (result, i) == error_mark_node)
8206         {
8207           result = error_mark_node;
8208           break;
8209         }
8210     }
8211
8212   /* Update ARGS to restore the substitution from parameter packs to
8213      their argument packs.  */
8214   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8215     {
8216       tree parm = TREE_PURPOSE (pack);
8217
8218       if (TREE_CODE (parm) == PARM_DECL)
8219         register_local_specialization (TREE_TYPE (pack), parm);
8220       else
8221         {
8222           int idx, level;
8223           template_parm_level_and_index (parm, &level, &idx);
8224           
8225           /* Update the corresponding argument.  */
8226           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8227             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8228               TREE_TYPE (pack);
8229           else
8230             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8231         }
8232     }
8233
8234   if (very_local_specializations)
8235     {
8236       htab_delete (local_specializations);
8237       local_specializations = NULL;
8238     }
8239   
8240   return result;
8241 }
8242
8243 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8244    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8245    parameter packs; all parms generated from a function parameter pack will
8246    have the same DECL_PARM_INDEX.  */
8247
8248 tree
8249 get_pattern_parm (tree parm, tree tmpl)
8250 {
8251   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8252   tree patparm;
8253
8254   if (DECL_ARTIFICIAL (parm))
8255     {
8256       for (patparm = DECL_ARGUMENTS (pattern);
8257            patparm; patparm = TREE_CHAIN (patparm))
8258         if (DECL_ARTIFICIAL (patparm)
8259             && DECL_NAME (parm) == DECL_NAME (patparm))
8260           break;
8261     }
8262   else
8263     {
8264       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8265       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8266       gcc_assert (DECL_PARM_INDEX (patparm)
8267                   == DECL_PARM_INDEX (parm));
8268     }
8269
8270   return patparm;
8271 }
8272
8273 /* Substitute ARGS into the vector or list of template arguments T.  */
8274
8275 static tree
8276 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8277 {
8278   tree orig_t = t;
8279   int len = TREE_VEC_LENGTH (t);
8280   int need_new = 0, i, expanded_len_adjust = 0, out;
8281   tree *elts = (tree *) alloca (len * sizeof (tree));
8282
8283   for (i = 0; i < len; i++)
8284     {
8285       tree orig_arg = TREE_VEC_ELT (t, i);
8286       tree new_arg;
8287
8288       if (TREE_CODE (orig_arg) == TREE_VEC)
8289         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8290       else if (PACK_EXPANSION_P (orig_arg))
8291         {
8292           /* Substitute into an expansion expression.  */
8293           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8294
8295           if (TREE_CODE (new_arg) == TREE_VEC)
8296             /* Add to the expanded length adjustment the number of
8297                expanded arguments. We subtract one from this
8298                measurement, because the argument pack expression
8299                itself is already counted as 1 in
8300                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8301                the argument pack is empty.  */
8302             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8303         }
8304       else if (ARGUMENT_PACK_P (orig_arg))
8305         {
8306           /* Substitute into each of the arguments.  */
8307           new_arg = TYPE_P (orig_arg)
8308             ? cxx_make_type (TREE_CODE (orig_arg))
8309             : make_node (TREE_CODE (orig_arg));
8310           
8311           SET_ARGUMENT_PACK_ARGS (
8312             new_arg,
8313             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8314                                   args, complain, in_decl));
8315
8316           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8317             new_arg = error_mark_node;
8318
8319           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8320             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8321                                           complain, in_decl);
8322             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8323
8324             if (TREE_TYPE (new_arg) == error_mark_node)
8325               new_arg = error_mark_node;
8326           }
8327         }
8328       else
8329         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8330
8331       if (new_arg == error_mark_node)
8332         return error_mark_node;
8333
8334       elts[i] = new_arg;
8335       if (new_arg != orig_arg)
8336         need_new = 1;
8337     }
8338
8339   if (!need_new)
8340     return t;
8341
8342   /* Make space for the expanded arguments coming from template
8343      argument packs.  */
8344   t = make_tree_vec (len + expanded_len_adjust);
8345   for (i = 0, out = 0; i < len; i++)
8346     {
8347       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8348            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8349           && TREE_CODE (elts[i]) == TREE_VEC)
8350         {
8351           int idx;
8352
8353           /* Now expand the template argument pack "in place".  */
8354           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8355             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8356         }
8357       else
8358         {
8359           TREE_VEC_ELT (t, out) = elts[i];
8360           out++;
8361         }
8362     }
8363
8364   return t;
8365 }
8366
8367 /* Return the result of substituting ARGS into the template parameters
8368    given by PARMS.  If there are m levels of ARGS and m + n levels of
8369    PARMS, then the result will contain n levels of PARMS.  For
8370    example, if PARMS is `template <class T> template <class U>
8371    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8372    result will be `template <int*, double, class V>'.  */
8373
8374 static tree
8375 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8376 {
8377   tree r = NULL_TREE;
8378   tree* new_parms;
8379
8380   /* When substituting into a template, we must set
8381      PROCESSING_TEMPLATE_DECL as the template parameters may be
8382      dependent if they are based on one-another, and the dependency
8383      predicates are short-circuit outside of templates.  */
8384   ++processing_template_decl;
8385
8386   for (new_parms = &r;
8387        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8388        new_parms = &(TREE_CHAIN (*new_parms)),
8389          parms = TREE_CHAIN (parms))
8390     {
8391       tree new_vec =
8392         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8393       int i;
8394
8395       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8396         {
8397           tree tuple;
8398           tree default_value;
8399           tree parm_decl;
8400
8401           if (parms == error_mark_node)
8402             continue;
8403
8404           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8405
8406           if (tuple == error_mark_node)
8407             continue;
8408
8409           default_value = TREE_PURPOSE (tuple);
8410           parm_decl = TREE_VALUE (tuple);
8411
8412           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8413           if (TREE_CODE (parm_decl) == PARM_DECL
8414               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8415             parm_decl = error_mark_node;
8416           default_value = tsubst_template_arg (default_value, args,
8417                                                complain, NULL_TREE);
8418
8419           tuple = build_tree_list (default_value, parm_decl);
8420           TREE_VEC_ELT (new_vec, i) = tuple;
8421         }
8422
8423       *new_parms =
8424         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8425                              - TMPL_ARGS_DEPTH (args)),
8426                    new_vec, NULL_TREE);
8427     }
8428
8429   --processing_template_decl;
8430
8431   return r;
8432 }
8433
8434 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8435    type T.  If T is not an aggregate or enumeration type, it is
8436    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8437    ENTERING_SCOPE is nonzero, T is the context for a template which
8438    we are presently tsubst'ing.  Return the substituted value.  */
8439
8440 static tree
8441 tsubst_aggr_type (tree t,
8442                   tree args,
8443                   tsubst_flags_t complain,
8444                   tree in_decl,
8445                   int entering_scope)
8446 {
8447   if (t == NULL_TREE)
8448     return NULL_TREE;
8449
8450   switch (TREE_CODE (t))
8451     {
8452     case RECORD_TYPE:
8453       if (TYPE_PTRMEMFUNC_P (t))
8454         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8455
8456       /* Else fall through.  */
8457     case ENUMERAL_TYPE:
8458     case UNION_TYPE:
8459       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8460         {
8461           tree argvec;
8462           tree context;
8463           tree r;
8464           int saved_unevaluated_operand;
8465           int saved_inhibit_evaluation_warnings;
8466
8467           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8468           saved_unevaluated_operand = cp_unevaluated_operand;
8469           cp_unevaluated_operand = 0;
8470           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8471           c_inhibit_evaluation_warnings = 0;
8472
8473           /* First, determine the context for the type we are looking
8474              up.  */
8475           context = TYPE_CONTEXT (t);
8476           if (context)
8477             {
8478               context = tsubst_aggr_type (context, args, complain,
8479                                           in_decl, /*entering_scope=*/1);
8480               /* If context is a nested class inside a class template,
8481                  it may still need to be instantiated (c++/33959).  */
8482               if (TYPE_P (context))
8483                 context = complete_type (context);
8484             }
8485
8486           /* Then, figure out what arguments are appropriate for the
8487              type we are trying to find.  For example, given:
8488
8489                template <class T> struct S;
8490                template <class T, class U> void f(T, U) { S<U> su; }
8491
8492              and supposing that we are instantiating f<int, double>,
8493              then our ARGS will be {int, double}, but, when looking up
8494              S we only want {double}.  */
8495           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8496                                          complain, in_decl);
8497           if (argvec == error_mark_node)
8498             r = error_mark_node;
8499           else
8500             {
8501               r = lookup_template_class (t, argvec, in_decl, context,
8502                                          entering_scope, complain);
8503               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8504             }
8505
8506           cp_unevaluated_operand = saved_unevaluated_operand;
8507           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8508
8509           return r;
8510         }
8511       else
8512         /* This is not a template type, so there's nothing to do.  */
8513         return t;
8514
8515     default:
8516       return tsubst (t, args, complain, in_decl);
8517     }
8518 }
8519
8520 /* Substitute into the default argument ARG (a default argument for
8521    FN), which has the indicated TYPE.  */
8522
8523 tree
8524 tsubst_default_argument (tree fn, tree type, tree arg)
8525 {
8526   tree saved_class_ptr = NULL_TREE;
8527   tree saved_class_ref = NULL_TREE;
8528
8529   /* This default argument came from a template.  Instantiate the
8530      default argument here, not in tsubst.  In the case of
8531      something like:
8532
8533        template <class T>
8534        struct S {
8535          static T t();
8536          void f(T = t());
8537        };
8538
8539      we must be careful to do name lookup in the scope of S<T>,
8540      rather than in the current class.  */
8541   push_access_scope (fn);
8542   /* The "this" pointer is not valid in a default argument.  */
8543   if (cfun)
8544     {
8545       saved_class_ptr = current_class_ptr;
8546       cp_function_chain->x_current_class_ptr = NULL_TREE;
8547       saved_class_ref = current_class_ref;
8548       cp_function_chain->x_current_class_ref = NULL_TREE;
8549     }
8550
8551   push_deferring_access_checks(dk_no_deferred);
8552   /* The default argument expression may cause implicitly defined
8553      member functions to be synthesized, which will result in garbage
8554      collection.  We must treat this situation as if we were within
8555      the body of function so as to avoid collecting live data on the
8556      stack.  */
8557   ++function_depth;
8558   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8559                      tf_warning_or_error, NULL_TREE,
8560                      /*integral_constant_expression_p=*/false);
8561   --function_depth;
8562   pop_deferring_access_checks();
8563
8564   /* Restore the "this" pointer.  */
8565   if (cfun)
8566     {
8567       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8568       cp_function_chain->x_current_class_ref = saved_class_ref;
8569     }
8570
8571   /* Make sure the default argument is reasonable.  */
8572   arg = check_default_argument (type, arg);
8573
8574   pop_access_scope (fn);
8575
8576   return arg;
8577 }
8578
8579 /* Substitute into all the default arguments for FN.  */
8580
8581 static void
8582 tsubst_default_arguments (tree fn)
8583 {
8584   tree arg;
8585   tree tmpl_args;
8586
8587   tmpl_args = DECL_TI_ARGS (fn);
8588
8589   /* If this function is not yet instantiated, we certainly don't need
8590      its default arguments.  */
8591   if (uses_template_parms (tmpl_args))
8592     return;
8593
8594   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8595        arg;
8596        arg = TREE_CHAIN (arg))
8597     if (TREE_PURPOSE (arg))
8598       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8599                                                     TREE_VALUE (arg),
8600                                                     TREE_PURPOSE (arg));
8601 }
8602
8603 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8604    result of the substitution.  Issue error and warning messages under
8605    control of COMPLAIN.  */
8606
8607 static tree
8608 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8609 {
8610 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8611   location_t saved_loc;
8612   tree r = NULL_TREE;
8613   tree in_decl = t;
8614   hashval_t hash = 0;
8615
8616   /* Set the filename and linenumber to improve error-reporting.  */
8617   saved_loc = input_location;
8618   input_location = DECL_SOURCE_LOCATION (t);
8619
8620   switch (TREE_CODE (t))
8621     {
8622     case TEMPLATE_DECL:
8623       {
8624         /* We can get here when processing a member function template,
8625            member class template, or template template parameter.  */
8626         tree decl = DECL_TEMPLATE_RESULT (t);
8627         tree spec;
8628         tree tmpl_args;
8629         tree full_args;
8630
8631         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8632           {
8633             /* Template template parameter is treated here.  */
8634             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8635             if (new_type == error_mark_node)
8636               RETURN (error_mark_node);
8637
8638             r = copy_decl (t);
8639             TREE_CHAIN (r) = NULL_TREE;
8640             TREE_TYPE (r) = new_type;
8641             DECL_TEMPLATE_RESULT (r)
8642               = build_decl (DECL_SOURCE_LOCATION (decl),
8643                             TYPE_DECL, DECL_NAME (decl), new_type);
8644             DECL_TEMPLATE_PARMS (r)
8645               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8646                                        complain);
8647             TYPE_NAME (new_type) = r;
8648             break;
8649           }
8650
8651         /* We might already have an instance of this template.
8652            The ARGS are for the surrounding class type, so the
8653            full args contain the tsubst'd args for the context,
8654            plus the innermost args from the template decl.  */
8655         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8656           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8657           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8658         /* Because this is a template, the arguments will still be
8659            dependent, even after substitution.  If
8660            PROCESSING_TEMPLATE_DECL is not set, the dependency
8661            predicates will short-circuit.  */
8662         ++processing_template_decl;
8663         full_args = tsubst_template_args (tmpl_args, args,
8664                                           complain, in_decl);
8665         --processing_template_decl;
8666         if (full_args == error_mark_node)
8667           RETURN (error_mark_node);
8668
8669         /* If this is a default template template argument,
8670            tsubst might not have changed anything.  */
8671         if (full_args == tmpl_args)
8672           RETURN (t);
8673
8674         hash = hash_tmpl_and_args (t, full_args);
8675         spec = retrieve_specialization (t, full_args, hash);
8676         if (spec != NULL_TREE)
8677           {
8678             r = spec;
8679             break;
8680           }
8681
8682         /* Make a new template decl.  It will be similar to the
8683            original, but will record the current template arguments.
8684            We also create a new function declaration, which is just
8685            like the old one, but points to this new template, rather
8686            than the old one.  */
8687         r = copy_decl (t);
8688         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8689         TREE_CHAIN (r) = NULL_TREE;
8690
8691         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8692
8693         if (TREE_CODE (decl) == TYPE_DECL)
8694           {
8695             tree new_type;
8696             ++processing_template_decl;
8697             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8698             --processing_template_decl;
8699             if (new_type == error_mark_node)
8700               RETURN (error_mark_node);
8701
8702             TREE_TYPE (r) = new_type;
8703             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8704             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8705             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8706             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8707           }
8708         else
8709           {
8710             tree new_decl;
8711             ++processing_template_decl;
8712             new_decl = tsubst (decl, args, complain, in_decl);
8713             --processing_template_decl;
8714             if (new_decl == error_mark_node)
8715               RETURN (error_mark_node);
8716
8717             DECL_TEMPLATE_RESULT (r) = new_decl;
8718             DECL_TI_TEMPLATE (new_decl) = r;
8719             TREE_TYPE (r) = TREE_TYPE (new_decl);
8720             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8721             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8722           }
8723
8724         SET_DECL_IMPLICIT_INSTANTIATION (r);
8725         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8726         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8727
8728         /* The template parameters for this new template are all the
8729            template parameters for the old template, except the
8730            outermost level of parameters.  */
8731         DECL_TEMPLATE_PARMS (r)
8732           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8733                                    complain);
8734
8735         if (PRIMARY_TEMPLATE_P (t))
8736           DECL_PRIMARY_TEMPLATE (r) = r;
8737
8738         if (TREE_CODE (decl) != TYPE_DECL)
8739           /* Record this non-type partial instantiation.  */
8740           register_specialization (r, t,
8741                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8742                                    false, hash);
8743       }
8744       break;
8745
8746     case FUNCTION_DECL:
8747       {
8748         tree ctx;
8749         tree argvec = NULL_TREE;
8750         tree *friends;
8751         tree gen_tmpl;
8752         tree type;
8753         int member;
8754         int args_depth;
8755         int parms_depth;
8756
8757         /* Nobody should be tsubst'ing into non-template functions.  */
8758         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8759
8760         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8761           {
8762             tree spec;
8763             bool dependent_p;
8764
8765             /* If T is not dependent, just return it.  We have to
8766                increment PROCESSING_TEMPLATE_DECL because
8767                value_dependent_expression_p assumes that nothing is
8768                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8769             ++processing_template_decl;
8770             dependent_p = value_dependent_expression_p (t);
8771             --processing_template_decl;
8772             if (!dependent_p)
8773               RETURN (t);
8774
8775             /* Calculate the most general template of which R is a
8776                specialization, and the complete set of arguments used to
8777                specialize R.  */
8778             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8779             argvec = tsubst_template_args (DECL_TI_ARGS
8780                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8781                                            args, complain, in_decl);
8782
8783             /* Check to see if we already have this specialization.  */
8784             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8785             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8786
8787             if (spec)
8788               {
8789                 r = spec;
8790                 break;
8791               }
8792
8793             /* We can see more levels of arguments than parameters if
8794                there was a specialization of a member template, like
8795                this:
8796
8797                  template <class T> struct S { template <class U> void f(); }
8798                  template <> template <class U> void S<int>::f(U);
8799
8800                Here, we'll be substituting into the specialization,
8801                because that's where we can find the code we actually
8802                want to generate, but we'll have enough arguments for
8803                the most general template.
8804
8805                We also deal with the peculiar case:
8806
8807                  template <class T> struct S {
8808                    template <class U> friend void f();
8809                  };
8810                  template <class U> void f() {}
8811                  template S<int>;
8812                  template void f<double>();
8813
8814                Here, the ARGS for the instantiation of will be {int,
8815                double}.  But, we only need as many ARGS as there are
8816                levels of template parameters in CODE_PATTERN.  We are
8817                careful not to get fooled into reducing the ARGS in
8818                situations like:
8819
8820                  template <class T> struct S { template <class U> void f(U); }
8821                  template <class T> template <> void S<T>::f(int) {}
8822
8823                which we can spot because the pattern will be a
8824                specialization in this case.  */
8825             args_depth = TMPL_ARGS_DEPTH (args);
8826             parms_depth =
8827               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8828             if (args_depth > parms_depth
8829                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8830               args = get_innermost_template_args (args, parms_depth);
8831           }
8832         else
8833           {
8834             /* This special case arises when we have something like this:
8835
8836                  template <class T> struct S {
8837                    friend void f<int>(int, double);
8838                  };
8839
8840                Here, the DECL_TI_TEMPLATE for the friend declaration
8841                will be an IDENTIFIER_NODE.  We are being called from
8842                tsubst_friend_function, and we want only to create a
8843                new decl (R) with appropriate types so that we can call
8844                determine_specialization.  */
8845             gen_tmpl = NULL_TREE;
8846           }
8847
8848         if (DECL_CLASS_SCOPE_P (t))
8849           {
8850             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8851               member = 2;
8852             else
8853               member = 1;
8854             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8855                                     complain, t, /*entering_scope=*/1);
8856           }
8857         else
8858           {
8859             member = 0;
8860             ctx = DECL_CONTEXT (t);
8861           }
8862         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8863         if (type == error_mark_node)
8864           RETURN (error_mark_node);
8865
8866         /* We do NOT check for matching decls pushed separately at this
8867            point, as they may not represent instantiations of this
8868            template, and in any case are considered separate under the
8869            discrete model.  */
8870         r = copy_decl (t);
8871         DECL_USE_TEMPLATE (r) = 0;
8872         TREE_TYPE (r) = type;
8873         /* Clear out the mangled name and RTL for the instantiation.  */
8874         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8875         SET_DECL_RTL (r, NULL_RTX);
8876         /* Leave DECL_INITIAL set on deleted instantiations.  */
8877         if (!DECL_DELETED_FN (r))
8878           DECL_INITIAL (r) = NULL_TREE;
8879         DECL_CONTEXT (r) = ctx;
8880
8881         if (member && DECL_CONV_FN_P (r))
8882           /* Type-conversion operator.  Reconstruct the name, in
8883              case it's the name of one of the template's parameters.  */
8884           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8885
8886         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8887                                      complain, t);
8888         DECL_RESULT (r) = NULL_TREE;
8889
8890         TREE_STATIC (r) = 0;
8891         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8892         DECL_EXTERNAL (r) = 1;
8893         /* If this is an instantiation of a function with internal
8894            linkage, we already know what object file linkage will be
8895            assigned to the instantiation.  */
8896         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8897         DECL_DEFER_OUTPUT (r) = 0;
8898         TREE_CHAIN (r) = NULL_TREE;
8899         DECL_PENDING_INLINE_INFO (r) = 0;
8900         DECL_PENDING_INLINE_P (r) = 0;
8901         DECL_SAVED_TREE (r) = NULL_TREE;
8902         DECL_STRUCT_FUNCTION (r) = NULL;
8903         TREE_USED (r) = 0;
8904         /* We'll re-clone as appropriate in instantiate_template.  */
8905         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8906
8907         /* If we aren't complaining now, return on error before we register
8908            the specialization so that we'll complain eventually.  */
8909         if ((complain & tf_error) == 0
8910             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8911             && !grok_op_properties (r, /*complain=*/false))
8912           RETURN (error_mark_node);
8913
8914         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8915            this in the special friend case mentioned above where
8916            GEN_TMPL is NULL.  */
8917         if (gen_tmpl)
8918           {
8919             DECL_TEMPLATE_INFO (r)
8920               = build_template_info (gen_tmpl, argvec);
8921             SET_DECL_IMPLICIT_INSTANTIATION (r);
8922             register_specialization (r, gen_tmpl, argvec, false, hash);
8923
8924             /* We're not supposed to instantiate default arguments
8925                until they are called, for a template.  But, for a
8926                declaration like:
8927
8928                  template <class T> void f ()
8929                  { extern void g(int i = T()); }
8930
8931                we should do the substitution when the template is
8932                instantiated.  We handle the member function case in
8933                instantiate_class_template since the default arguments
8934                might refer to other members of the class.  */
8935             if (!member
8936                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8937                 && !uses_template_parms (argvec))
8938               tsubst_default_arguments (r);
8939           }
8940         else
8941           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8942
8943         /* Copy the list of befriending classes.  */
8944         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8945              *friends;
8946              friends = &TREE_CHAIN (*friends))
8947           {
8948             *friends = copy_node (*friends);
8949             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8950                                             args, complain,
8951                                             in_decl);
8952           }
8953
8954         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8955           {
8956             maybe_retrofit_in_chrg (r);
8957             if (DECL_CONSTRUCTOR_P (r))
8958               grok_ctor_properties (ctx, r);
8959             /* If this is an instantiation of a member template, clone it.
8960                If it isn't, that'll be handled by
8961                clone_constructors_and_destructors.  */
8962             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8963               clone_function_decl (r, /*update_method_vec_p=*/0);
8964           }
8965         else if ((complain & tf_error) != 0
8966                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8967                  && !grok_op_properties (r, /*complain=*/true))
8968           RETURN (error_mark_node);
8969
8970         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8971           SET_DECL_FRIEND_CONTEXT (r,
8972                                    tsubst (DECL_FRIEND_CONTEXT (t),
8973                                             args, complain, in_decl));
8974
8975         /* Possibly limit visibility based on template args.  */
8976         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8977         if (DECL_VISIBILITY_SPECIFIED (t))
8978           {
8979             DECL_VISIBILITY_SPECIFIED (r) = 0;
8980             DECL_ATTRIBUTES (r)
8981               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8982           }
8983         determine_visibility (r);
8984         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
8985             && !processing_template_decl)
8986           defaulted_late_check (r);
8987
8988         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8989                                         args, complain, in_decl);
8990       }
8991       break;
8992
8993     case PARM_DECL:
8994       {
8995         tree type = NULL_TREE;
8996         int i, len = 1;
8997         tree expanded_types = NULL_TREE;
8998         tree prev_r = NULL_TREE;
8999         tree first_r = NULL_TREE;
9000
9001         if (FUNCTION_PARAMETER_PACK_P (t))
9002           {
9003             /* If there is a local specialization that isn't a
9004                parameter pack, it means that we're doing a "simple"
9005                substitution from inside tsubst_pack_expansion. Just
9006                return the local specialization (which will be a single
9007                parm).  */
9008             tree spec = retrieve_local_specialization (t);
9009             if (spec 
9010                 && TREE_CODE (spec) == PARM_DECL
9011                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9012               RETURN (spec);
9013
9014             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9015                the parameters in this function parameter pack.  */
9016             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9017                                                     complain, in_decl);
9018             if (TREE_CODE (expanded_types) == TREE_VEC)
9019               {
9020                 len = TREE_VEC_LENGTH (expanded_types);
9021
9022                 /* Zero-length parameter packs are boring. Just substitute
9023                    into the chain.  */
9024                 if (len == 0)
9025                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9026                                   TREE_CHAIN (t)));
9027               }
9028             else
9029               {
9030                 /* All we did was update the type. Make a note of that.  */
9031                 type = expanded_types;
9032                 expanded_types = NULL_TREE;
9033               }
9034           }
9035
9036         /* Loop through all of the parameter's we'll build. When T is
9037            a function parameter pack, LEN is the number of expanded
9038            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9039         r = NULL_TREE;
9040         for (i = 0; i < len; ++i)
9041           {
9042             prev_r = r;
9043             r = copy_node (t);
9044             if (DECL_TEMPLATE_PARM_P (t))
9045               SET_DECL_TEMPLATE_PARM_P (r);
9046
9047             /* An argument of a function parameter pack is not a parameter
9048                pack.  */
9049             FUNCTION_PARAMETER_PACK_P (r) = false;
9050
9051             if (expanded_types)
9052               /* We're on the Ith parameter of the function parameter
9053                  pack.  */
9054               {
9055                 /* Get the Ith type.  */
9056                 type = TREE_VEC_ELT (expanded_types, i);
9057
9058                 if (DECL_NAME (r))
9059                   /* Rename the parameter to include the index.  */
9060                   DECL_NAME (r) =
9061                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9062               }
9063             else if (!type)
9064               /* We're dealing with a normal parameter.  */
9065               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9066
9067             type = type_decays_to (type);
9068             TREE_TYPE (r) = type;
9069             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9070
9071             if (DECL_INITIAL (r))
9072               {
9073                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9074                   DECL_INITIAL (r) = TREE_TYPE (r);
9075                 else
9076                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9077                                              complain, in_decl);
9078               }
9079
9080             DECL_CONTEXT (r) = NULL_TREE;
9081
9082             if (!DECL_TEMPLATE_PARM_P (r))
9083               DECL_ARG_TYPE (r) = type_passed_as (type);
9084
9085             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9086                                             args, complain, in_decl);
9087
9088             /* Keep track of the first new parameter we
9089                generate. That's what will be returned to the
9090                caller.  */
9091             if (!first_r)
9092               first_r = r;
9093
9094             /* Build a proper chain of parameters when substituting
9095                into a function parameter pack.  */
9096             if (prev_r)
9097               TREE_CHAIN (prev_r) = r;
9098           }
9099
9100         if (TREE_CHAIN (t))
9101           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9102                                    complain, TREE_CHAIN (t));
9103
9104         /* FIRST_R contains the start of the chain we've built.  */
9105         r = first_r;
9106       }
9107       break;
9108
9109     case FIELD_DECL:
9110       {
9111         tree type;
9112
9113         r = copy_decl (t);
9114         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9115         if (type == error_mark_node)
9116           RETURN (error_mark_node);
9117         TREE_TYPE (r) = type;
9118         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9119
9120         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9121         DECL_INITIAL (r)
9122           = tsubst_expr (DECL_INITIAL (t), args,
9123                          complain, in_decl,
9124                          /*integral_constant_expression_p=*/true);
9125         /* We don't have to set DECL_CONTEXT here; it is set by
9126            finish_member_declaration.  */
9127         TREE_CHAIN (r) = NULL_TREE;
9128         if (VOID_TYPE_P (type))
9129           error ("instantiation of %q+D as type %qT", r, type);
9130
9131         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9132                                         args, complain, in_decl);
9133       }
9134       break;
9135
9136     case USING_DECL:
9137       /* We reach here only for member using decls.  */
9138       if (DECL_DEPENDENT_P (t))
9139         {
9140           r = do_class_using_decl
9141             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9142              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9143           if (!r)
9144             r = error_mark_node;
9145           else
9146             {
9147               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9148               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9149             }
9150         }
9151       else
9152         {
9153           r = copy_node (t);
9154           TREE_CHAIN (r) = NULL_TREE;
9155         }
9156       break;
9157
9158     case TYPE_DECL:
9159     case VAR_DECL:
9160       {
9161         tree argvec = NULL_TREE;
9162         tree gen_tmpl = NULL_TREE;
9163         tree spec;
9164         tree tmpl = NULL_TREE;
9165         tree ctx;
9166         tree type = NULL_TREE;
9167         bool local_p;
9168
9169         if (TREE_CODE (t) == TYPE_DECL
9170             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9171           {
9172             /* If this is the canonical decl, we don't have to
9173                mess with instantiations, and often we can't (for
9174                typename, template type parms and such).  Note that
9175                TYPE_NAME is not correct for the above test if
9176                we've copied the type for a typedef.  */
9177             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9178             if (type == error_mark_node)
9179               RETURN (error_mark_node);
9180             r = TYPE_NAME (type);
9181             break;
9182           }
9183
9184         /* Check to see if we already have the specialization we
9185            need.  */
9186         spec = NULL_TREE;
9187         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9188           {
9189             /* T is a static data member or namespace-scope entity.
9190                We have to substitute into namespace-scope variables
9191                (even though such entities are never templates) because
9192                of cases like:
9193                
9194                  template <class T> void f() { extern T t; }
9195
9196                where the entity referenced is not known until
9197                instantiation time.  */
9198             local_p = false;
9199             ctx = DECL_CONTEXT (t);
9200             if (DECL_CLASS_SCOPE_P (t))
9201               {
9202                 ctx = tsubst_aggr_type (ctx, args,
9203                                         complain,
9204                                         in_decl, /*entering_scope=*/1);
9205                 /* If CTX is unchanged, then T is in fact the
9206                    specialization we want.  That situation occurs when
9207                    referencing a static data member within in its own
9208                    class.  We can use pointer equality, rather than
9209                    same_type_p, because DECL_CONTEXT is always
9210                    canonical.  */
9211                 if (ctx == DECL_CONTEXT (t))
9212                   spec = t;
9213               }
9214
9215             if (!spec)
9216               {
9217                 tmpl = DECL_TI_TEMPLATE (t);
9218                 gen_tmpl = most_general_template (tmpl);
9219                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9220                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9221                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9222               }
9223           }
9224         else
9225           {
9226             /* A local variable.  */
9227             local_p = true;
9228             /* Subsequent calls to pushdecl will fill this in.  */
9229             ctx = NULL_TREE;
9230             spec = retrieve_local_specialization (t);
9231           }
9232         /* If we already have the specialization we need, there is
9233            nothing more to do.  */ 
9234         if (spec)
9235           {
9236             r = spec;
9237             break;
9238           }
9239
9240         /* Create a new node for the specialization we need.  */
9241         r = copy_decl (t);
9242         if (type == NULL_TREE)
9243           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9244         if (TREE_CODE (r) == VAR_DECL)
9245           {
9246             /* Even if the original location is out of scope, the
9247                newly substituted one is not.  */
9248             DECL_DEAD_FOR_LOCAL (r) = 0;
9249             DECL_INITIALIZED_P (r) = 0;
9250             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9251             if (type == error_mark_node)
9252               RETURN (error_mark_node);
9253             if (TREE_CODE (type) == FUNCTION_TYPE)
9254               {
9255                 /* It may seem that this case cannot occur, since:
9256
9257                      typedef void f();
9258                      void g() { f x; }
9259
9260                    declares a function, not a variable.  However:
9261       
9262                      typedef void f();
9263                      template <typename T> void g() { T t; }
9264                      template void g<f>();
9265
9266                    is an attempt to declare a variable with function
9267                    type.  */
9268                 error ("variable %qD has function type",
9269                        /* R is not yet sufficiently initialized, so we
9270                           just use its name.  */
9271                        DECL_NAME (r));
9272                 RETURN (error_mark_node);
9273               }
9274             type = complete_type (type);
9275             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9276               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9277             type = check_var_type (DECL_NAME (r), type);
9278
9279             if (DECL_HAS_VALUE_EXPR_P (t))
9280               {
9281                 tree ve = DECL_VALUE_EXPR (t);
9282                 ve = tsubst_expr (ve, args, complain, in_decl,
9283                                   /*constant_expression_p=*/false);
9284                 SET_DECL_VALUE_EXPR (r, ve);
9285               }
9286           }
9287         else if (DECL_SELF_REFERENCE_P (t))
9288           SET_DECL_SELF_REFERENCE_P (r);
9289         TREE_TYPE (r) = type;
9290         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9291         DECL_CONTEXT (r) = ctx;
9292         /* Clear out the mangled name and RTL for the instantiation.  */
9293         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9294         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9295           SET_DECL_RTL (r, NULL_RTX);
9296         /* The initializer must not be expanded until it is required;
9297            see [temp.inst].  */
9298         DECL_INITIAL (r) = NULL_TREE;
9299         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9300           SET_DECL_RTL (r, NULL_RTX);
9301         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9302         if (TREE_CODE (r) == VAR_DECL)
9303           {
9304             /* Possibly limit visibility based on template args.  */
9305             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9306             if (DECL_VISIBILITY_SPECIFIED (t))
9307               {
9308                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9309                 DECL_ATTRIBUTES (r)
9310                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9311               }
9312             determine_visibility (r);
9313           }
9314         /* Preserve a typedef that names a type.  */
9315         else if (TREE_CODE (r) == TYPE_DECL
9316                  && DECL_ORIGINAL_TYPE (t)
9317                  && type != error_mark_node)
9318           {
9319             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9320                                              args, complain, in_decl);
9321             TREE_TYPE (r) = type = build_variant_type_copy (type);
9322             TYPE_NAME (type) = r;
9323           }
9324
9325         if (!local_p)
9326           {
9327             /* A static data member declaration is always marked
9328                external when it is declared in-class, even if an
9329                initializer is present.  We mimic the non-template
9330                processing here.  */
9331             DECL_EXTERNAL (r) = 1;
9332
9333             register_specialization (r, gen_tmpl, argvec, false, hash);
9334             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9335             SET_DECL_IMPLICIT_INSTANTIATION (r);
9336           }
9337         else if (cp_unevaluated_operand)
9338           {
9339             /* We're substituting this var in a decltype outside of its
9340                scope, such as for a lambda return type.  Don't add it to
9341                local_specializations, do perform auto deduction.  */
9342             tree auto_node = type_uses_auto (type);
9343             tree init
9344               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9345                              /*constant_expression_p=*/false);
9346
9347             if (auto_node && init && describable_type (init))
9348               {
9349                 type = do_auto_deduction (type, init, auto_node);
9350                 TREE_TYPE (r) = type;
9351               }
9352           }
9353         else
9354           register_local_specialization (r, t);
9355
9356         TREE_CHAIN (r) = NULL_TREE;
9357
9358         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9359                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9360                                         args, complain, in_decl);
9361         layout_decl (r, 0);
9362       }
9363       break;
9364
9365     default:
9366       gcc_unreachable ();
9367     }
9368 #undef RETURN
9369
9370  out:
9371   /* Restore the file and line information.  */
9372   input_location = saved_loc;
9373
9374   return r;
9375 }
9376
9377 /* Substitute into the ARG_TYPES of a function type.  */
9378
9379 static tree
9380 tsubst_arg_types (tree arg_types,
9381                   tree args,
9382                   tsubst_flags_t complain,
9383                   tree in_decl)
9384 {
9385   tree remaining_arg_types;
9386   tree type = NULL_TREE;
9387   int i = 1;
9388   tree expanded_args = NULL_TREE;
9389   tree default_arg;
9390
9391   if (!arg_types || arg_types == void_list_node)
9392     return arg_types;
9393
9394   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9395                                           args, complain, in_decl);
9396   if (remaining_arg_types == error_mark_node)
9397     return error_mark_node;
9398
9399   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9400     {
9401       /* For a pack expansion, perform substitution on the
9402          entire expression. Later on, we'll handle the arguments
9403          one-by-one.  */
9404       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9405                                             args, complain, in_decl);
9406
9407       if (TREE_CODE (expanded_args) == TREE_VEC)
9408         /* So that we'll spin through the parameters, one by one.  */
9409         i = TREE_VEC_LENGTH (expanded_args);
9410       else
9411         {
9412           /* We only partially substituted into the parameter
9413              pack. Our type is TYPE_PACK_EXPANSION.  */
9414           type = expanded_args;
9415           expanded_args = NULL_TREE;
9416         }
9417     }
9418
9419   while (i > 0) {
9420     --i;
9421     
9422     if (expanded_args)
9423       type = TREE_VEC_ELT (expanded_args, i);
9424     else if (!type)
9425       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9426
9427     if (type == error_mark_node)
9428       return error_mark_node;
9429     if (VOID_TYPE_P (type))
9430       {
9431         if (complain & tf_error)
9432           {
9433             error ("invalid parameter type %qT", type);
9434             if (in_decl)
9435               error ("in declaration %q+D", in_decl);
9436           }
9437         return error_mark_node;
9438     }
9439     
9440     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9441        top-level qualifiers as required.  */
9442     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9443
9444     /* We do not substitute into default arguments here.  The standard
9445        mandates that they be instantiated only when needed, which is
9446        done in build_over_call.  */
9447     default_arg = TREE_PURPOSE (arg_types);
9448
9449     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9450       {
9451         /* We've instantiated a template before its default arguments
9452            have been parsed.  This can happen for a nested template
9453            class, and is not an error unless we require the default
9454            argument in a call of this function.  */
9455         remaining_arg_types = 
9456           tree_cons (default_arg, type, remaining_arg_types);
9457         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9458                        remaining_arg_types);
9459       }
9460     else
9461       remaining_arg_types = 
9462         hash_tree_cons (default_arg, type, remaining_arg_types);
9463   }
9464         
9465   return remaining_arg_types;
9466 }
9467
9468 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9469    *not* handle the exception-specification for FNTYPE, because the
9470    initial substitution of explicitly provided template parameters
9471    during argument deduction forbids substitution into the
9472    exception-specification:
9473
9474      [temp.deduct]
9475
9476      All references in the function type of the function template to  the
9477      corresponding template parameters are replaced by the specified tem-
9478      plate argument values.  If a substitution in a template parameter or
9479      in  the function type of the function template results in an invalid
9480      type, type deduction fails.  [Note: The equivalent  substitution  in
9481      exception specifications is done only when the function is instanti-
9482      ated, at which point a program is  ill-formed  if  the  substitution
9483      results in an invalid type.]  */
9484
9485 static tree
9486 tsubst_function_type (tree t,
9487                       tree args,
9488                       tsubst_flags_t complain,
9489                       tree in_decl)
9490 {
9491   tree return_type;
9492   tree arg_types;
9493   tree fntype;
9494
9495   /* The TYPE_CONTEXT is not used for function/method types.  */
9496   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9497
9498   /* Substitute the return type.  */
9499   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9500   if (return_type == error_mark_node)
9501     return error_mark_node;
9502   /* The standard does not presently indicate that creation of a
9503      function type with an invalid return type is a deduction failure.
9504      However, that is clearly analogous to creating an array of "void"
9505      or a reference to a reference.  This is core issue #486.  */
9506   if (TREE_CODE (return_type) == ARRAY_TYPE
9507       || TREE_CODE (return_type) == FUNCTION_TYPE)
9508     {
9509       if (complain & tf_error)
9510         {
9511           if (TREE_CODE (return_type) == ARRAY_TYPE)
9512             error ("function returning an array");
9513           else
9514             error ("function returning a function");
9515         }
9516       return error_mark_node;
9517     }
9518
9519   /* Substitute the argument types.  */
9520   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9521                                 complain, in_decl);
9522   if (arg_types == error_mark_node)
9523     return error_mark_node;
9524
9525   /* Construct a new type node and return it.  */
9526   if (TREE_CODE (t) == FUNCTION_TYPE)
9527     fntype = build_function_type (return_type, arg_types);
9528   else
9529     {
9530       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9531       if (! MAYBE_CLASS_TYPE_P (r))
9532         {
9533           /* [temp.deduct]
9534
9535              Type deduction may fail for any of the following
9536              reasons:
9537
9538              -- Attempting to create "pointer to member of T" when T
9539              is not a class type.  */
9540           if (complain & tf_error)
9541             error ("creating pointer to member function of non-class type %qT",
9542                       r);
9543           return error_mark_node;
9544         }
9545
9546       fntype = build_method_type_directly (r, return_type,
9547                                            TREE_CHAIN (arg_types));
9548     }
9549   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9550   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9551
9552   return fntype;
9553 }
9554
9555 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9556    ARGS into that specification, and return the substituted
9557    specification.  If there is no specification, return NULL_TREE.  */
9558
9559 static tree
9560 tsubst_exception_specification (tree fntype,
9561                                 tree args,
9562                                 tsubst_flags_t complain,
9563                                 tree in_decl)
9564 {
9565   tree specs;
9566   tree new_specs;
9567
9568   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9569   new_specs = NULL_TREE;
9570   if (specs)
9571     {
9572       if (! TREE_VALUE (specs))
9573         new_specs = specs;
9574       else
9575         while (specs)
9576           {
9577             tree spec;
9578             int i, len = 1;
9579             tree expanded_specs = NULL_TREE;
9580
9581             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9582               {
9583                 /* Expand the pack expansion type.  */
9584                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9585                                                        args, complain,
9586                                                        in_decl);
9587
9588                 if (expanded_specs == error_mark_node)
9589                   return error_mark_node;
9590                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9591                   len = TREE_VEC_LENGTH (expanded_specs);
9592                 else
9593                   {
9594                     /* We're substituting into a member template, so
9595                        we got a TYPE_PACK_EXPANSION back.  Add that
9596                        expansion and move on.  */
9597                     gcc_assert (TREE_CODE (expanded_specs) 
9598                                 == TYPE_PACK_EXPANSION);
9599                     new_specs = add_exception_specifier (new_specs,
9600                                                          expanded_specs,
9601                                                          complain);
9602                     specs = TREE_CHAIN (specs);
9603                     continue;
9604                   }
9605               }
9606
9607             for (i = 0; i < len; ++i)
9608               {
9609                 if (expanded_specs)
9610                   spec = TREE_VEC_ELT (expanded_specs, i);
9611                 else
9612                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9613                 if (spec == error_mark_node)
9614                   return spec;
9615                 new_specs = add_exception_specifier (new_specs, spec, 
9616                                                      complain);
9617               }
9618
9619             specs = TREE_CHAIN (specs);
9620           }
9621     }
9622   return new_specs;
9623 }
9624
9625 /* Take the tree structure T and replace template parameters used
9626    therein with the argument vector ARGS.  IN_DECL is an associated
9627    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9628    Issue error and warning messages under control of COMPLAIN.  Note
9629    that we must be relatively non-tolerant of extensions here, in
9630    order to preserve conformance; if we allow substitutions that
9631    should not be allowed, we may allow argument deductions that should
9632    not succeed, and therefore report ambiguous overload situations
9633    where there are none.  In theory, we could allow the substitution,
9634    but indicate that it should have failed, and allow our caller to
9635    make sure that the right thing happens, but we don't try to do this
9636    yet.
9637
9638    This function is used for dealing with types, decls and the like;
9639    for expressions, use tsubst_expr or tsubst_copy.  */
9640
9641 tree
9642 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9643 {
9644   tree type, r;
9645
9646   if (t == NULL_TREE || t == error_mark_node
9647       || t == integer_type_node
9648       || t == void_type_node
9649       || t == char_type_node
9650       || t == unknown_type_node
9651       || TREE_CODE (t) == NAMESPACE_DECL)
9652     return t;
9653
9654   if (DECL_P (t))
9655     return tsubst_decl (t, args, complain);
9656
9657   if (args == NULL_TREE)
9658     return t;
9659
9660   if (TREE_CODE (t) == IDENTIFIER_NODE)
9661     type = IDENTIFIER_TYPE_VALUE (t);
9662   else
9663     type = TREE_TYPE (t);
9664
9665   gcc_assert (type != unknown_type_node);
9666
9667   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9668      such as attribute aligned.  */
9669   if (TYPE_P (t)
9670       && TYPE_NAME (t)
9671       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9672     {
9673       tree decl = TYPE_NAME (t);
9674       
9675       if (DECL_CLASS_SCOPE_P (decl)
9676           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9677           && uses_template_parms (DECL_CONTEXT (decl)))
9678         {
9679           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9680           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9681           r = retrieve_specialization (tmpl, gen_args, 0);
9682         }
9683       else if (DECL_FUNCTION_SCOPE_P (decl)
9684                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9685                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9686         r = retrieve_local_specialization (decl);
9687       else
9688         /* The typedef is from a non-template context.  */
9689         return t;
9690
9691       if (r)
9692         {
9693           r = TREE_TYPE (r);
9694           r = cp_build_qualified_type_real
9695             (r, cp_type_quals (t) | cp_type_quals (r),
9696              complain | tf_ignore_bad_quals);
9697           return r;
9698         }
9699       /* Else we must be instantiating the typedef, so fall through.  */
9700     }
9701
9702   if (type
9703       && TREE_CODE (t) != TYPENAME_TYPE
9704       && TREE_CODE (t) != IDENTIFIER_NODE
9705       && TREE_CODE (t) != FUNCTION_TYPE
9706       && TREE_CODE (t) != METHOD_TYPE)
9707     type = tsubst (type, args, complain, in_decl);
9708   if (type == error_mark_node)
9709     return error_mark_node;
9710
9711   switch (TREE_CODE (t))
9712     {
9713     case RECORD_TYPE:
9714     case UNION_TYPE:
9715     case ENUMERAL_TYPE:
9716       return tsubst_aggr_type (t, args, complain, in_decl,
9717                                /*entering_scope=*/0);
9718
9719     case ERROR_MARK:
9720     case IDENTIFIER_NODE:
9721     case VOID_TYPE:
9722     case REAL_TYPE:
9723     case COMPLEX_TYPE:
9724     case VECTOR_TYPE:
9725     case BOOLEAN_TYPE:
9726     case INTEGER_CST:
9727     case REAL_CST:
9728     case STRING_CST:
9729       return t;
9730
9731     case INTEGER_TYPE:
9732       if (t == integer_type_node)
9733         return t;
9734
9735       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9736           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9737         return t;
9738
9739       {
9740         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9741
9742         max = tsubst_expr (omax, args, complain, in_decl,
9743                            /*integral_constant_expression_p=*/false);
9744
9745         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9746            needed.  */
9747         if (TREE_CODE (max) == NOP_EXPR
9748             && TREE_SIDE_EFFECTS (omax)
9749             && !TREE_TYPE (max))
9750           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9751
9752         max = fold_decl_constant_value (max);
9753
9754         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9755            with TREE_SIDE_EFFECTS that indicates this is not an integral
9756            constant expression.  */
9757         if (processing_template_decl
9758             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9759           {
9760             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9761             TREE_SIDE_EFFECTS (max) = 1;
9762           }
9763
9764         if (TREE_CODE (max) != INTEGER_CST
9765             && !at_function_scope_p ()
9766             && !TREE_SIDE_EFFECTS (max)
9767             && !value_dependent_expression_p (max))
9768           {
9769             if (complain & tf_error)
9770               error ("array bound is not an integer constant");
9771             return error_mark_node;
9772           }
9773
9774         /* [temp.deduct]
9775
9776            Type deduction may fail for any of the following
9777            reasons:
9778
9779              Attempting to create an array with a size that is
9780              zero or negative.  */
9781         if (integer_zerop (max) && !(complain & tf_error))
9782           /* We must fail if performing argument deduction (as
9783              indicated by the state of complain), so that
9784              another substitution can be found.  */
9785           return error_mark_node;
9786         else if (TREE_CODE (max) == INTEGER_CST
9787                  && INT_CST_LT (max, integer_zero_node))
9788           {
9789             if (complain & tf_error)
9790               error ("creating array with negative size (%qE)", max);
9791
9792             return error_mark_node;
9793           }
9794
9795         return compute_array_index_type (NULL_TREE, max);
9796       }
9797
9798     case TEMPLATE_TYPE_PARM:
9799     case TEMPLATE_TEMPLATE_PARM:
9800     case BOUND_TEMPLATE_TEMPLATE_PARM:
9801     case TEMPLATE_PARM_INDEX:
9802       {
9803         int idx;
9804         int level;
9805         int levels;
9806         tree arg = NULL_TREE;
9807
9808         r = NULL_TREE;
9809
9810         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9811         template_parm_level_and_index (t, &level, &idx); 
9812
9813         levels = TMPL_ARGS_DEPTH (args);
9814         if (level <= levels)
9815           {
9816             arg = TMPL_ARG (args, level, idx);
9817
9818             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9819               /* See through ARGUMENT_PACK_SELECT arguments. */
9820               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9821           }
9822
9823         if (arg == error_mark_node)
9824           return error_mark_node;
9825         else if (arg != NULL_TREE)
9826           {
9827             if (ARGUMENT_PACK_P (arg))
9828               /* If ARG is an argument pack, we don't actually want to
9829                  perform a substitution here, because substitutions
9830                  for argument packs are only done
9831                  element-by-element. We can get to this point when
9832                  substituting the type of a non-type template
9833                  parameter pack, when that type actually contains
9834                  template parameter packs from an outer template, e.g.,
9835
9836                  template<typename... Types> struct A {
9837                    template<Types... Values> struct B { };
9838                  };  */
9839               return t;
9840
9841             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9842               {
9843                 int quals;
9844                 gcc_assert (TYPE_P (arg));
9845
9846                 /* cv-quals from the template are discarded when
9847                    substituting in a function or reference type.  */
9848                 if (TREE_CODE (arg) == FUNCTION_TYPE
9849                     || TREE_CODE (arg) == METHOD_TYPE
9850                     || TREE_CODE (arg) == REFERENCE_TYPE)
9851                   quals = cp_type_quals (arg);
9852                 else
9853                   quals = cp_type_quals (arg) | cp_type_quals (t);
9854                   
9855                 return cp_build_qualified_type_real
9856                   (arg, quals, complain | tf_ignore_bad_quals);
9857               }
9858             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9859               {
9860                 /* We are processing a type constructed from a
9861                    template template parameter.  */
9862                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9863                                       args, complain, in_decl);
9864                 if (argvec == error_mark_node)
9865                   return error_mark_node;
9866
9867                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9868                    are resolving nested-types in the signature of a
9869                    member function templates.  Otherwise ARG is a
9870                    TEMPLATE_DECL and is the real template to be
9871                    instantiated.  */
9872                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9873                   arg = TYPE_NAME (arg);
9874
9875                 r = lookup_template_class (arg,
9876                                            argvec, in_decl,
9877                                            DECL_CONTEXT (arg),
9878                                             /*entering_scope=*/0,
9879                                            complain);
9880                 return cp_build_qualified_type_real
9881                   (r, TYPE_QUALS (t), complain);
9882               }
9883             else
9884               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9885               return arg;
9886           }
9887
9888         if (level == 1)
9889           /* This can happen during the attempted tsubst'ing in
9890              unify.  This means that we don't yet have any information
9891              about the template parameter in question.  */
9892           return t;
9893
9894         /* If we get here, we must have been looking at a parm for a
9895            more deeply nested template.  Make a new version of this
9896            template parameter, but with a lower level.  */
9897         switch (TREE_CODE (t))
9898           {
9899           case TEMPLATE_TYPE_PARM:
9900           case TEMPLATE_TEMPLATE_PARM:
9901           case BOUND_TEMPLATE_TEMPLATE_PARM:
9902             if (cp_type_quals (t))
9903               {
9904                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9905                 r = cp_build_qualified_type_real
9906                   (r, cp_type_quals (t),
9907                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9908                                ? tf_ignore_bad_quals : 0));
9909               }
9910             else
9911               {
9912                 r = copy_type (t);
9913                 TEMPLATE_TYPE_PARM_INDEX (r)
9914                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9915                                                 r, levels, args, complain);
9916                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9917                 TYPE_MAIN_VARIANT (r) = r;
9918                 TYPE_POINTER_TO (r) = NULL_TREE;
9919                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9920
9921                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9922                   /* We have reduced the level of the template
9923                      template parameter, but not the levels of its
9924                      template parameters, so canonical_type_parameter
9925                      will not be able to find the canonical template
9926                      template parameter for this level. Thus, we
9927                      require structural equality checking to compare
9928                      TEMPLATE_TEMPLATE_PARMs. */
9929                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9930                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9931                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9932                 else
9933                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9934
9935                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9936                   {
9937                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9938                                           complain, in_decl);
9939                     if (argvec == error_mark_node)
9940                       return error_mark_node;
9941
9942                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9943                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
9944                   }
9945               }
9946             break;
9947
9948           case TEMPLATE_PARM_INDEX:
9949             r = reduce_template_parm_level (t, type, levels, args, complain);
9950             break;
9951
9952           default:
9953             gcc_unreachable ();
9954           }
9955
9956         return r;
9957       }
9958
9959     case TREE_LIST:
9960       {
9961         tree purpose, value, chain;
9962
9963         if (t == void_list_node)
9964           return t;
9965
9966         purpose = TREE_PURPOSE (t);
9967         if (purpose)
9968           {
9969             purpose = tsubst (purpose, args, complain, in_decl);
9970             if (purpose == error_mark_node)
9971               return error_mark_node;
9972           }
9973         value = TREE_VALUE (t);
9974         if (value)
9975           {
9976             value = tsubst (value, args, complain, in_decl);
9977             if (value == error_mark_node)
9978               return error_mark_node;
9979           }
9980         chain = TREE_CHAIN (t);
9981         if (chain && chain != void_type_node)
9982           {
9983             chain = tsubst (chain, args, complain, in_decl);
9984             if (chain == error_mark_node)
9985               return error_mark_node;
9986           }
9987         if (purpose == TREE_PURPOSE (t)
9988             && value == TREE_VALUE (t)
9989             && chain == TREE_CHAIN (t))
9990           return t;
9991         return hash_tree_cons (purpose, value, chain);
9992       }
9993
9994     case TREE_BINFO:
9995       /* We should never be tsubsting a binfo.  */
9996       gcc_unreachable ();
9997
9998     case TREE_VEC:
9999       /* A vector of template arguments.  */
10000       gcc_assert (!type);
10001       return tsubst_template_args (t, args, complain, in_decl);
10002
10003     case POINTER_TYPE:
10004     case REFERENCE_TYPE:
10005       {
10006         enum tree_code code;
10007
10008         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10009           return t;
10010
10011         code = TREE_CODE (t);
10012
10013
10014         /* [temp.deduct]
10015
10016            Type deduction may fail for any of the following
10017            reasons:
10018
10019            -- Attempting to create a pointer to reference type.
10020            -- Attempting to create a reference to a reference type or
10021               a reference to void.
10022
10023           Core issue 106 says that creating a reference to a reference
10024           during instantiation is no longer a cause for failure. We
10025           only enforce this check in strict C++98 mode.  */
10026         if ((TREE_CODE (type) == REFERENCE_TYPE
10027              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10028             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10029           {
10030             static location_t last_loc;
10031
10032             /* We keep track of the last time we issued this error
10033                message to avoid spewing a ton of messages during a
10034                single bad template instantiation.  */
10035             if (complain & tf_error
10036                 && last_loc != input_location)
10037               {
10038                 if (TREE_CODE (type) == VOID_TYPE)
10039                   error ("forming reference to void");
10040                 else
10041                   error ("forming %s to reference type %qT",
10042                          (code == POINTER_TYPE) ? "pointer" : "reference",
10043                          type);
10044                 last_loc = input_location;
10045               }
10046
10047             return error_mark_node;
10048           }
10049         else if (code == POINTER_TYPE)
10050           {
10051             r = build_pointer_type (type);
10052             if (TREE_CODE (type) == METHOD_TYPE)
10053               r = build_ptrmemfunc_type (r);
10054           }
10055         else if (TREE_CODE (type) == REFERENCE_TYPE)
10056           /* In C++0x, during template argument substitution, when there is an
10057              attempt to create a reference to a reference type, reference
10058              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10059
10060              "If a template-argument for a template-parameter T names a type
10061              that is a reference to a type A, an attempt to create the type
10062              'lvalue reference to cv T' creates the type 'lvalue reference to
10063              A,' while an attempt to create the type type rvalue reference to
10064              cv T' creates the type T"
10065           */
10066           r = cp_build_reference_type
10067               (TREE_TYPE (type),
10068                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10069         else
10070           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10071         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10072
10073         if (r != error_mark_node)
10074           /* Will this ever be needed for TYPE_..._TO values?  */
10075           layout_type (r);
10076
10077         return r;
10078       }
10079     case OFFSET_TYPE:
10080       {
10081         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10082         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10083           {
10084             /* [temp.deduct]
10085
10086                Type deduction may fail for any of the following
10087                reasons:
10088
10089                -- Attempting to create "pointer to member of T" when T
10090                   is not a class type.  */
10091             if (complain & tf_error)
10092               error ("creating pointer to member of non-class type %qT", r);
10093             return error_mark_node;
10094           }
10095         if (TREE_CODE (type) == REFERENCE_TYPE)
10096           {
10097             if (complain & tf_error)
10098               error ("creating pointer to member reference type %qT", type);
10099             return error_mark_node;
10100           }
10101         if (TREE_CODE (type) == VOID_TYPE)
10102           {
10103             if (complain & tf_error)
10104               error ("creating pointer to member of type void");
10105             return error_mark_node;
10106           }
10107         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10108         if (TREE_CODE (type) == FUNCTION_TYPE)
10109           {
10110             /* The type of the implicit object parameter gets its
10111                cv-qualifiers from the FUNCTION_TYPE. */
10112             tree memptr;
10113             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10114             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10115             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10116                                                  complain);
10117           }
10118         else
10119           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10120                                                TYPE_QUALS (t),
10121                                                complain);
10122       }
10123     case FUNCTION_TYPE:
10124     case METHOD_TYPE:
10125       {
10126         tree fntype;
10127         tree specs;
10128         fntype = tsubst_function_type (t, args, complain, in_decl);
10129         if (fntype == error_mark_node)
10130           return error_mark_node;
10131
10132         /* Substitute the exception specification.  */
10133         specs = tsubst_exception_specification (t, args, complain,
10134                                                 in_decl);
10135         if (specs == error_mark_node)
10136           return error_mark_node;
10137         if (specs)
10138           fntype = build_exception_variant (fntype, specs);
10139         return fntype;
10140       }
10141     case ARRAY_TYPE:
10142       {
10143         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10144         if (domain == error_mark_node)
10145           return error_mark_node;
10146
10147         /* As an optimization, we avoid regenerating the array type if
10148            it will obviously be the same as T.  */
10149         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10150           return t;
10151
10152         /* These checks should match the ones in grokdeclarator.
10153
10154            [temp.deduct]
10155
10156            The deduction may fail for any of the following reasons:
10157
10158            -- Attempting to create an array with an element type that
10159               is void, a function type, or a reference type, or [DR337]
10160               an abstract class type.  */
10161         if (TREE_CODE (type) == VOID_TYPE
10162             || TREE_CODE (type) == FUNCTION_TYPE
10163             || TREE_CODE (type) == REFERENCE_TYPE)
10164           {
10165             if (complain & tf_error)
10166               error ("creating array of %qT", type);
10167             return error_mark_node;
10168           }
10169         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10170           {
10171             if (complain & tf_error)
10172               error ("creating array of %qT, which is an abstract class type",
10173                      type);
10174             return error_mark_node;
10175           }
10176
10177         r = build_cplus_array_type (type, domain);
10178
10179         if (TYPE_USER_ALIGN (t))
10180           {
10181             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10182             TYPE_USER_ALIGN (r) = 1;
10183           }
10184
10185         return r;
10186       }
10187
10188     case PLUS_EXPR:
10189     case MINUS_EXPR:
10190       {
10191         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10192         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10193
10194         if (e1 == error_mark_node || e2 == error_mark_node)
10195           return error_mark_node;
10196
10197         return fold_build2_loc (input_location,
10198                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10199       }
10200
10201     case NEGATE_EXPR:
10202     case NOP_EXPR:
10203       {
10204         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10205         if (e == error_mark_node)
10206           return error_mark_node;
10207
10208         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10209       }
10210
10211     case TYPENAME_TYPE:
10212       {
10213         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10214                                      in_decl, /*entering_scope=*/1);
10215         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10216                               complain, in_decl);
10217
10218         if (ctx == error_mark_node || f == error_mark_node)
10219           return error_mark_node;
10220
10221         if (!MAYBE_CLASS_TYPE_P (ctx))
10222           {
10223             if (complain & tf_error)
10224               error ("%qT is not a class, struct, or union type", ctx);
10225             return error_mark_node;
10226           }
10227         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10228           {
10229             /* Normally, make_typename_type does not require that the CTX
10230                have complete type in order to allow things like:
10231
10232                  template <class T> struct S { typename S<T>::X Y; };
10233
10234                But, such constructs have already been resolved by this
10235                point, so here CTX really should have complete type, unless
10236                it's a partial instantiation.  */
10237             if (!(complain & tf_no_class_instantiations))
10238               ctx = complete_type (ctx);
10239             if (!COMPLETE_TYPE_P (ctx))
10240               {
10241                 if (complain & tf_error)
10242                   cxx_incomplete_type_error (NULL_TREE, ctx);
10243                 return error_mark_node;
10244               }
10245           }
10246
10247         f = make_typename_type (ctx, f, typename_type,
10248                                 (complain & tf_error) | tf_keep_type_decl);
10249         if (f == error_mark_node)
10250           return f;
10251         if (TREE_CODE (f) == TYPE_DECL)
10252           {
10253             complain |= tf_ignore_bad_quals;
10254             f = TREE_TYPE (f);
10255           }
10256
10257         if (TREE_CODE (f) != TYPENAME_TYPE)
10258           {
10259             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10260               error ("%qT resolves to %qT, which is not an enumeration type",
10261                      t, f);
10262             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10263               error ("%qT resolves to %qT, which is is not a class type",
10264                      t, f);
10265           }
10266
10267         return cp_build_qualified_type_real
10268           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10269       }
10270
10271     case UNBOUND_CLASS_TEMPLATE:
10272       {
10273         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10274                                      in_decl, /*entering_scope=*/1);
10275         tree name = TYPE_IDENTIFIER (t);
10276         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10277
10278         if (ctx == error_mark_node || name == error_mark_node)
10279           return error_mark_node;
10280
10281         if (parm_list)
10282           parm_list = tsubst_template_parms (parm_list, args, complain);
10283         return make_unbound_class_template (ctx, name, parm_list, complain);
10284       }
10285
10286     case INDIRECT_REF:
10287     case ADDR_EXPR:
10288     case CALL_EXPR:
10289       gcc_unreachable ();
10290
10291     case ARRAY_REF:
10292       {
10293         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10294         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10295                                /*integral_constant_expression_p=*/false);
10296         if (e1 == error_mark_node || e2 == error_mark_node)
10297           return error_mark_node;
10298
10299         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10300       }
10301
10302     case SCOPE_REF:
10303       {
10304         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10305         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10306         if (e1 == error_mark_node || e2 == error_mark_node)
10307           return error_mark_node;
10308
10309         return build_qualified_name (/*type=*/NULL_TREE,
10310                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10311       }
10312
10313     case TYPEOF_TYPE:
10314       {
10315         tree type;
10316
10317         ++cp_unevaluated_operand;
10318         ++c_inhibit_evaluation_warnings;
10319
10320         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10321                             complain, in_decl,
10322                             /*integral_constant_expression_p=*/false);
10323
10324         --cp_unevaluated_operand;
10325         --c_inhibit_evaluation_warnings;
10326
10327         type = finish_typeof (type);
10328         return cp_build_qualified_type_real (type,
10329                                              cp_type_quals (t)
10330                                              | cp_type_quals (type),
10331                                              complain);
10332       }
10333
10334     case DECLTYPE_TYPE:
10335       {
10336         tree type;
10337
10338         ++cp_unevaluated_operand;
10339         ++c_inhibit_evaluation_warnings;
10340
10341         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10342                             complain, in_decl,
10343                             /*integral_constant_expression_p=*/false);
10344
10345         --cp_unevaluated_operand;
10346         --c_inhibit_evaluation_warnings;
10347
10348         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10349           type = lambda_capture_field_type (type);
10350         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10351           type = lambda_return_type (type);
10352         else
10353           type = finish_decltype_type
10354             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10355         return cp_build_qualified_type_real (type,
10356                                              cp_type_quals (t)
10357                                              | cp_type_quals (type),
10358                                              complain);
10359       }
10360
10361     case TYPE_ARGUMENT_PACK:
10362     case NONTYPE_ARGUMENT_PACK:
10363       {
10364         tree r = TYPE_P (t)
10365           ? cxx_make_type (TREE_CODE (t))
10366           : make_node (TREE_CODE (t));
10367         tree packed_out = 
10368           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10369                                 args,
10370                                 complain,
10371                                 in_decl);
10372         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10373
10374         /* For template nontype argument packs, also substitute into
10375            the type.  */
10376         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10377           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10378
10379         return r;
10380       }
10381       break;
10382
10383     default:
10384       sorry ("use of %qs in template",
10385              tree_code_name [(int) TREE_CODE (t)]);
10386       return error_mark_node;
10387     }
10388 }
10389
10390 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10391    type of the expression on the left-hand side of the "." or "->"
10392    operator.  */
10393
10394 static tree
10395 tsubst_baselink (tree baselink, tree object_type,
10396                  tree args, tsubst_flags_t complain, tree in_decl)
10397 {
10398     tree name;
10399     tree qualifying_scope;
10400     tree fns;
10401     tree optype;
10402     tree template_args = 0;
10403     bool template_id_p = false;
10404
10405     /* A baselink indicates a function from a base class.  Both the
10406        BASELINK_ACCESS_BINFO and the base class referenced may
10407        indicate bases of the template class, rather than the
10408        instantiated class.  In addition, lookups that were not
10409        ambiguous before may be ambiguous now.  Therefore, we perform
10410        the lookup again.  */
10411     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10412     qualifying_scope = tsubst (qualifying_scope, args,
10413                                complain, in_decl);
10414     fns = BASELINK_FUNCTIONS (baselink);
10415     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10416     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10417       {
10418         template_id_p = true;
10419         template_args = TREE_OPERAND (fns, 1);
10420         fns = TREE_OPERAND (fns, 0);
10421         if (template_args)
10422           template_args = tsubst_template_args (template_args, args,
10423                                                 complain, in_decl);
10424       }
10425     name = DECL_NAME (get_first_fn (fns));
10426     if (IDENTIFIER_TYPENAME_P (name))
10427       name = mangle_conv_op_name_for_type (optype);
10428     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10429
10430     /* If lookup found a single function, mark it as used at this
10431        point.  (If it lookup found multiple functions the one selected
10432        later by overload resolution will be marked as used at that
10433        point.)  */
10434     if (BASELINK_P (baselink))
10435       fns = BASELINK_FUNCTIONS (baselink);
10436     if (!template_id_p && !really_overloaded_fn (fns))
10437       mark_used (OVL_CURRENT (fns));
10438
10439     /* Add back the template arguments, if present.  */
10440     if (BASELINK_P (baselink) && template_id_p)
10441       BASELINK_FUNCTIONS (baselink)
10442         = build_nt (TEMPLATE_ID_EXPR,
10443                     BASELINK_FUNCTIONS (baselink),
10444                     template_args);
10445     /* Update the conversion operator type.  */
10446     BASELINK_OPTYPE (baselink) = optype;
10447
10448     if (!object_type)
10449       object_type = current_class_type;
10450     return adjust_result_of_qualified_name_lookup (baselink,
10451                                                    qualifying_scope,
10452                                                    object_type);
10453 }
10454
10455 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10456    true if the qualified-id will be a postfix-expression in-and-of
10457    itself; false if more of the postfix-expression follows the
10458    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10459    of "&".  */
10460
10461 static tree
10462 tsubst_qualified_id (tree qualified_id, tree args,
10463                      tsubst_flags_t complain, tree in_decl,
10464                      bool done, bool address_p)
10465 {
10466   tree expr;
10467   tree scope;
10468   tree name;
10469   bool is_template;
10470   tree template_args;
10471
10472   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10473
10474   /* Figure out what name to look up.  */
10475   name = TREE_OPERAND (qualified_id, 1);
10476   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10477     {
10478       is_template = true;
10479       template_args = TREE_OPERAND (name, 1);
10480       if (template_args)
10481         template_args = tsubst_template_args (template_args, args,
10482                                               complain, in_decl);
10483       name = TREE_OPERAND (name, 0);
10484     }
10485   else
10486     {
10487       is_template = false;
10488       template_args = NULL_TREE;
10489     }
10490
10491   /* Substitute into the qualifying scope.  When there are no ARGS, we
10492      are just trying to simplify a non-dependent expression.  In that
10493      case the qualifying scope may be dependent, and, in any case,
10494      substituting will not help.  */
10495   scope = TREE_OPERAND (qualified_id, 0);
10496   if (args)
10497     {
10498       scope = tsubst (scope, args, complain, in_decl);
10499       expr = tsubst_copy (name, args, complain, in_decl);
10500     }
10501   else
10502     expr = name;
10503
10504   if (dependent_type_p (scope))
10505     {
10506       tree type = NULL_TREE;
10507       if (DECL_P (expr) && !dependent_scope_p (scope))
10508         type = TREE_TYPE (expr);
10509       return build_qualified_name (type, scope, expr,
10510                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10511     }
10512
10513   if (!BASELINK_P (name) && !DECL_P (expr))
10514     {
10515       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10516         {
10517           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10518           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10519             {
10520               error ("qualifying type %qT does not match destructor name ~%qT",
10521                      scope, TREE_OPERAND (expr, 0));
10522               expr = error_mark_node;
10523             }
10524           else
10525             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10526                                           /*is_type_p=*/0, false);
10527         }
10528       else
10529         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10530       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10531                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10532         {
10533           if (complain & tf_error)
10534             {
10535               error ("dependent-name %qE is parsed as a non-type, but "
10536                      "instantiation yields a type", qualified_id);
10537               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10538             }
10539           return error_mark_node;
10540         }
10541     }
10542
10543   if (DECL_P (expr))
10544     {
10545       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10546                                            scope);
10547       /* Remember that there was a reference to this entity.  */
10548       mark_used (expr);
10549     }
10550
10551   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10552     {
10553       if (complain & tf_error)
10554         qualified_name_lookup_error (scope,
10555                                      TREE_OPERAND (qualified_id, 1),
10556                                      expr, input_location);
10557       return error_mark_node;
10558     }
10559
10560   if (is_template)
10561     expr = lookup_template_function (expr, template_args);
10562
10563   if (expr == error_mark_node && complain & tf_error)
10564     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10565                                  expr, input_location);
10566   else if (TYPE_P (scope))
10567     {
10568       expr = (adjust_result_of_qualified_name_lookup
10569               (expr, scope, current_class_type));
10570       expr = (finish_qualified_id_expr
10571               (scope, expr, done, address_p,
10572                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10573                /*template_arg_p=*/false));
10574     }
10575
10576   /* Expressions do not generally have reference type.  */
10577   if (TREE_CODE (expr) != SCOPE_REF
10578       /* However, if we're about to form a pointer-to-member, we just
10579          want the referenced member referenced.  */
10580       && TREE_CODE (expr) != OFFSET_REF)
10581     expr = convert_from_reference (expr);
10582
10583   return expr;
10584 }
10585
10586 /* Like tsubst, but deals with expressions.  This function just replaces
10587    template parms; to finish processing the resultant expression, use
10588    tsubst_expr.  */
10589
10590 static tree
10591 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10592 {
10593   enum tree_code code;
10594   tree r;
10595
10596   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10597     return t;
10598
10599   code = TREE_CODE (t);
10600
10601   switch (code)
10602     {
10603     case PARM_DECL:
10604       r = retrieve_local_specialization (t);
10605
10606       if (r == NULL)
10607         {
10608           tree c;
10609           /* This can happen for a parameter name used later in a function
10610              declaration (such as in a late-specified return type).  Just
10611              make a dummy decl, since it's only used for its type.  */
10612           gcc_assert (cp_unevaluated_operand != 0);
10613           /* We copy T because want to tsubst the PARM_DECL only,
10614              not the following PARM_DECLs that are chained to T.  */
10615           c = copy_node (t);
10616           r = tsubst_decl (c, args, complain);
10617           /* Give it the template pattern as its context; its true context
10618              hasn't been instantiated yet and this is good enough for
10619              mangling.  */
10620           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10621         }
10622       
10623       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10624         r = ARGUMENT_PACK_SELECT_ARG (r);
10625       mark_used (r);
10626       return r;
10627
10628     case CONST_DECL:
10629       {
10630         tree enum_type;
10631         tree v;
10632
10633         if (DECL_TEMPLATE_PARM_P (t))
10634           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10635         /* There is no need to substitute into namespace-scope
10636            enumerators.  */
10637         if (DECL_NAMESPACE_SCOPE_P (t))
10638           return t;
10639         /* If ARGS is NULL, then T is known to be non-dependent.  */
10640         if (args == NULL_TREE)
10641           return integral_constant_value (t);
10642
10643         /* Unfortunately, we cannot just call lookup_name here.
10644            Consider:
10645
10646              template <int I> int f() {
10647              enum E { a = I };
10648              struct S { void g() { E e = a; } };
10649              };
10650
10651            When we instantiate f<7>::S::g(), say, lookup_name is not
10652            clever enough to find f<7>::a.  */
10653         enum_type
10654           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10655                               /*entering_scope=*/0);
10656
10657         for (v = TYPE_VALUES (enum_type);
10658              v != NULL_TREE;
10659              v = TREE_CHAIN (v))
10660           if (TREE_PURPOSE (v) == DECL_NAME (t))
10661             return TREE_VALUE (v);
10662
10663           /* We didn't find the name.  That should never happen; if
10664              name-lookup found it during preliminary parsing, we
10665              should find it again here during instantiation.  */
10666         gcc_unreachable ();
10667       }
10668       return t;
10669
10670     case FIELD_DECL:
10671       if (DECL_CONTEXT (t))
10672         {
10673           tree ctx;
10674
10675           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10676                                   /*entering_scope=*/1);
10677           if (ctx != DECL_CONTEXT (t))
10678             {
10679               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10680               if (!r)
10681                 {
10682                   if (complain & tf_error)
10683                     error ("using invalid field %qD", t);
10684                   return error_mark_node;
10685                 }
10686               return r;
10687             }
10688         }
10689
10690       return t;
10691
10692     case VAR_DECL:
10693     case FUNCTION_DECL:
10694       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10695           || local_variable_p (t))
10696         t = tsubst (t, args, complain, in_decl);
10697       mark_used (t);
10698       return t;
10699
10700     case BASELINK:
10701       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10702
10703     case TEMPLATE_DECL:
10704       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10705         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10706                        args, complain, in_decl);
10707       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10708         return tsubst (t, args, complain, in_decl);
10709       else if (DECL_CLASS_SCOPE_P (t)
10710                && uses_template_parms (DECL_CONTEXT (t)))
10711         {
10712           /* Template template argument like the following example need
10713              special treatment:
10714
10715                template <template <class> class TT> struct C {};
10716                template <class T> struct D {
10717                  template <class U> struct E {};
10718                  C<E> c;                                // #1
10719                };
10720                D<int> d;                                // #2
10721
10722              We are processing the template argument `E' in #1 for
10723              the template instantiation #2.  Originally, `E' is a
10724              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10725              have to substitute this with one having context `D<int>'.  */
10726
10727           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10728           return lookup_field (context, DECL_NAME(t), 0, false);
10729         }
10730       else
10731         /* Ordinary template template argument.  */
10732         return t;
10733
10734     case CAST_EXPR:
10735     case REINTERPRET_CAST_EXPR:
10736     case CONST_CAST_EXPR:
10737     case STATIC_CAST_EXPR:
10738     case DYNAMIC_CAST_EXPR:
10739     case NOP_EXPR:
10740       return build1
10741         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10742          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10743
10744     case SIZEOF_EXPR:
10745       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10746         {
10747           /* We only want to compute the number of arguments.  */
10748           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10749                                                 complain, in_decl);
10750           int len = 0;
10751
10752           if (TREE_CODE (expanded) == TREE_VEC)
10753             len = TREE_VEC_LENGTH (expanded);
10754
10755           if (expanded == error_mark_node)
10756             return error_mark_node;
10757           else if (PACK_EXPANSION_P (expanded)
10758                    || (TREE_CODE (expanded) == TREE_VEC
10759                        && len > 0
10760                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10761             {
10762               if (TREE_CODE (expanded) == TREE_VEC)
10763                 expanded = TREE_VEC_ELT (expanded, len - 1);
10764
10765               if (TYPE_P (expanded))
10766                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10767                                                    complain & tf_error);
10768               else
10769                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10770                                                    complain & tf_error);
10771             }
10772           else
10773             return build_int_cst (size_type_node, len);
10774         }
10775       /* Fall through */
10776
10777     case INDIRECT_REF:
10778     case NEGATE_EXPR:
10779     case TRUTH_NOT_EXPR:
10780     case BIT_NOT_EXPR:
10781     case ADDR_EXPR:
10782     case UNARY_PLUS_EXPR:      /* Unary + */
10783     case ALIGNOF_EXPR:
10784     case ARROW_EXPR:
10785     case THROW_EXPR:
10786     case TYPEID_EXPR:
10787     case REALPART_EXPR:
10788     case IMAGPART_EXPR:
10789       return build1
10790         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10791          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10792
10793     case COMPONENT_REF:
10794       {
10795         tree object;
10796         tree name;
10797
10798         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10799         name = TREE_OPERAND (t, 1);
10800         if (TREE_CODE (name) == BIT_NOT_EXPR)
10801           {
10802             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10803                                 complain, in_decl);
10804             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10805           }
10806         else if (TREE_CODE (name) == SCOPE_REF
10807                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10808           {
10809             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10810                                      complain, in_decl);
10811             name = TREE_OPERAND (name, 1);
10812             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10813                                 complain, in_decl);
10814             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10815             name = build_qualified_name (/*type=*/NULL_TREE,
10816                                          base, name,
10817                                          /*template_p=*/false);
10818           }
10819         else if (TREE_CODE (name) == BASELINK)
10820           name = tsubst_baselink (name,
10821                                   non_reference (TREE_TYPE (object)),
10822                                   args, complain,
10823                                   in_decl);
10824         else
10825           name = tsubst_copy (name, args, complain, in_decl);
10826         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10827       }
10828
10829     case PLUS_EXPR:
10830     case MINUS_EXPR:
10831     case MULT_EXPR:
10832     case TRUNC_DIV_EXPR:
10833     case CEIL_DIV_EXPR:
10834     case FLOOR_DIV_EXPR:
10835     case ROUND_DIV_EXPR:
10836     case EXACT_DIV_EXPR:
10837     case BIT_AND_EXPR:
10838     case BIT_IOR_EXPR:
10839     case BIT_XOR_EXPR:
10840     case TRUNC_MOD_EXPR:
10841     case FLOOR_MOD_EXPR:
10842     case TRUTH_ANDIF_EXPR:
10843     case TRUTH_ORIF_EXPR:
10844     case TRUTH_AND_EXPR:
10845     case TRUTH_OR_EXPR:
10846     case RSHIFT_EXPR:
10847     case LSHIFT_EXPR:
10848     case RROTATE_EXPR:
10849     case LROTATE_EXPR:
10850     case EQ_EXPR:
10851     case NE_EXPR:
10852     case MAX_EXPR:
10853     case MIN_EXPR:
10854     case LE_EXPR:
10855     case GE_EXPR:
10856     case LT_EXPR:
10857     case GT_EXPR:
10858     case COMPOUND_EXPR:
10859     case DOTSTAR_EXPR:
10860     case MEMBER_REF:
10861     case PREDECREMENT_EXPR:
10862     case PREINCREMENT_EXPR:
10863     case POSTDECREMENT_EXPR:
10864     case POSTINCREMENT_EXPR:
10865       return build_nt
10866         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10867          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10868
10869     case SCOPE_REF:
10870       return build_qualified_name (/*type=*/NULL_TREE,
10871                                    tsubst_copy (TREE_OPERAND (t, 0),
10872                                                 args, complain, in_decl),
10873                                    tsubst_copy (TREE_OPERAND (t, 1),
10874                                                 args, complain, in_decl),
10875                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10876
10877     case ARRAY_REF:
10878       return build_nt
10879         (ARRAY_REF,
10880          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10881          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10882          NULL_TREE, NULL_TREE);
10883
10884     case CALL_EXPR:
10885       {
10886         int n = VL_EXP_OPERAND_LENGTH (t);
10887         tree result = build_vl_exp (CALL_EXPR, n);
10888         int i;
10889         for (i = 0; i < n; i++)
10890           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10891                                              complain, in_decl);
10892         return result;
10893       }
10894
10895     case COND_EXPR:
10896     case MODOP_EXPR:
10897     case PSEUDO_DTOR_EXPR:
10898       {
10899         r = build_nt
10900           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10901            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10902            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10903         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10904         return r;
10905       }
10906
10907     case NEW_EXPR:
10908       {
10909         r = build_nt
10910         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10911          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10912          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10913         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10914         return r;
10915       }
10916
10917     case DELETE_EXPR:
10918       {
10919         r = build_nt
10920         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10921          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10922         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10923         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10924         return r;
10925       }
10926
10927     case TEMPLATE_ID_EXPR:
10928       {
10929         /* Substituted template arguments */
10930         tree fn = TREE_OPERAND (t, 0);
10931         tree targs = TREE_OPERAND (t, 1);
10932
10933         fn = tsubst_copy (fn, args, complain, in_decl);
10934         if (targs)
10935           targs = tsubst_template_args (targs, args, complain, in_decl);
10936
10937         return lookup_template_function (fn, targs);
10938       }
10939
10940     case TREE_LIST:
10941       {
10942         tree purpose, value, chain;
10943
10944         if (t == void_list_node)
10945           return t;
10946
10947         purpose = TREE_PURPOSE (t);
10948         if (purpose)
10949           purpose = tsubst_copy (purpose, args, complain, in_decl);
10950         value = TREE_VALUE (t);
10951         if (value)
10952           value = tsubst_copy (value, args, complain, in_decl);
10953         chain = TREE_CHAIN (t);
10954         if (chain && chain != void_type_node)
10955           chain = tsubst_copy (chain, args, complain, in_decl);
10956         if (purpose == TREE_PURPOSE (t)
10957             && value == TREE_VALUE (t)
10958             && chain == TREE_CHAIN (t))
10959           return t;
10960         return tree_cons (purpose, value, chain);
10961       }
10962
10963     case RECORD_TYPE:
10964     case UNION_TYPE:
10965     case ENUMERAL_TYPE:
10966     case INTEGER_TYPE:
10967     case TEMPLATE_TYPE_PARM:
10968     case TEMPLATE_TEMPLATE_PARM:
10969     case BOUND_TEMPLATE_TEMPLATE_PARM:
10970     case TEMPLATE_PARM_INDEX:
10971     case POINTER_TYPE:
10972     case REFERENCE_TYPE:
10973     case OFFSET_TYPE:
10974     case FUNCTION_TYPE:
10975     case METHOD_TYPE:
10976     case ARRAY_TYPE:
10977     case TYPENAME_TYPE:
10978     case UNBOUND_CLASS_TEMPLATE:
10979     case TYPEOF_TYPE:
10980     case DECLTYPE_TYPE:
10981     case TYPE_DECL:
10982       return tsubst (t, args, complain, in_decl);
10983
10984     case IDENTIFIER_NODE:
10985       if (IDENTIFIER_TYPENAME_P (t))
10986         {
10987           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10988           return mangle_conv_op_name_for_type (new_type);
10989         }
10990       else
10991         return t;
10992
10993     case CONSTRUCTOR:
10994       /* This is handled by tsubst_copy_and_build.  */
10995       gcc_unreachable ();
10996
10997     case VA_ARG_EXPR:
10998       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10999                                           in_decl),
11000                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11001
11002     case CLEANUP_POINT_EXPR:
11003       /* We shouldn't have built any of these during initial template
11004          generation.  Instead, they should be built during instantiation
11005          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11006       gcc_unreachable ();
11007
11008     case OFFSET_REF:
11009       mark_used (TREE_OPERAND (t, 1));
11010       return t;
11011
11012     case EXPR_PACK_EXPANSION:
11013       error ("invalid use of pack expansion expression");
11014       return error_mark_node;
11015
11016     case NONTYPE_ARGUMENT_PACK:
11017       error ("use %<...%> to expand argument pack");
11018       return error_mark_node;
11019
11020     default:
11021       return t;
11022     }
11023 }
11024
11025 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11026
11027 static tree
11028 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11029                     tree in_decl)
11030 {
11031   tree new_clauses = NULL, nc, oc;
11032
11033   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11034     {
11035       nc = copy_node (oc);
11036       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11037       new_clauses = nc;
11038
11039       switch (OMP_CLAUSE_CODE (nc))
11040         {
11041         case OMP_CLAUSE_LASTPRIVATE:
11042           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11043             {
11044               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11045               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11046                            in_decl, /*integral_constant_expression_p=*/false);
11047               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11048                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11049             }
11050           /* FALLTHRU */
11051         case OMP_CLAUSE_PRIVATE:
11052         case OMP_CLAUSE_SHARED:
11053         case OMP_CLAUSE_FIRSTPRIVATE:
11054         case OMP_CLAUSE_REDUCTION:
11055         case OMP_CLAUSE_COPYIN:
11056         case OMP_CLAUSE_COPYPRIVATE:
11057         case OMP_CLAUSE_IF:
11058         case OMP_CLAUSE_NUM_THREADS:
11059         case OMP_CLAUSE_SCHEDULE:
11060         case OMP_CLAUSE_COLLAPSE:
11061           OMP_CLAUSE_OPERAND (nc, 0)
11062             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11063                            in_decl, /*integral_constant_expression_p=*/false);
11064           break;
11065         case OMP_CLAUSE_NOWAIT:
11066         case OMP_CLAUSE_ORDERED:
11067         case OMP_CLAUSE_DEFAULT:
11068         case OMP_CLAUSE_UNTIED:
11069           break;
11070         default:
11071           gcc_unreachable ();
11072         }
11073     }
11074
11075   return finish_omp_clauses (nreverse (new_clauses));
11076 }
11077
11078 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11079
11080 static tree
11081 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11082                           tree in_decl)
11083 {
11084 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11085
11086   tree purpose, value, chain;
11087
11088   if (t == NULL)
11089     return t;
11090
11091   if (TREE_CODE (t) != TREE_LIST)
11092     return tsubst_copy_and_build (t, args, complain, in_decl,
11093                                   /*function_p=*/false,
11094                                   /*integral_constant_expression_p=*/false);
11095
11096   if (t == void_list_node)
11097     return t;
11098
11099   purpose = TREE_PURPOSE (t);
11100   if (purpose)
11101     purpose = RECUR (purpose);
11102   value = TREE_VALUE (t);
11103   if (value && TREE_CODE (value) != LABEL_DECL)
11104     value = RECUR (value);
11105   chain = TREE_CHAIN (t);
11106   if (chain && chain != void_type_node)
11107     chain = RECUR (chain);
11108   return tree_cons (purpose, value, chain);
11109 #undef RECUR
11110 }
11111
11112 /* Substitute one OMP_FOR iterator.  */
11113
11114 static void
11115 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11116                          tree condv, tree incrv, tree *clauses,
11117                          tree args, tsubst_flags_t complain, tree in_decl,
11118                          bool integral_constant_expression_p)
11119 {
11120 #define RECUR(NODE)                             \
11121   tsubst_expr ((NODE), args, complain, in_decl, \
11122                integral_constant_expression_p)
11123   tree decl, init, cond, incr, auto_node;
11124
11125   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11126   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11127   decl = RECUR (TREE_OPERAND (init, 0));
11128   init = TREE_OPERAND (init, 1);
11129   auto_node = type_uses_auto (TREE_TYPE (decl));
11130   if (auto_node && init)
11131     {
11132       tree init_expr = init;
11133       if (TREE_CODE (init_expr) == DECL_EXPR)
11134         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11135       init_expr = RECUR (init_expr);
11136       TREE_TYPE (decl)
11137         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11138     }
11139   gcc_assert (!type_dependent_expression_p (decl));
11140
11141   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11142     {
11143       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11144       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11145       if (TREE_CODE (incr) == MODIFY_EXPR)
11146         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11147                                     RECUR (TREE_OPERAND (incr, 1)),
11148                                     complain);
11149       else
11150         incr = RECUR (incr);
11151       TREE_VEC_ELT (declv, i) = decl;
11152       TREE_VEC_ELT (initv, i) = init;
11153       TREE_VEC_ELT (condv, i) = cond;
11154       TREE_VEC_ELT (incrv, i) = incr;
11155       return;
11156     }
11157
11158   if (init && TREE_CODE (init) != DECL_EXPR)
11159     {
11160       tree c;
11161       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11162         {
11163           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11164                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11165               && OMP_CLAUSE_DECL (c) == decl)
11166             break;
11167           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11168                    && OMP_CLAUSE_DECL (c) == decl)
11169             error ("iteration variable %qD should not be firstprivate", decl);
11170           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11171                    && OMP_CLAUSE_DECL (c) == decl)
11172             error ("iteration variable %qD should not be reduction", decl);
11173         }
11174       if (c == NULL)
11175         {
11176           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11177           OMP_CLAUSE_DECL (c) = decl;
11178           c = finish_omp_clauses (c);
11179           if (c)
11180             {
11181               OMP_CLAUSE_CHAIN (c) = *clauses;
11182               *clauses = c;
11183             }
11184         }
11185     }
11186   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11187   if (COMPARISON_CLASS_P (cond))
11188     cond = build2 (TREE_CODE (cond), boolean_type_node,
11189                    RECUR (TREE_OPERAND (cond, 0)),
11190                    RECUR (TREE_OPERAND (cond, 1)));
11191   else
11192     cond = RECUR (cond);
11193   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11194   switch (TREE_CODE (incr))
11195     {
11196     case PREINCREMENT_EXPR:
11197     case PREDECREMENT_EXPR:
11198     case POSTINCREMENT_EXPR:
11199     case POSTDECREMENT_EXPR:
11200       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11201                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11202       break;
11203     case MODIFY_EXPR:
11204       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11205           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11206         {
11207           tree rhs = TREE_OPERAND (incr, 1);
11208           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11209                          RECUR (TREE_OPERAND (incr, 0)),
11210                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11211                                  RECUR (TREE_OPERAND (rhs, 0)),
11212                                  RECUR (TREE_OPERAND (rhs, 1))));
11213         }
11214       else
11215         incr = RECUR (incr);
11216       break;
11217     case MODOP_EXPR:
11218       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11219           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11220         {
11221           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11222           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11223                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11224                                  TREE_TYPE (decl), lhs,
11225                                  RECUR (TREE_OPERAND (incr, 2))));
11226         }
11227       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11228                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11229                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11230         {
11231           tree rhs = TREE_OPERAND (incr, 2);
11232           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11233                          RECUR (TREE_OPERAND (incr, 0)),
11234                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11235                                  RECUR (TREE_OPERAND (rhs, 0)),
11236                                  RECUR (TREE_OPERAND (rhs, 1))));
11237         }
11238       else
11239         incr = RECUR (incr);
11240       break;
11241     default:
11242       incr = RECUR (incr);
11243       break;
11244     }
11245
11246   TREE_VEC_ELT (declv, i) = decl;
11247   TREE_VEC_ELT (initv, i) = init;
11248   TREE_VEC_ELT (condv, i) = cond;
11249   TREE_VEC_ELT (incrv, i) = incr;
11250 #undef RECUR
11251 }
11252
11253 /* Like tsubst_copy for expressions, etc. but also does semantic
11254    processing.  */
11255
11256 static tree
11257 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11258              bool integral_constant_expression_p)
11259 {
11260 #define RECUR(NODE)                             \
11261   tsubst_expr ((NODE), args, complain, in_decl, \
11262                integral_constant_expression_p)
11263
11264   tree stmt, tmp;
11265
11266   if (t == NULL_TREE || t == error_mark_node)
11267     return t;
11268
11269   if (EXPR_HAS_LOCATION (t))
11270     input_location = EXPR_LOCATION (t);
11271   if (STATEMENT_CODE_P (TREE_CODE (t)))
11272     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11273
11274   switch (TREE_CODE (t))
11275     {
11276     case STATEMENT_LIST:
11277       {
11278         tree_stmt_iterator i;
11279         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11280           RECUR (tsi_stmt (i));
11281         break;
11282       }
11283
11284     case CTOR_INITIALIZER:
11285       finish_mem_initializers (tsubst_initializer_list
11286                                (TREE_OPERAND (t, 0), args));
11287       break;
11288
11289     case RETURN_EXPR:
11290       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11291       break;
11292
11293     case EXPR_STMT:
11294       tmp = RECUR (EXPR_STMT_EXPR (t));
11295       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11296         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11297       else
11298         finish_expr_stmt (tmp);
11299       break;
11300
11301     case USING_STMT:
11302       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11303       break;
11304
11305     case DECL_EXPR:
11306       {
11307         tree decl;
11308         tree init;
11309
11310         decl = DECL_EXPR_DECL (t);
11311         if (TREE_CODE (decl) == LABEL_DECL)
11312           finish_label_decl (DECL_NAME (decl));
11313         else if (TREE_CODE (decl) == USING_DECL)
11314           {
11315             tree scope = USING_DECL_SCOPE (decl);
11316             tree name = DECL_NAME (decl);
11317             tree decl;
11318
11319             scope = RECUR (scope);
11320             decl = lookup_qualified_name (scope, name,
11321                                           /*is_type_p=*/false,
11322                                           /*complain=*/false);
11323             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11324               qualified_name_lookup_error (scope, name, decl, input_location);
11325             else
11326               do_local_using_decl (decl, scope, name);
11327           }
11328         else
11329           {
11330             init = DECL_INITIAL (decl);
11331             decl = tsubst (decl, args, complain, in_decl);
11332             if (decl != error_mark_node)
11333               {
11334                 /* By marking the declaration as instantiated, we avoid
11335                    trying to instantiate it.  Since instantiate_decl can't
11336                    handle local variables, and since we've already done
11337                    all that needs to be done, that's the right thing to
11338                    do.  */
11339                 if (TREE_CODE (decl) == VAR_DECL)
11340                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11341                 if (TREE_CODE (decl) == VAR_DECL
11342                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11343                   /* Anonymous aggregates are a special case.  */
11344                   finish_anon_union (decl);
11345                 else
11346                   {
11347                     maybe_push_decl (decl);
11348                     if (TREE_CODE (decl) == VAR_DECL
11349                         && DECL_PRETTY_FUNCTION_P (decl))
11350                       {
11351                         /* For __PRETTY_FUNCTION__ we have to adjust the
11352                            initializer.  */
11353                         const char *const name
11354                           = cxx_printable_name (current_function_decl, 2);
11355                         init = cp_fname_init (name, &TREE_TYPE (decl));
11356                       }
11357                     else
11358                       {
11359                         tree t = RECUR (init);
11360
11361                         if (init && !t)
11362                           /* If we had an initializer but it
11363                              instantiated to nothing,
11364                              value-initialize the object.  This will
11365                              only occur when the initializer was a
11366                              pack expansion where the parameter packs
11367                              used in that expansion were of length
11368                              zero.  */
11369                           init = build_value_init (TREE_TYPE (decl));
11370                         else
11371                           init = t;
11372                       }
11373
11374                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11375                   }
11376               }
11377           }
11378
11379         /* A DECL_EXPR can also be used as an expression, in the condition
11380            clause of an if/for/while construct.  */
11381         return decl;
11382       }
11383
11384     case FOR_STMT:
11385       stmt = begin_for_stmt ();
11386                           RECUR (FOR_INIT_STMT (t));
11387       finish_for_init_stmt (stmt);
11388       tmp = RECUR (FOR_COND (t));
11389       finish_for_cond (tmp, stmt);
11390       tmp = RECUR (FOR_EXPR (t));
11391       finish_for_expr (tmp, stmt);
11392       RECUR (FOR_BODY (t));
11393       finish_for_stmt (stmt);
11394       break;
11395
11396     case WHILE_STMT:
11397       stmt = begin_while_stmt ();
11398       tmp = RECUR (WHILE_COND (t));
11399       finish_while_stmt_cond (tmp, stmt);
11400       RECUR (WHILE_BODY (t));
11401       finish_while_stmt (stmt);
11402       break;
11403
11404     case DO_STMT:
11405       stmt = begin_do_stmt ();
11406       RECUR (DO_BODY (t));
11407       finish_do_body (stmt);
11408       tmp = RECUR (DO_COND (t));
11409       finish_do_stmt (tmp, stmt);
11410       break;
11411
11412     case IF_STMT:
11413       stmt = begin_if_stmt ();
11414       tmp = RECUR (IF_COND (t));
11415       finish_if_stmt_cond (tmp, stmt);
11416       RECUR (THEN_CLAUSE (t));
11417       finish_then_clause (stmt);
11418
11419       if (ELSE_CLAUSE (t))
11420         {
11421           begin_else_clause (stmt);
11422           RECUR (ELSE_CLAUSE (t));
11423           finish_else_clause (stmt);
11424         }
11425
11426       finish_if_stmt (stmt);
11427       break;
11428
11429     case BIND_EXPR:
11430       if (BIND_EXPR_BODY_BLOCK (t))
11431         stmt = begin_function_body ();
11432       else
11433         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11434                                     ? BCS_TRY_BLOCK : 0);
11435
11436       RECUR (BIND_EXPR_BODY (t));
11437
11438       if (BIND_EXPR_BODY_BLOCK (t))
11439         finish_function_body (stmt);
11440       else
11441         finish_compound_stmt (stmt);
11442       break;
11443
11444     case BREAK_STMT:
11445       finish_break_stmt ();
11446       break;
11447
11448     case CONTINUE_STMT:
11449       finish_continue_stmt ();
11450       break;
11451
11452     case SWITCH_STMT:
11453       stmt = begin_switch_stmt ();
11454       tmp = RECUR (SWITCH_STMT_COND (t));
11455       finish_switch_cond (tmp, stmt);
11456       RECUR (SWITCH_STMT_BODY (t));
11457       finish_switch_stmt (stmt);
11458       break;
11459
11460     case CASE_LABEL_EXPR:
11461       finish_case_label (EXPR_LOCATION (t),
11462                          RECUR (CASE_LOW (t)),
11463                          RECUR (CASE_HIGH (t)));
11464       break;
11465
11466     case LABEL_EXPR:
11467       {
11468         tree decl = LABEL_EXPR_LABEL (t);
11469         tree label;
11470
11471         label = finish_label_stmt (DECL_NAME (decl));
11472         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11473           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11474       }
11475       break;
11476
11477     case GOTO_EXPR:
11478       tmp = GOTO_DESTINATION (t);
11479       if (TREE_CODE (tmp) != LABEL_DECL)
11480         /* Computed goto's must be tsubst'd into.  On the other hand,
11481            non-computed gotos must not be; the identifier in question
11482            will have no binding.  */
11483         tmp = RECUR (tmp);
11484       else
11485         tmp = DECL_NAME (tmp);
11486       finish_goto_stmt (tmp);
11487       break;
11488
11489     case ASM_EXPR:
11490       tmp = finish_asm_stmt
11491         (ASM_VOLATILE_P (t),
11492          RECUR (ASM_STRING (t)),
11493          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11494          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11495          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11496          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11497       {
11498         tree asm_expr = tmp;
11499         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11500           asm_expr = TREE_OPERAND (asm_expr, 0);
11501         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11502       }
11503       break;
11504
11505     case TRY_BLOCK:
11506       if (CLEANUP_P (t))
11507         {
11508           stmt = begin_try_block ();
11509           RECUR (TRY_STMTS (t));
11510           finish_cleanup_try_block (stmt);
11511           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11512         }
11513       else
11514         {
11515           tree compound_stmt = NULL_TREE;
11516
11517           if (FN_TRY_BLOCK_P (t))
11518             stmt = begin_function_try_block (&compound_stmt);
11519           else
11520             stmt = begin_try_block ();
11521
11522           RECUR (TRY_STMTS (t));
11523
11524           if (FN_TRY_BLOCK_P (t))
11525             finish_function_try_block (stmt);
11526           else
11527             finish_try_block (stmt);
11528
11529           RECUR (TRY_HANDLERS (t));
11530           if (FN_TRY_BLOCK_P (t))
11531             finish_function_handler_sequence (stmt, compound_stmt);
11532           else
11533             finish_handler_sequence (stmt);
11534         }
11535       break;
11536
11537     case HANDLER:
11538       {
11539         tree decl = HANDLER_PARMS (t);
11540
11541         if (decl)
11542           {
11543             decl = tsubst (decl, args, complain, in_decl);
11544             /* Prevent instantiate_decl from trying to instantiate
11545                this variable.  We've already done all that needs to be
11546                done.  */
11547             if (decl != error_mark_node)
11548               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11549           }
11550         stmt = begin_handler ();
11551         finish_handler_parms (decl, stmt);
11552         RECUR (HANDLER_BODY (t));
11553         finish_handler (stmt);
11554       }
11555       break;
11556
11557     case TAG_DEFN:
11558       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11559       break;
11560
11561     case STATIC_ASSERT:
11562       {
11563         tree condition = 
11564           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11565                        args,
11566                        complain, in_decl,
11567                        /*integral_constant_expression_p=*/true);
11568         finish_static_assert (condition,
11569                               STATIC_ASSERT_MESSAGE (t),
11570                               STATIC_ASSERT_SOURCE_LOCATION (t),
11571                               /*member_p=*/false);
11572       }
11573       break;
11574
11575     case OMP_PARALLEL:
11576       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11577                                 args, complain, in_decl);
11578       stmt = begin_omp_parallel ();
11579       RECUR (OMP_PARALLEL_BODY (t));
11580       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11581         = OMP_PARALLEL_COMBINED (t);
11582       break;
11583
11584     case OMP_TASK:
11585       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11586                                 args, complain, in_decl);
11587       stmt = begin_omp_task ();
11588       RECUR (OMP_TASK_BODY (t));
11589       finish_omp_task (tmp, stmt);
11590       break;
11591
11592     case OMP_FOR:
11593       {
11594         tree clauses, body, pre_body;
11595         tree declv, initv, condv, incrv;
11596         int i;
11597
11598         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11599                                       args, complain, in_decl);
11600         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11601         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11602         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11603         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11604
11605         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11606           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11607                                    &clauses, args, complain, in_decl,
11608                                    integral_constant_expression_p);
11609
11610         stmt = begin_omp_structured_block ();
11611
11612         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11613           if (TREE_VEC_ELT (initv, i) == NULL
11614               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11615             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11616           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11617             {
11618               tree init = RECUR (TREE_VEC_ELT (initv, i));
11619               gcc_assert (init == TREE_VEC_ELT (declv, i));
11620               TREE_VEC_ELT (initv, i) = NULL_TREE;
11621             }
11622           else
11623             {
11624               tree decl_expr = TREE_VEC_ELT (initv, i);
11625               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11626               gcc_assert (init != NULL);
11627               TREE_VEC_ELT (initv, i) = RECUR (init);
11628               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11629               RECUR (decl_expr);
11630               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11631             }
11632
11633         pre_body = push_stmt_list ();
11634         RECUR (OMP_FOR_PRE_BODY (t));
11635         pre_body = pop_stmt_list (pre_body);
11636
11637         body = push_stmt_list ();
11638         RECUR (OMP_FOR_BODY (t));
11639         body = pop_stmt_list (body);
11640
11641         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11642                             body, pre_body, clauses);
11643
11644         add_stmt (finish_omp_structured_block (stmt));
11645       }
11646       break;
11647
11648     case OMP_SECTIONS:
11649     case OMP_SINGLE:
11650       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11651       stmt = push_stmt_list ();
11652       RECUR (OMP_BODY (t));
11653       stmt = pop_stmt_list (stmt);
11654
11655       t = copy_node (t);
11656       OMP_BODY (t) = stmt;
11657       OMP_CLAUSES (t) = tmp;
11658       add_stmt (t);
11659       break;
11660
11661     case OMP_SECTION:
11662     case OMP_CRITICAL:
11663     case OMP_MASTER:
11664     case OMP_ORDERED:
11665       stmt = push_stmt_list ();
11666       RECUR (OMP_BODY (t));
11667       stmt = pop_stmt_list (stmt);
11668
11669       t = copy_node (t);
11670       OMP_BODY (t) = stmt;
11671       add_stmt (t);
11672       break;
11673
11674     case OMP_ATOMIC:
11675       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11676       {
11677         tree op1 = TREE_OPERAND (t, 1);
11678         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11679         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11680         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11681       }
11682       break;
11683
11684     case EXPR_PACK_EXPANSION:
11685       error ("invalid use of pack expansion expression");
11686       return error_mark_node;
11687
11688     case NONTYPE_ARGUMENT_PACK:
11689       error ("use %<...%> to expand argument pack");
11690       return error_mark_node;
11691
11692     default:
11693       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11694
11695       return tsubst_copy_and_build (t, args, complain, in_decl,
11696                                     /*function_p=*/false,
11697                                     integral_constant_expression_p);
11698     }
11699
11700   return NULL_TREE;
11701 #undef RECUR
11702 }
11703
11704 /* T is a postfix-expression that is not being used in a function
11705    call.  Return the substituted version of T.  */
11706
11707 static tree
11708 tsubst_non_call_postfix_expression (tree t, tree args,
11709                                     tsubst_flags_t complain,
11710                                     tree in_decl)
11711 {
11712   if (TREE_CODE (t) == SCOPE_REF)
11713     t = tsubst_qualified_id (t, args, complain, in_decl,
11714                              /*done=*/false, /*address_p=*/false);
11715   else
11716     t = tsubst_copy_and_build (t, args, complain, in_decl,
11717                                /*function_p=*/false,
11718                                /*integral_constant_expression_p=*/false);
11719
11720   return t;
11721 }
11722
11723 /* Like tsubst but deals with expressions and performs semantic
11724    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11725
11726 tree
11727 tsubst_copy_and_build (tree t,
11728                        tree args,
11729                        tsubst_flags_t complain,
11730                        tree in_decl,
11731                        bool function_p,
11732                        bool integral_constant_expression_p)
11733 {
11734 #define RECUR(NODE)                                             \
11735   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11736                          /*function_p=*/false,                  \
11737                          integral_constant_expression_p)
11738
11739   tree op1;
11740
11741   if (t == NULL_TREE || t == error_mark_node)
11742     return t;
11743
11744   switch (TREE_CODE (t))
11745     {
11746     case USING_DECL:
11747       t = DECL_NAME (t);
11748       /* Fall through.  */
11749     case IDENTIFIER_NODE:
11750       {
11751         tree decl;
11752         cp_id_kind idk;
11753         bool non_integral_constant_expression_p;
11754         const char *error_msg;
11755
11756         if (IDENTIFIER_TYPENAME_P (t))
11757           {
11758             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11759             t = mangle_conv_op_name_for_type (new_type);
11760           }
11761
11762         /* Look up the name.  */
11763         decl = lookup_name (t);
11764
11765         /* By convention, expressions use ERROR_MARK_NODE to indicate
11766            failure, not NULL_TREE.  */
11767         if (decl == NULL_TREE)
11768           decl = error_mark_node;
11769
11770         decl = finish_id_expression (t, decl, NULL_TREE,
11771                                      &idk,
11772                                      integral_constant_expression_p,
11773                                      /*allow_non_integral_constant_expression_p=*/false,
11774                                      &non_integral_constant_expression_p,
11775                                      /*template_p=*/false,
11776                                      /*done=*/true,
11777                                      /*address_p=*/false,
11778                                      /*template_arg_p=*/false,
11779                                      &error_msg,
11780                                      input_location);
11781         if (error_msg)
11782           error (error_msg);
11783         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11784           decl = unqualified_name_lookup_error (decl);
11785         return decl;
11786       }
11787
11788     case TEMPLATE_ID_EXPR:
11789       {
11790         tree object;
11791         tree templ = RECUR (TREE_OPERAND (t, 0));
11792         tree targs = TREE_OPERAND (t, 1);
11793
11794         if (targs)
11795           targs = tsubst_template_args (targs, args, complain, in_decl);
11796
11797         if (TREE_CODE (templ) == COMPONENT_REF)
11798           {
11799             object = TREE_OPERAND (templ, 0);
11800             templ = TREE_OPERAND (templ, 1);
11801           }
11802         else
11803           object = NULL_TREE;
11804         templ = lookup_template_function (templ, targs);
11805
11806         if (object)
11807           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11808                          object, templ, NULL_TREE);
11809         else
11810           return baselink_for_fns (templ);
11811       }
11812
11813     case INDIRECT_REF:
11814       {
11815         tree r = RECUR (TREE_OPERAND (t, 0));
11816
11817         if (REFERENCE_REF_P (t))
11818           {
11819             /* A type conversion to reference type will be enclosed in
11820                such an indirect ref, but the substitution of the cast
11821                will have also added such an indirect ref.  */
11822             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11823               r = convert_from_reference (r);
11824           }
11825         else
11826           r = build_x_indirect_ref (r, "unary *", complain);
11827         return r;
11828       }
11829
11830     case NOP_EXPR:
11831       return build_nop
11832         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11833          RECUR (TREE_OPERAND (t, 0)));
11834
11835     case CAST_EXPR:
11836     case REINTERPRET_CAST_EXPR:
11837     case CONST_CAST_EXPR:
11838     case DYNAMIC_CAST_EXPR:
11839     case STATIC_CAST_EXPR:
11840       {
11841         tree type;
11842         tree op;
11843
11844         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11845         if (integral_constant_expression_p
11846             && !cast_valid_in_integral_constant_expression_p (type))
11847           {
11848             if (complain & tf_error)
11849               error ("a cast to a type other than an integral or "
11850                      "enumeration type cannot appear in a constant-expression");
11851             return error_mark_node; 
11852           }
11853
11854         op = RECUR (TREE_OPERAND (t, 0));
11855
11856         switch (TREE_CODE (t))
11857           {
11858           case CAST_EXPR:
11859             return build_functional_cast (type, op, complain);
11860           case REINTERPRET_CAST_EXPR:
11861             return build_reinterpret_cast (type, op, complain);
11862           case CONST_CAST_EXPR:
11863             return build_const_cast (type, op, complain);
11864           case DYNAMIC_CAST_EXPR:
11865             return build_dynamic_cast (type, op, complain);
11866           case STATIC_CAST_EXPR:
11867             return build_static_cast (type, op, complain);
11868           default:
11869             gcc_unreachable ();
11870           }
11871       }
11872
11873     case POSTDECREMENT_EXPR:
11874     case POSTINCREMENT_EXPR:
11875       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11876                                                 args, complain, in_decl);
11877       return build_x_unary_op (TREE_CODE (t), op1, complain);
11878
11879     case PREDECREMENT_EXPR:
11880     case PREINCREMENT_EXPR:
11881     case NEGATE_EXPR:
11882     case BIT_NOT_EXPR:
11883     case ABS_EXPR:
11884     case TRUTH_NOT_EXPR:
11885     case UNARY_PLUS_EXPR:  /* Unary + */
11886     case REALPART_EXPR:
11887     case IMAGPART_EXPR:
11888       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11889                                complain);
11890
11891     case ADDR_EXPR:
11892       op1 = TREE_OPERAND (t, 0);
11893       if (TREE_CODE (op1) == SCOPE_REF)
11894         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11895                                    /*done=*/true, /*address_p=*/true);
11896       else
11897         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11898                                                   in_decl);
11899       if (TREE_CODE (op1) == LABEL_DECL)
11900         return finish_label_address_expr (DECL_NAME (op1),
11901                                           EXPR_LOCATION (op1));
11902       return build_x_unary_op (ADDR_EXPR, op1, complain);
11903
11904     case PLUS_EXPR:
11905     case MINUS_EXPR:
11906     case MULT_EXPR:
11907     case TRUNC_DIV_EXPR:
11908     case CEIL_DIV_EXPR:
11909     case FLOOR_DIV_EXPR:
11910     case ROUND_DIV_EXPR:
11911     case EXACT_DIV_EXPR:
11912     case BIT_AND_EXPR:
11913     case BIT_IOR_EXPR:
11914     case BIT_XOR_EXPR:
11915     case TRUNC_MOD_EXPR:
11916     case FLOOR_MOD_EXPR:
11917     case TRUTH_ANDIF_EXPR:
11918     case TRUTH_ORIF_EXPR:
11919     case TRUTH_AND_EXPR:
11920     case TRUTH_OR_EXPR:
11921     case RSHIFT_EXPR:
11922     case LSHIFT_EXPR:
11923     case RROTATE_EXPR:
11924     case LROTATE_EXPR:
11925     case EQ_EXPR:
11926     case NE_EXPR:
11927     case MAX_EXPR:
11928     case MIN_EXPR:
11929     case LE_EXPR:
11930     case GE_EXPR:
11931     case LT_EXPR:
11932     case GT_EXPR:
11933     case MEMBER_REF:
11934     case DOTSTAR_EXPR:
11935       return build_x_binary_op
11936         (TREE_CODE (t),
11937          RECUR (TREE_OPERAND (t, 0)),
11938          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11939           ? ERROR_MARK
11940           : TREE_CODE (TREE_OPERAND (t, 0))),
11941          RECUR (TREE_OPERAND (t, 1)),
11942          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11943           ? ERROR_MARK
11944           : TREE_CODE (TREE_OPERAND (t, 1))),
11945          /*overloaded_p=*/NULL,
11946          complain);
11947
11948     case SCOPE_REF:
11949       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11950                                   /*address_p=*/false);
11951     case ARRAY_REF:
11952       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11953                                                 args, complain, in_decl);
11954       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11955
11956     case SIZEOF_EXPR:
11957       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11958         return tsubst_copy (t, args, complain, in_decl);
11959       /* Fall through */
11960       
11961     case ALIGNOF_EXPR:
11962       op1 = TREE_OPERAND (t, 0);
11963       if (!args)
11964         {
11965           /* When there are no ARGS, we are trying to evaluate a
11966              non-dependent expression from the parser.  Trying to do
11967              the substitutions may not work.  */
11968           if (!TYPE_P (op1))
11969             op1 = TREE_TYPE (op1);
11970         }
11971       else
11972         {
11973           ++cp_unevaluated_operand;
11974           ++c_inhibit_evaluation_warnings;
11975           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11976                                        /*function_p=*/false,
11977                                        /*integral_constant_expression_p=*/false);
11978           --cp_unevaluated_operand;
11979           --c_inhibit_evaluation_warnings;
11980         }
11981       if (TYPE_P (op1))
11982         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11983                                            complain & tf_error);
11984       else
11985         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11986                                            complain & tf_error);
11987
11988     case MODOP_EXPR:
11989       {
11990         tree r = build_x_modify_expr
11991           (RECUR (TREE_OPERAND (t, 0)),
11992            TREE_CODE (TREE_OPERAND (t, 1)),
11993            RECUR (TREE_OPERAND (t, 2)),
11994            complain);
11995         /* TREE_NO_WARNING must be set if either the expression was
11996            parenthesized or it uses an operator such as >>= rather
11997            than plain assignment.  In the former case, it was already
11998            set and must be copied.  In the latter case,
11999            build_x_modify_expr sets it and it must not be reset
12000            here.  */
12001         if (TREE_NO_WARNING (t))
12002           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12003         return r;
12004       }
12005
12006     case ARROW_EXPR:
12007       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12008                                                 args, complain, in_decl);
12009       /* Remember that there was a reference to this entity.  */
12010       if (DECL_P (op1))
12011         mark_used (op1);
12012       return build_x_arrow (op1);
12013
12014     case NEW_EXPR:
12015       {
12016         tree placement = RECUR (TREE_OPERAND (t, 0));
12017         tree init = RECUR (TREE_OPERAND (t, 3));
12018         VEC(tree,gc) *placement_vec;
12019         VEC(tree,gc) *init_vec;
12020         tree ret;
12021
12022         if (placement == NULL_TREE)
12023           placement_vec = NULL;
12024         else
12025           {
12026             placement_vec = make_tree_vector ();
12027             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12028               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12029           }
12030
12031         /* If there was an initializer in the original tree, but it
12032            instantiated to an empty list, then we should pass a
12033            non-NULL empty vector to tell build_new that it was an
12034            empty initializer() rather than no initializer.  This can
12035            only happen when the initializer is a pack expansion whose
12036            parameter packs are of length zero.  */
12037         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12038           init_vec = NULL;
12039         else
12040           {
12041             init_vec = make_tree_vector ();
12042             if (init == void_zero_node)
12043               gcc_assert (init_vec != NULL);
12044             else
12045               {
12046                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12047                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12048               }
12049           }
12050
12051         ret = build_new (&placement_vec,
12052                          RECUR (TREE_OPERAND (t, 1)),
12053                          RECUR (TREE_OPERAND (t, 2)),
12054                          &init_vec,
12055                          NEW_EXPR_USE_GLOBAL (t),
12056                          complain);
12057
12058         if (placement_vec != NULL)
12059           release_tree_vector (placement_vec);
12060         if (init_vec != NULL)
12061           release_tree_vector (init_vec);
12062
12063         return ret;
12064       }
12065
12066     case DELETE_EXPR:
12067      return delete_sanity
12068        (RECUR (TREE_OPERAND (t, 0)),
12069         RECUR (TREE_OPERAND (t, 1)),
12070         DELETE_EXPR_USE_VEC (t),
12071         DELETE_EXPR_USE_GLOBAL (t));
12072
12073     case COMPOUND_EXPR:
12074       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12075                                     RECUR (TREE_OPERAND (t, 1)),
12076                                     complain);
12077
12078     case CALL_EXPR:
12079       {
12080         tree function;
12081         VEC(tree,gc) *call_args;
12082         unsigned int nargs, i;
12083         bool qualified_p;
12084         bool koenig_p;
12085         tree ret;
12086
12087         function = CALL_EXPR_FN (t);
12088         /* When we parsed the expression,  we determined whether or
12089            not Koenig lookup should be performed.  */
12090         koenig_p = KOENIG_LOOKUP_P (t);
12091         if (TREE_CODE (function) == SCOPE_REF)
12092           {
12093             qualified_p = true;
12094             function = tsubst_qualified_id (function, args, complain, in_decl,
12095                                             /*done=*/false,
12096                                             /*address_p=*/false);
12097           }
12098         else
12099           {
12100             if (TREE_CODE (function) == COMPONENT_REF)
12101               {
12102                 tree op = TREE_OPERAND (function, 1);
12103
12104                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12105                                || (BASELINK_P (op)
12106                                    && BASELINK_QUALIFIED_P (op)));
12107               }
12108             else
12109               qualified_p = false;
12110
12111             function = tsubst_copy_and_build (function, args, complain,
12112                                               in_decl,
12113                                               !qualified_p,
12114                                               integral_constant_expression_p);
12115
12116             if (BASELINK_P (function))
12117               qualified_p = true;
12118           }
12119
12120         nargs = call_expr_nargs (t);
12121         call_args = make_tree_vector ();
12122         for (i = 0; i < nargs; ++i)
12123           {
12124             tree arg = CALL_EXPR_ARG (t, i);
12125
12126             if (!PACK_EXPANSION_P (arg))
12127               VEC_safe_push (tree, gc, call_args,
12128                              RECUR (CALL_EXPR_ARG (t, i)));
12129             else
12130               {
12131                 /* Expand the pack expansion and push each entry onto
12132                    CALL_ARGS.  */
12133                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12134                 if (TREE_CODE (arg) == TREE_VEC)
12135                   {
12136                     unsigned int len, j;
12137
12138                     len = TREE_VEC_LENGTH (arg);
12139                     for (j = 0; j < len; ++j)
12140                       {
12141                         tree value = TREE_VEC_ELT (arg, j);
12142                         if (value != NULL_TREE)
12143                           value = convert_from_reference (value);
12144                         VEC_safe_push (tree, gc, call_args, value);
12145                       }
12146                   }
12147                 else
12148                   {
12149                     /* A partial substitution.  Add one entry.  */
12150                     VEC_safe_push (tree, gc, call_args, arg);
12151                   }
12152               }
12153           }
12154
12155         /* We do not perform argument-dependent lookup if normal
12156            lookup finds a non-function, in accordance with the
12157            expected resolution of DR 218.  */
12158         if (koenig_p
12159             && ((is_overloaded_fn (function)
12160                  /* If lookup found a member function, the Koenig lookup is
12161                     not appropriate, even if an unqualified-name was used
12162                     to denote the function.  */
12163                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12164                 || TREE_CODE (function) == IDENTIFIER_NODE)
12165             /* Only do this when substitution turns a dependent call
12166                into a non-dependent call.  */
12167             && type_dependent_expression_p_push (t)
12168             && !any_type_dependent_arguments_p (call_args))
12169           function = perform_koenig_lookup (function, call_args);
12170
12171         if (TREE_CODE (function) == IDENTIFIER_NODE)
12172           {
12173             unqualified_name_lookup_error (function);
12174             release_tree_vector (call_args);
12175             return error_mark_node;
12176           }
12177
12178         /* Remember that there was a reference to this entity.  */
12179         if (DECL_P (function))
12180           mark_used (function);
12181
12182         if (TREE_CODE (function) == OFFSET_REF)
12183           ret = build_offset_ref_call_from_tree (function, &call_args);
12184         else if (TREE_CODE (function) == COMPONENT_REF)
12185           {
12186             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12187               ret = finish_call_expr (function, &call_args,
12188                                        /*disallow_virtual=*/false,
12189                                        /*koenig_p=*/false,
12190                                        complain);
12191             else
12192               ret = (build_new_method_call
12193                       (TREE_OPERAND (function, 0),
12194                        TREE_OPERAND (function, 1),
12195                        &call_args, NULL_TREE,
12196                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12197                        /*fn_p=*/NULL,
12198                        complain));
12199           }
12200         else
12201           ret = finish_call_expr (function, &call_args,
12202                                   /*disallow_virtual=*/qualified_p,
12203                                   koenig_p,
12204                                   complain);
12205
12206         release_tree_vector (call_args);
12207
12208         return ret;
12209       }
12210
12211     case COND_EXPR:
12212       return build_x_conditional_expr
12213         (RECUR (TREE_OPERAND (t, 0)),
12214          RECUR (TREE_OPERAND (t, 1)),
12215          RECUR (TREE_OPERAND (t, 2)),
12216          complain);
12217
12218     case PSEUDO_DTOR_EXPR:
12219       return finish_pseudo_destructor_expr
12220         (RECUR (TREE_OPERAND (t, 0)),
12221          RECUR (TREE_OPERAND (t, 1)),
12222          RECUR (TREE_OPERAND (t, 2)));
12223
12224     case TREE_LIST:
12225       {
12226         tree purpose, value, chain;
12227
12228         if (t == void_list_node)
12229           return t;
12230
12231         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12232             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12233           {
12234             /* We have pack expansions, so expand those and
12235                create a new list out of it.  */
12236             tree purposevec = NULL_TREE;
12237             tree valuevec = NULL_TREE;
12238             tree chain;
12239             int i, len = -1;
12240
12241             /* Expand the argument expressions.  */
12242             if (TREE_PURPOSE (t))
12243               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12244                                                  complain, in_decl);
12245             if (TREE_VALUE (t))
12246               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12247                                                complain, in_decl);
12248
12249             /* Build the rest of the list.  */
12250             chain = TREE_CHAIN (t);
12251             if (chain && chain != void_type_node)
12252               chain = RECUR (chain);
12253
12254             /* Determine the number of arguments.  */
12255             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12256               {
12257                 len = TREE_VEC_LENGTH (purposevec);
12258                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12259               }
12260             else if (TREE_CODE (valuevec) == TREE_VEC)
12261               len = TREE_VEC_LENGTH (valuevec);
12262             else
12263               {
12264                 /* Since we only performed a partial substitution into
12265                    the argument pack, we only return a single list
12266                    node.  */
12267                 if (purposevec == TREE_PURPOSE (t)
12268                     && valuevec == TREE_VALUE (t)
12269                     && chain == TREE_CHAIN (t))
12270                   return t;
12271
12272                 return tree_cons (purposevec, valuevec, chain);
12273               }
12274             
12275             /* Convert the argument vectors into a TREE_LIST */
12276             i = len;
12277             while (i > 0)
12278               {
12279                 /* Grab the Ith values.  */
12280                 i--;
12281                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12282                                      : NULL_TREE;
12283                 value 
12284                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12285                              : NULL_TREE;
12286
12287                 /* Build the list (backwards).  */
12288                 chain = tree_cons (purpose, value, chain);
12289               }
12290
12291             return chain;
12292           }
12293
12294         purpose = TREE_PURPOSE (t);
12295         if (purpose)
12296           purpose = RECUR (purpose);
12297         value = TREE_VALUE (t);
12298         if (value)
12299           value = RECUR (value);
12300         chain = TREE_CHAIN (t);
12301         if (chain && chain != void_type_node)
12302           chain = RECUR (chain);
12303         if (purpose == TREE_PURPOSE (t)
12304             && value == TREE_VALUE (t)
12305             && chain == TREE_CHAIN (t))
12306           return t;
12307         return tree_cons (purpose, value, chain);
12308       }
12309
12310     case COMPONENT_REF:
12311       {
12312         tree object;
12313         tree object_type;
12314         tree member;
12315
12316         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12317                                                      args, complain, in_decl);
12318         /* Remember that there was a reference to this entity.  */
12319         if (DECL_P (object))
12320           mark_used (object);
12321         object_type = TREE_TYPE (object);
12322
12323         member = TREE_OPERAND (t, 1);
12324         if (BASELINK_P (member))
12325           member = tsubst_baselink (member,
12326                                     non_reference (TREE_TYPE (object)),
12327                                     args, complain, in_decl);
12328         else
12329           member = tsubst_copy (member, args, complain, in_decl);
12330         if (member == error_mark_node)
12331           return error_mark_node;
12332
12333         if (object_type && !CLASS_TYPE_P (object_type))
12334           {
12335             if (SCALAR_TYPE_P (object_type))
12336               {
12337                 tree s = NULL_TREE;
12338                 tree dtor = member;
12339
12340                 if (TREE_CODE (dtor) == SCOPE_REF)
12341                   {
12342                     s = TREE_OPERAND (dtor, 0);
12343                     dtor = TREE_OPERAND (dtor, 1);
12344                   }
12345                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12346                   {
12347                     dtor = TREE_OPERAND (dtor, 0);
12348                     if (TYPE_P (dtor))
12349                       return finish_pseudo_destructor_expr (object, s, dtor);
12350                   }
12351               }
12352           }
12353         else if (TREE_CODE (member) == SCOPE_REF
12354                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12355           {
12356             tree tmpl;
12357             tree args;
12358
12359             /* Lookup the template functions now that we know what the
12360                scope is.  */
12361             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12362             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12363             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12364                                             /*is_type_p=*/false,
12365                                             /*complain=*/false);
12366             if (BASELINK_P (member))
12367               {
12368                 BASELINK_FUNCTIONS (member)
12369                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12370                               args);
12371                 member = (adjust_result_of_qualified_name_lookup
12372                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12373                            object_type));
12374               }
12375             else
12376               {
12377                 qualified_name_lookup_error (object_type, tmpl, member,
12378                                              input_location);
12379                 return error_mark_node;
12380               }
12381           }
12382         else if (TREE_CODE (member) == SCOPE_REF
12383                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12384                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12385           {
12386             if (complain & tf_error)
12387               {
12388                 if (TYPE_P (TREE_OPERAND (member, 0)))
12389                   error ("%qT is not a class or namespace",
12390                          TREE_OPERAND (member, 0));
12391                 else
12392                   error ("%qD is not a class or namespace",
12393                          TREE_OPERAND (member, 0));
12394               }
12395             return error_mark_node;
12396           }
12397         else if (TREE_CODE (member) == FIELD_DECL)
12398           return finish_non_static_data_member (member, object, NULL_TREE);
12399
12400         return finish_class_member_access_expr (object, member,
12401                                                 /*template_p=*/false,
12402                                                 complain);
12403       }
12404
12405     case THROW_EXPR:
12406       return build_throw
12407         (RECUR (TREE_OPERAND (t, 0)));
12408
12409     case CONSTRUCTOR:
12410       {
12411         VEC(constructor_elt,gc) *n;
12412         constructor_elt *ce;
12413         unsigned HOST_WIDE_INT idx;
12414         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12415         bool process_index_p;
12416         int newlen;
12417         bool need_copy_p = false;
12418         tree r;
12419
12420         if (type == error_mark_node)
12421           return error_mark_node;
12422
12423         /* digest_init will do the wrong thing if we let it.  */
12424         if (type && TYPE_PTRMEMFUNC_P (type))
12425           return t;
12426
12427         /* We do not want to process the index of aggregate
12428            initializers as they are identifier nodes which will be
12429            looked up by digest_init.  */
12430         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12431
12432         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12433         newlen = VEC_length (constructor_elt, n);
12434         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12435           {
12436             if (ce->index && process_index_p)
12437               ce->index = RECUR (ce->index);
12438
12439             if (PACK_EXPANSION_P (ce->value))
12440               {
12441                 /* Substitute into the pack expansion.  */
12442                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12443                                                   in_decl);
12444
12445                 if (ce->value == error_mark_node)
12446                   ;
12447                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12448                   /* Just move the argument into place.  */
12449                   ce->value = TREE_VEC_ELT (ce->value, 0);
12450                 else
12451                   {
12452                     /* Update the length of the final CONSTRUCTOR
12453                        arguments vector, and note that we will need to
12454                        copy.*/
12455                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12456                     need_copy_p = true;
12457                   }
12458               }
12459             else
12460               ce->value = RECUR (ce->value);
12461           }
12462
12463         if (need_copy_p)
12464           {
12465             VEC(constructor_elt,gc) *old_n = n;
12466
12467             n = VEC_alloc (constructor_elt, gc, newlen);
12468             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12469                  idx++)
12470               {
12471                 if (TREE_CODE (ce->value) == TREE_VEC)
12472                   {
12473                     int i, len = TREE_VEC_LENGTH (ce->value);
12474                     for (i = 0; i < len; ++i)
12475                       CONSTRUCTOR_APPEND_ELT (n, 0,
12476                                               TREE_VEC_ELT (ce->value, i));
12477                   }
12478                 else
12479                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12480               }
12481           }
12482
12483         r = build_constructor (init_list_type_node, n);
12484         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12485
12486         if (TREE_HAS_CONSTRUCTOR (t))
12487           return finish_compound_literal (type, r);
12488
12489         return r;
12490       }
12491
12492     case TYPEID_EXPR:
12493       {
12494         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12495         if (TYPE_P (operand_0))
12496           return get_typeid (operand_0);
12497         return build_typeid (operand_0);
12498       }
12499
12500     case VAR_DECL:
12501       if (!args)
12502         return t;
12503       /* Fall through */
12504
12505     case PARM_DECL:
12506       {
12507         tree r = tsubst_copy (t, args, complain, in_decl);
12508
12509         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12510           /* If the original type was a reference, we'll be wrapped in
12511              the appropriate INDIRECT_REF.  */
12512           r = convert_from_reference (r);
12513         return r;
12514       }
12515
12516     case VA_ARG_EXPR:
12517       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12518                              tsubst_copy (TREE_TYPE (t), args, complain,
12519                                           in_decl));
12520
12521     case OFFSETOF_EXPR:
12522       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12523
12524     case TRAIT_EXPR:
12525       {
12526         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12527                                   complain, in_decl);
12528
12529         tree type2 = TRAIT_EXPR_TYPE2 (t);
12530         if (type2)
12531           type2 = tsubst_copy (type2, args, complain, in_decl);
12532         
12533         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12534       }
12535
12536     case STMT_EXPR:
12537       {
12538         tree old_stmt_expr = cur_stmt_expr;
12539         tree stmt_expr = begin_stmt_expr ();
12540
12541         cur_stmt_expr = stmt_expr;
12542         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12543                      integral_constant_expression_p);
12544         stmt_expr = finish_stmt_expr (stmt_expr, false);
12545         cur_stmt_expr = old_stmt_expr;
12546
12547         return stmt_expr;
12548       }
12549
12550     case CONST_DECL:
12551       t = tsubst_copy (t, args, complain, in_decl);
12552       /* As in finish_id_expression, we resolve enumeration constants
12553          to their underlying values.  */
12554       if (TREE_CODE (t) == CONST_DECL)
12555         {
12556           used_types_insert (TREE_TYPE (t));
12557           return DECL_INITIAL (t);
12558         }
12559       return t;
12560
12561     case LAMBDA_EXPR:
12562       {
12563         tree r = build_lambda_expr ();
12564
12565         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12566         TREE_TYPE (r) = type;
12567         CLASSTYPE_LAMBDA_EXPR (type) = r;
12568
12569         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12570           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12571         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12572         LAMBDA_EXPR_DISCRIMINATOR (r)
12573           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12574         LAMBDA_EXPR_CAPTURE_LIST (r)
12575           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12576         LAMBDA_EXPR_THIS_CAPTURE (r)
12577           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12578         LAMBDA_EXPR_EXTRA_SCOPE (r)
12579           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12580
12581         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12582         determine_visibility (TYPE_NAME (type));
12583         /* Now that we know visibility, instantiate the type so we have a
12584            declaration of the op() for later calls to lambda_function.  */
12585         complete_type (type);
12586
12587         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12588         if (type)
12589           apply_lambda_return_type (r, type);
12590
12591         return build_lambda_object (r);
12592       }
12593
12594     default:
12595       /* Handle Objective-C++ constructs, if appropriate.  */
12596       {
12597         tree subst
12598           = objcp_tsubst_copy_and_build (t, args, complain,
12599                                          in_decl, /*function_p=*/false);
12600         if (subst)
12601           return subst;
12602       }
12603       return tsubst_copy (t, args, complain, in_decl);
12604     }
12605
12606 #undef RECUR
12607 }
12608
12609 /* Verify that the instantiated ARGS are valid. For type arguments,
12610    make sure that the type's linkage is ok. For non-type arguments,
12611    make sure they are constants if they are integral or enumerations.
12612    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12613
12614 static bool
12615 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12616 {
12617   if (ARGUMENT_PACK_P (t))
12618     {
12619       tree vec = ARGUMENT_PACK_ARGS (t);
12620       int len = TREE_VEC_LENGTH (vec);
12621       bool result = false;
12622       int i;
12623
12624       for (i = 0; i < len; ++i)
12625         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12626           result = true;
12627       return result;
12628     }
12629   else if (TYPE_P (t))
12630     {
12631       /* [basic.link]: A name with no linkage (notably, the name
12632          of a class or enumeration declared in a local scope)
12633          shall not be used to declare an entity with linkage.
12634          This implies that names with no linkage cannot be used as
12635          template arguments
12636
12637          DR 757 relaxes this restriction for C++0x.  */
12638       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12639                  : no_linkage_check (t, /*relaxed_p=*/false));
12640
12641       if (nt)
12642         {
12643           /* DR 488 makes use of a type with no linkage cause
12644              type deduction to fail.  */
12645           if (complain & tf_error)
12646             {
12647               if (TYPE_ANONYMOUS_P (nt))
12648                 error ("%qT is/uses anonymous type", t);
12649               else
12650                 error ("template argument for %qD uses local type %qT",
12651                        tmpl, t);
12652             }
12653           return true;
12654         }
12655       /* In order to avoid all sorts of complications, we do not
12656          allow variably-modified types as template arguments.  */
12657       else if (variably_modified_type_p (t, NULL_TREE))
12658         {
12659           if (complain & tf_error)
12660             error ("%qT is a variably modified type", t);
12661           return true;
12662         }
12663     }
12664   /* A non-type argument of integral or enumerated type must be a
12665      constant.  */
12666   else if (TREE_TYPE (t)
12667            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12668            && !TREE_CONSTANT (t))
12669     {
12670       if (complain & tf_error)
12671         error ("integral expression %qE is not constant", t);
12672       return true;
12673     }
12674   return false;
12675 }
12676
12677 static bool
12678 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12679 {
12680   int ix, len = DECL_NTPARMS (tmpl);
12681   bool result = false;
12682
12683   for (ix = 0; ix != len; ix++)
12684     {
12685       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12686         result = true;
12687     }
12688   if (result && (complain & tf_error))
12689     error ("  trying to instantiate %qD", tmpl);
12690   return result;
12691 }
12692
12693 /* Instantiate the indicated variable or function template TMPL with
12694    the template arguments in TARG_PTR.  */
12695
12696 tree
12697 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12698 {
12699   tree targ_ptr = orig_args;
12700   tree fndecl;
12701   tree gen_tmpl;
12702   tree spec;
12703   HOST_WIDE_INT saved_processing_template_decl;
12704
12705   if (tmpl == error_mark_node)
12706     return error_mark_node;
12707
12708   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12709
12710   /* If this function is a clone, handle it specially.  */
12711   if (DECL_CLONED_FUNCTION_P (tmpl))
12712     {
12713       tree spec;
12714       tree clone;
12715
12716       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12717          DECL_CLONED_FUNCTION.  */
12718       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12719                                    targ_ptr, complain);
12720       if (spec == error_mark_node)
12721         return error_mark_node;
12722
12723       /* Look for the clone.  */
12724       FOR_EACH_CLONE (clone, spec)
12725         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12726           return clone;
12727       /* We should always have found the clone by now.  */
12728       gcc_unreachable ();
12729       return NULL_TREE;
12730     }
12731
12732   /* Check to see if we already have this specialization.  */
12733   gen_tmpl = most_general_template (tmpl);
12734   if (tmpl != gen_tmpl)
12735     /* The TMPL is a partial instantiation.  To get a full set of
12736        arguments we must add the arguments used to perform the
12737        partial instantiation.  */
12738     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12739                                             targ_ptr);
12740
12741   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12742      but it doesn't seem to be on the hot path.  */
12743   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12744
12745   gcc_assert (tmpl == gen_tmpl
12746               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12747                   == spec)
12748               || fndecl == NULL_TREE);
12749
12750   if (spec != NULL_TREE)
12751     return spec;
12752
12753   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12754                                complain))
12755     return error_mark_node;
12756
12757   /* We are building a FUNCTION_DECL, during which the access of its
12758      parameters and return types have to be checked.  However this
12759      FUNCTION_DECL which is the desired context for access checking
12760      is not built yet.  We solve this chicken-and-egg problem by
12761      deferring all checks until we have the FUNCTION_DECL.  */
12762   push_deferring_access_checks (dk_deferred);
12763
12764   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12765      (because, for example, we have encountered a non-dependent
12766      function call in the body of a template function and must now
12767      determine which of several overloaded functions will be called),
12768      within the instantiation itself we are not processing a
12769      template.  */  
12770   saved_processing_template_decl = processing_template_decl;
12771   processing_template_decl = 0;
12772   /* Substitute template parameters to obtain the specialization.  */
12773   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12774                    targ_ptr, complain, gen_tmpl);
12775   processing_template_decl = saved_processing_template_decl;
12776   if (fndecl == error_mark_node)
12777     return error_mark_node;
12778
12779   /* Now we know the specialization, compute access previously
12780      deferred.  */
12781   push_access_scope (fndecl);
12782
12783   /* Some typedefs referenced from within the template code need to be access
12784      checked at template instantiation time, i.e now. These types were
12785      added to the template at parsing time. Let's get those and perfom
12786      the acces checks then.  */
12787   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12788   perform_deferred_access_checks ();
12789   pop_access_scope (fndecl);
12790   pop_deferring_access_checks ();
12791
12792   /* The DECL_TI_TEMPLATE should always be the immediate parent
12793      template, not the most general template.  */
12794   DECL_TI_TEMPLATE (fndecl) = tmpl;
12795
12796   /* If we've just instantiated the main entry point for a function,
12797      instantiate all the alternate entry points as well.  We do this
12798      by cloning the instantiation of the main entry point, not by
12799      instantiating the template clones.  */
12800   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12801     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12802
12803   return fndecl;
12804 }
12805
12806 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12807    NARGS elements of the arguments that are being used when calling
12808    it.  TARGS is a vector into which the deduced template arguments
12809    are placed.
12810
12811    Return zero for success, 2 for an incomplete match that doesn't resolve
12812    all the types, and 1 for complete failure.  An error message will be
12813    printed only for an incomplete match.
12814
12815    If FN is a conversion operator, or we are trying to produce a specific
12816    specialization, RETURN_TYPE is the return type desired.
12817
12818    The EXPLICIT_TARGS are explicit template arguments provided via a
12819    template-id.
12820
12821    The parameter STRICT is one of:
12822
12823    DEDUCE_CALL:
12824      We are deducing arguments for a function call, as in
12825      [temp.deduct.call].
12826
12827    DEDUCE_CONV:
12828      We are deducing arguments for a conversion function, as in
12829      [temp.deduct.conv].
12830
12831    DEDUCE_EXACT:
12832      We are deducing arguments when doing an explicit instantiation
12833      as in [temp.explicit], when determining an explicit specialization
12834      as in [temp.expl.spec], or when taking the address of a function
12835      template, as in [temp.deduct.funcaddr].  */
12836
12837 int
12838 fn_type_unification (tree fn,
12839                      tree explicit_targs,
12840                      tree targs,
12841                      const tree *args,
12842                      unsigned int nargs,
12843                      tree return_type,
12844                      unification_kind_t strict,
12845                      int flags)
12846 {
12847   tree parms;
12848   tree fntype;
12849   int result;
12850   bool incomplete_argument_packs_p = false;
12851
12852   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12853
12854   fntype = TREE_TYPE (fn);
12855   if (explicit_targs)
12856     {
12857       /* [temp.deduct]
12858
12859          The specified template arguments must match the template
12860          parameters in kind (i.e., type, nontype, template), and there
12861          must not be more arguments than there are parameters;
12862          otherwise type deduction fails.
12863
12864          Nontype arguments must match the types of the corresponding
12865          nontype template parameters, or must be convertible to the
12866          types of the corresponding nontype parameters as specified in
12867          _temp.arg.nontype_, otherwise type deduction fails.
12868
12869          All references in the function type of the function template
12870          to the corresponding template parameters are replaced by the
12871          specified template argument values.  If a substitution in a
12872          template parameter or in the function type of the function
12873          template results in an invalid type, type deduction fails.  */
12874       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12875       int i, len = TREE_VEC_LENGTH (tparms);
12876       tree converted_args;
12877       bool incomplete = false;
12878
12879       if (explicit_targs == error_mark_node)
12880         return 1;
12881
12882       converted_args
12883         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12884                                   /*require_all_args=*/false,
12885                                   /*use_default_args=*/false));
12886       if (converted_args == error_mark_node)
12887         return 1;
12888
12889       /* Substitute the explicit args into the function type.  This is
12890          necessary so that, for instance, explicitly declared function
12891          arguments can match null pointed constants.  If we were given
12892          an incomplete set of explicit args, we must not do semantic
12893          processing during substitution as we could create partial
12894          instantiations.  */
12895       for (i = 0; i < len; i++)
12896         {
12897           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12898           bool parameter_pack = false;
12899
12900           /* Dig out the actual parm.  */
12901           if (TREE_CODE (parm) == TYPE_DECL
12902               || TREE_CODE (parm) == TEMPLATE_DECL)
12903             {
12904               parm = TREE_TYPE (parm);
12905               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12906             }
12907           else if (TREE_CODE (parm) == PARM_DECL)
12908             {
12909               parm = DECL_INITIAL (parm);
12910               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12911             }
12912
12913           if (parameter_pack)
12914             {
12915               int level, idx;
12916               tree targ;
12917               template_parm_level_and_index (parm, &level, &idx);
12918
12919               /* Mark the argument pack as "incomplete". We could
12920                  still deduce more arguments during unification.  */
12921               targ = TMPL_ARG (converted_args, level, idx);
12922               if (targ)
12923                 {
12924                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12925                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12926                     = ARGUMENT_PACK_ARGS (targ);
12927                 }
12928
12929               /* We have some incomplete argument packs.  */
12930               incomplete_argument_packs_p = true;
12931             }
12932         }
12933
12934       if (incomplete_argument_packs_p)
12935         /* Any substitution is guaranteed to be incomplete if there
12936            are incomplete argument packs, because we can still deduce
12937            more arguments.  */
12938         incomplete = 1;
12939       else
12940         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12941
12942       processing_template_decl += incomplete;
12943       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12944       processing_template_decl -= incomplete;
12945
12946       if (fntype == error_mark_node)
12947         return 1;
12948
12949       /* Place the explicitly specified arguments in TARGS.  */
12950       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12951         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12952     }
12953
12954   /* Never do unification on the 'this' parameter.  */
12955   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12956
12957   if (return_type)
12958     {
12959       tree *new_args;
12960
12961       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12962       new_args = XALLOCAVEC (tree, nargs + 1);
12963       new_args[0] = return_type;
12964       memcpy (new_args + 1, args, nargs * sizeof (tree));
12965       args = new_args;
12966       ++nargs;
12967     }
12968
12969   /* We allow incomplete unification without an error message here
12970      because the standard doesn't seem to explicitly prohibit it.  Our
12971      callers must be ready to deal with unification failures in any
12972      event.  */
12973   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12974                                   targs, parms, args, nargs, /*subr=*/0,
12975                                   strict, flags);
12976
12977   if (result == 0 && incomplete_argument_packs_p)
12978     {
12979       int i, len = NUM_TMPL_ARGS (targs);
12980
12981       /* Clear the "incomplete" flags on all argument packs.  */
12982       for (i = 0; i < len; i++)
12983         {
12984           tree arg = TREE_VEC_ELT (targs, i);
12985           if (ARGUMENT_PACK_P (arg))
12986             {
12987               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12988               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12989             }
12990         }
12991     }
12992
12993   /* Now that we have bindings for all of the template arguments,
12994      ensure that the arguments deduced for the template template
12995      parameters have compatible template parameter lists.  We cannot
12996      check this property before we have deduced all template
12997      arguments, because the template parameter types of a template
12998      template parameter might depend on prior template parameters
12999      deduced after the template template parameter.  The following
13000      ill-formed example illustrates this issue:
13001
13002        template<typename T, template<T> class C> void f(C<5>, T);
13003
13004        template<int N> struct X {};
13005
13006        void g() {
13007          f(X<5>(), 5l); // error: template argument deduction fails
13008        }
13009
13010      The template parameter list of 'C' depends on the template type
13011      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13012      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13013      time that we deduce 'C'.  */
13014   if (result == 0
13015       && !template_template_parm_bindings_ok_p 
13016            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13017     return 1;
13018
13019   if (result == 0)
13020     /* All is well so far.  Now, check:
13021
13022        [temp.deduct]
13023
13024        When all template arguments have been deduced, all uses of
13025        template parameters in nondeduced contexts are replaced with
13026        the corresponding deduced argument values.  If the
13027        substitution results in an invalid type, as described above,
13028        type deduction fails.  */
13029     {
13030       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13031       if (substed == error_mark_node)
13032         return 1;
13033
13034       /* If we're looking for an exact match, check that what we got
13035          is indeed an exact match.  It might not be if some template
13036          parameters are used in non-deduced contexts.  */
13037       if (strict == DEDUCE_EXACT)
13038         {
13039           unsigned int i;
13040
13041           tree sarg
13042             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13043           if (return_type)
13044             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13045           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13046             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13047               return 1;
13048         }
13049     }
13050
13051   return result;
13052 }
13053
13054 /* Adjust types before performing type deduction, as described in
13055    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13056    sections are symmetric.  PARM is the type of a function parameter
13057    or the return type of the conversion function.  ARG is the type of
13058    the argument passed to the call, or the type of the value
13059    initialized with the result of the conversion function.
13060    ARG_EXPR is the original argument expression, which may be null.  */
13061
13062 static int
13063 maybe_adjust_types_for_deduction (unification_kind_t strict,
13064                                   tree* parm,
13065                                   tree* arg,
13066                                   tree arg_expr)
13067 {
13068   int result = 0;
13069
13070   switch (strict)
13071     {
13072     case DEDUCE_CALL:
13073       break;
13074
13075     case DEDUCE_CONV:
13076       {
13077         /* Swap PARM and ARG throughout the remainder of this
13078            function; the handling is precisely symmetric since PARM
13079            will initialize ARG rather than vice versa.  */
13080         tree* temp = parm;
13081         parm = arg;
13082         arg = temp;
13083         break;
13084       }
13085
13086     case DEDUCE_EXACT:
13087       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13088          too, but here handle it by stripping the reference from PARM
13089          rather than by adding it to ARG.  */
13090       if (TREE_CODE (*parm) == REFERENCE_TYPE
13091           && TYPE_REF_IS_RVALUE (*parm)
13092           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13093           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13094           && TREE_CODE (*arg) == REFERENCE_TYPE
13095           && !TYPE_REF_IS_RVALUE (*arg))
13096         *parm = TREE_TYPE (*parm);
13097       /* Nothing else to do in this case.  */
13098       return 0;
13099
13100     default:
13101       gcc_unreachable ();
13102     }
13103
13104   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13105     {
13106       /* [temp.deduct.call]
13107
13108          If P is not a reference type:
13109
13110          --If A is an array type, the pointer type produced by the
13111          array-to-pointer standard conversion (_conv.array_) is
13112          used in place of A for type deduction; otherwise,
13113
13114          --If A is a function type, the pointer type produced by
13115          the function-to-pointer standard conversion
13116          (_conv.func_) is used in place of A for type deduction;
13117          otherwise,
13118
13119          --If A is a cv-qualified type, the top level
13120          cv-qualifiers of A's type are ignored for type
13121          deduction.  */
13122       if (TREE_CODE (*arg) == ARRAY_TYPE)
13123         *arg = build_pointer_type (TREE_TYPE (*arg));
13124       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13125         *arg = build_pointer_type (*arg);
13126       else
13127         *arg = TYPE_MAIN_VARIANT (*arg);
13128     }
13129
13130   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13131      of the form T&&, where T is a template parameter, and the argument
13132      is an lvalue, T is deduced as A& */
13133   if (TREE_CODE (*parm) == REFERENCE_TYPE
13134       && TYPE_REF_IS_RVALUE (*parm)
13135       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13136       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13137       && arg_expr && real_lvalue_p (arg_expr))
13138     *arg = build_reference_type (*arg);
13139
13140   /* [temp.deduct.call]
13141
13142      If P is a cv-qualified type, the top level cv-qualifiers
13143      of P's type are ignored for type deduction.  If P is a
13144      reference type, the type referred to by P is used for
13145      type deduction.  */
13146   *parm = TYPE_MAIN_VARIANT (*parm);
13147   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13148     {
13149       *parm = TREE_TYPE (*parm);
13150       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13151     }
13152
13153   /* DR 322. For conversion deduction, remove a reference type on parm
13154      too (which has been swapped into ARG).  */
13155   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13156     *arg = TREE_TYPE (*arg);
13157
13158   return result;
13159 }
13160
13161 /* Most parms like fn_type_unification.
13162
13163    If SUBR is 1, we're being called recursively (to unify the
13164    arguments of a function or method parameter of a function
13165    template). */
13166
13167 static int
13168 type_unification_real (tree tparms,
13169                        tree targs,
13170                        tree xparms,
13171                        const tree *xargs,
13172                        unsigned int xnargs,
13173                        int subr,
13174                        unification_kind_t strict,
13175                        int flags)
13176 {
13177   tree parm, arg, arg_expr;
13178   int i;
13179   int ntparms = TREE_VEC_LENGTH (tparms);
13180   int sub_strict;
13181   int saw_undeduced = 0;
13182   tree parms;
13183   const tree *args;
13184   unsigned int nargs;
13185   unsigned int ia;
13186
13187   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13188   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13189   gcc_assert (ntparms > 0);
13190
13191   switch (strict)
13192     {
13193     case DEDUCE_CALL:
13194       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13195                     | UNIFY_ALLOW_DERIVED);
13196       break;
13197
13198     case DEDUCE_CONV:
13199       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13200       break;
13201
13202     case DEDUCE_EXACT:
13203       sub_strict = UNIFY_ALLOW_NONE;
13204       break;
13205
13206     default:
13207       gcc_unreachable ();
13208     }
13209
13210  again:
13211   parms = xparms;
13212   args = xargs;
13213   nargs = xnargs;
13214
13215   ia = 0;
13216   while (parms && parms != void_list_node
13217          && ia < nargs)
13218     {
13219       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13220         break;
13221
13222       parm = TREE_VALUE (parms);
13223       parms = TREE_CHAIN (parms);
13224       arg = args[ia];
13225       ++ia;
13226       arg_expr = NULL;
13227
13228       if (arg == error_mark_node)
13229         return 1;
13230       if (arg == unknown_type_node)
13231         /* We can't deduce anything from this, but we might get all the
13232            template args from other function args.  */
13233         continue;
13234
13235       /* Conversions will be performed on a function argument that
13236          corresponds with a function parameter that contains only
13237          non-deducible template parameters and explicitly specified
13238          template parameters.  */
13239       if (!uses_template_parms (parm))
13240         {
13241           tree type;
13242
13243           if (!TYPE_P (arg))
13244             type = TREE_TYPE (arg);
13245           else
13246             type = arg;
13247
13248           if (same_type_p (parm, type))
13249             continue;
13250           if (strict != DEDUCE_EXACT
13251               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13252                                   flags))
13253             continue;
13254
13255           return 1;
13256         }
13257
13258       if (!TYPE_P (arg))
13259         {
13260           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13261           if (type_unknown_p (arg))
13262             {
13263               /* [temp.deduct.type] 
13264
13265                  A template-argument can be deduced from a pointer to
13266                  function or pointer to member function argument if
13267                  the set of overloaded functions does not contain
13268                  function templates and at most one of a set of
13269                  overloaded functions provides a unique match.  */
13270               if (resolve_overloaded_unification
13271                   (tparms, targs, parm, arg, strict, sub_strict))
13272                 continue;
13273
13274               return 1;
13275             }
13276           arg_expr = arg;
13277           arg = unlowered_expr_type (arg);
13278           if (arg == error_mark_node)
13279             return 1;
13280         }
13281
13282       {
13283         int arg_strict = sub_strict;
13284
13285         if (!subr)
13286           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13287                                                           arg_expr);
13288
13289         if (arg == init_list_type_node && arg_expr)
13290           arg = arg_expr;
13291         if (unify (tparms, targs, parm, arg, arg_strict))
13292           return 1;
13293       }
13294     }
13295
13296
13297   if (parms 
13298       && parms != void_list_node
13299       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13300     {
13301       /* Unify the remaining arguments with the pack expansion type.  */
13302       tree argvec;
13303       tree parmvec = make_tree_vec (1);
13304
13305       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13306       argvec = make_tree_vec (nargs - ia);
13307       for (i = 0; ia < nargs; ++ia, ++i)
13308         TREE_VEC_ELT (argvec, i) = args[ia];
13309
13310       /* Copy the parameter into parmvec.  */
13311       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13312       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13313                                 /*call_args_p=*/true, /*subr=*/subr))
13314         return 1;
13315
13316       /* Advance to the end of the list of parameters.  */
13317       parms = TREE_CHAIN (parms);
13318     }
13319
13320   /* Fail if we've reached the end of the parm list, and more args
13321      are present, and the parm list isn't variadic.  */
13322   if (ia < nargs && parms == void_list_node)
13323     return 1;
13324   /* Fail if parms are left and they don't have default values.  */
13325   if (parms && parms != void_list_node
13326       && TREE_PURPOSE (parms) == NULL_TREE)
13327     return 1;
13328
13329   if (!subr)
13330     for (i = 0; i < ntparms; i++)
13331       if (!TREE_VEC_ELT (targs, i))
13332         {
13333           tree tparm;
13334
13335           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13336             continue;
13337
13338           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13339
13340           /* If this is an undeduced nontype parameter that depends on
13341              a type parameter, try another pass; its type may have been
13342              deduced from a later argument than the one from which
13343              this parameter can be deduced.  */
13344           if (TREE_CODE (tparm) == PARM_DECL
13345               && uses_template_parms (TREE_TYPE (tparm))
13346               && !saw_undeduced++)
13347             goto again;
13348
13349           /* Core issue #226 (C++0x) [temp.deduct]:
13350
13351                If a template argument has not been deduced, its
13352                default template argument, if any, is used. 
13353
13354              When we are in C++98 mode, TREE_PURPOSE will either
13355              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13356              to explicitly check cxx_dialect here.  */
13357           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13358             {
13359               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13360               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13361               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13362               arg = convert_template_argument (parm, arg, targs, tf_none,
13363                                                i, NULL_TREE);
13364               if (arg == error_mark_node)
13365                 return 1;
13366               else
13367                 {
13368                   TREE_VEC_ELT (targs, i) = arg;
13369                   continue;
13370                 }
13371             }
13372
13373           /* If the type parameter is a parameter pack, then it will
13374              be deduced to an empty parameter pack.  */
13375           if (template_parameter_pack_p (tparm))
13376             {
13377               tree arg;
13378
13379               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13380                 {
13381                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13382                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13383                   TREE_CONSTANT (arg) = 1;
13384                 }
13385               else
13386                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13387
13388               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13389
13390               TREE_VEC_ELT (targs, i) = arg;
13391               continue;
13392             }
13393
13394           return 2;
13395         }
13396
13397   return 0;
13398 }
13399
13400 /* Subroutine of type_unification_real.  Args are like the variables
13401    at the call site.  ARG is an overloaded function (or template-id);
13402    we try deducing template args from each of the overloads, and if
13403    only one succeeds, we go with that.  Modifies TARGS and returns
13404    true on success.  */
13405
13406 static bool
13407 resolve_overloaded_unification (tree tparms,
13408                                 tree targs,
13409                                 tree parm,
13410                                 tree arg,
13411                                 unification_kind_t strict,
13412                                 int sub_strict)
13413 {
13414   tree tempargs = copy_node (targs);
13415   int good = 0;
13416   tree goodfn = NULL_TREE;
13417   bool addr_p;
13418
13419   if (TREE_CODE (arg) == ADDR_EXPR)
13420     {
13421       arg = TREE_OPERAND (arg, 0);
13422       addr_p = true;
13423     }
13424   else
13425     addr_p = false;
13426
13427   if (TREE_CODE (arg) == COMPONENT_REF)
13428     /* Handle `&x' where `x' is some static or non-static member
13429        function name.  */
13430     arg = TREE_OPERAND (arg, 1);
13431
13432   if (TREE_CODE (arg) == OFFSET_REF)
13433     arg = TREE_OPERAND (arg, 1);
13434
13435   /* Strip baselink information.  */
13436   if (BASELINK_P (arg))
13437     arg = BASELINK_FUNCTIONS (arg);
13438
13439   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13440     {
13441       /* If we got some explicit template args, we need to plug them into
13442          the affected templates before we try to unify, in case the
13443          explicit args will completely resolve the templates in question.  */
13444
13445       tree expl_subargs = TREE_OPERAND (arg, 1);
13446       arg = TREE_OPERAND (arg, 0);
13447
13448       for (; arg; arg = OVL_NEXT (arg))
13449         {
13450           tree fn = OVL_CURRENT (arg);
13451           tree subargs, elem;
13452
13453           if (TREE_CODE (fn) != TEMPLATE_DECL)
13454             continue;
13455
13456           ++processing_template_decl;
13457           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13458                                   expl_subargs, /*check_ret=*/false);
13459           if (subargs)
13460             {
13461               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13462               if (try_one_overload (tparms, targs, tempargs, parm,
13463                                     elem, strict, sub_strict, addr_p)
13464                   && (!goodfn || !decls_match (goodfn, elem)))
13465                 {
13466                   goodfn = elem;
13467                   ++good;
13468                 }
13469             }
13470           --processing_template_decl;
13471         }
13472     }
13473   else if (TREE_CODE (arg) != OVERLOAD
13474            && TREE_CODE (arg) != FUNCTION_DECL)
13475     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13476        -- but the deduction does not succeed because the expression is
13477        not just the function on its own.  */
13478     return false;
13479   else
13480     for (; arg; arg = OVL_NEXT (arg))
13481       if (try_one_overload (tparms, targs, tempargs, parm,
13482                             TREE_TYPE (OVL_CURRENT (arg)),
13483                             strict, sub_strict, addr_p)
13484           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13485         {
13486           goodfn = OVL_CURRENT (arg);
13487           ++good;
13488         }
13489
13490   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13491      to function or pointer to member function argument if the set of
13492      overloaded functions does not contain function templates and at most
13493      one of a set of overloaded functions provides a unique match.
13494
13495      So if we found multiple possibilities, we return success but don't
13496      deduce anything.  */
13497
13498   if (good == 1)
13499     {
13500       int i = TREE_VEC_LENGTH (targs);
13501       for (; i--; )
13502         if (TREE_VEC_ELT (tempargs, i))
13503           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13504     }
13505   if (good)
13506     return true;
13507
13508   return false;
13509 }
13510
13511 /* Core DR 115: In contexts where deduction is done and fails, or in
13512    contexts where deduction is not done, if a template argument list is
13513    specified and it, along with any default template arguments, identifies
13514    a single function template specialization, then the template-id is an
13515    lvalue for the function template specialization.  */
13516
13517 tree
13518 resolve_nondeduced_context (tree orig_expr)
13519 {
13520   tree expr, offset, baselink;
13521   bool addr;
13522
13523   if (!type_unknown_p (orig_expr))
13524     return orig_expr;
13525
13526   expr = orig_expr;
13527   addr = false;
13528   offset = NULL_TREE;
13529   baselink = NULL_TREE;
13530
13531   if (TREE_CODE (expr) == ADDR_EXPR)
13532     {
13533       expr = TREE_OPERAND (expr, 0);
13534       addr = true;
13535     }
13536   if (TREE_CODE (expr) == OFFSET_REF)
13537     {
13538       offset = expr;
13539       expr = TREE_OPERAND (expr, 1);
13540     }
13541   if (TREE_CODE (expr) == BASELINK)
13542     {
13543       baselink = expr;
13544       expr = BASELINK_FUNCTIONS (expr);
13545     }
13546
13547   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13548     {
13549       int good = 0;
13550       tree goodfn = NULL_TREE;
13551
13552       /* If we got some explicit template args, we need to plug them into
13553          the affected templates before we try to unify, in case the
13554          explicit args will completely resolve the templates in question.  */
13555
13556       tree expl_subargs = TREE_OPERAND (expr, 1);
13557       tree arg = TREE_OPERAND (expr, 0);
13558       tree badfn = NULL_TREE;
13559       tree badargs = NULL_TREE;
13560
13561       for (; arg; arg = OVL_NEXT (arg))
13562         {
13563           tree fn = OVL_CURRENT (arg);
13564           tree subargs, elem;
13565
13566           if (TREE_CODE (fn) != TEMPLATE_DECL)
13567             continue;
13568
13569           ++processing_template_decl;
13570           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13571                                   expl_subargs, /*check_ret=*/false);
13572           if (subargs && !any_dependent_template_arguments_p (subargs))
13573             {
13574               elem = instantiate_template (fn, subargs, tf_none);
13575               if (elem == error_mark_node)
13576                 {
13577                   badfn = fn;
13578                   badargs = subargs;
13579                 }
13580               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13581                 {
13582                   goodfn = elem;
13583                   ++good;
13584                 }
13585             }
13586           --processing_template_decl;
13587         }
13588       if (good == 1)
13589         {
13590           expr = goodfn;
13591           if (baselink)
13592             expr = build_baselink (BASELINK_BINFO (baselink),
13593                                    BASELINK_ACCESS_BINFO (baselink),
13594                                    expr, BASELINK_OPTYPE (baselink));
13595           if (offset)
13596             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13597                            TREE_OPERAND (offset, 0), expr);
13598           if (addr)
13599             expr = build_address (expr);
13600           return expr;
13601         }
13602       else if (good == 0 && badargs)
13603         /* There were no good options and at least one bad one, so let the
13604            user know what the problem is.  */
13605         instantiate_template (badfn, badargs, tf_warning_or_error);
13606     }
13607   return orig_expr;
13608 }
13609
13610 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13611    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13612    different overloads deduce different arguments for a given parm.
13613    ADDR_P is true if the expression for which deduction is being
13614    performed was of the form "& fn" rather than simply "fn".
13615
13616    Returns 1 on success.  */
13617
13618 static int
13619 try_one_overload (tree tparms,
13620                   tree orig_targs,
13621                   tree targs,
13622                   tree parm,
13623                   tree arg,
13624                   unification_kind_t strict,
13625                   int sub_strict,
13626                   bool addr_p)
13627 {
13628   int nargs;
13629   tree tempargs;
13630   int i;
13631
13632   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13633      to function or pointer to member function argument if the set of
13634      overloaded functions does not contain function templates and at most
13635      one of a set of overloaded functions provides a unique match.
13636
13637      So if this is a template, just return success.  */
13638
13639   if (uses_template_parms (arg))
13640     return 1;
13641
13642   if (TREE_CODE (arg) == METHOD_TYPE)
13643     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13644   else if (addr_p)
13645     arg = build_pointer_type (arg);
13646
13647   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13648
13649   /* We don't copy orig_targs for this because if we have already deduced
13650      some template args from previous args, unify would complain when we
13651      try to deduce a template parameter for the same argument, even though
13652      there isn't really a conflict.  */
13653   nargs = TREE_VEC_LENGTH (targs);
13654   tempargs = make_tree_vec (nargs);
13655
13656   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13657     return 0;
13658
13659   /* First make sure we didn't deduce anything that conflicts with
13660      explicitly specified args.  */
13661   for (i = nargs; i--; )
13662     {
13663       tree elt = TREE_VEC_ELT (tempargs, i);
13664       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13665
13666       if (!elt)
13667         /*NOP*/;
13668       else if (uses_template_parms (elt))
13669         /* Since we're unifying against ourselves, we will fill in
13670            template args used in the function parm list with our own
13671            template parms.  Discard them.  */
13672         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13673       else if (oldelt && !template_args_equal (oldelt, elt))
13674         return 0;
13675     }
13676
13677   for (i = nargs; i--; )
13678     {
13679       tree elt = TREE_VEC_ELT (tempargs, i);
13680
13681       if (elt)
13682         TREE_VEC_ELT (targs, i) = elt;
13683     }
13684
13685   return 1;
13686 }
13687
13688 /* PARM is a template class (perhaps with unbound template
13689    parameters).  ARG is a fully instantiated type.  If ARG can be
13690    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13691    TARGS are as for unify.  */
13692
13693 static tree
13694 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13695 {
13696   tree copy_of_targs;
13697
13698   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13699       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13700           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13701     return NULL_TREE;
13702
13703   /* We need to make a new template argument vector for the call to
13704      unify.  If we used TARGS, we'd clutter it up with the result of
13705      the attempted unification, even if this class didn't work out.
13706      We also don't want to commit ourselves to all the unifications
13707      we've already done, since unification is supposed to be done on
13708      an argument-by-argument basis.  In other words, consider the
13709      following pathological case:
13710
13711        template <int I, int J, int K>
13712        struct S {};
13713
13714        template <int I, int J>
13715        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13716
13717        template <int I, int J, int K>
13718        void f(S<I, J, K>, S<I, I, I>);
13719
13720        void g() {
13721          S<0, 0, 0> s0;
13722          S<0, 1, 2> s2;
13723
13724          f(s0, s2);
13725        }
13726
13727      Now, by the time we consider the unification involving `s2', we
13728      already know that we must have `f<0, 0, 0>'.  But, even though
13729      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13730      because there are two ways to unify base classes of S<0, 1, 2>
13731      with S<I, I, I>.  If we kept the already deduced knowledge, we
13732      would reject the possibility I=1.  */
13733   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13734
13735   /* If unification failed, we're done.  */
13736   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13737              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13738     return NULL_TREE;
13739
13740   return arg;
13741 }
13742
13743 /* Given a template type PARM and a class type ARG, find the unique
13744    base type in ARG that is an instance of PARM.  We do not examine
13745    ARG itself; only its base-classes.  If there is not exactly one
13746    appropriate base class, return NULL_TREE.  PARM may be the type of
13747    a partial specialization, as well as a plain template type.  Used
13748    by unify.  */
13749
13750 static tree
13751 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13752 {
13753   tree rval = NULL_TREE;
13754   tree binfo;
13755
13756   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13757
13758   binfo = TYPE_BINFO (complete_type (arg));
13759   if (!binfo)
13760     /* The type could not be completed.  */
13761     return NULL_TREE;
13762
13763   /* Walk in inheritance graph order.  The search order is not
13764      important, and this avoids multiple walks of virtual bases.  */
13765   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13766     {
13767       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13768
13769       if (r)
13770         {
13771           /* If there is more than one satisfactory baseclass, then:
13772
13773                [temp.deduct.call]
13774
13775               If they yield more than one possible deduced A, the type
13776               deduction fails.
13777
13778              applies.  */
13779           if (rval && !same_type_p (r, rval))
13780             return NULL_TREE;
13781
13782           rval = r;
13783         }
13784     }
13785
13786   return rval;
13787 }
13788
13789 /* Returns the level of DECL, which declares a template parameter.  */
13790
13791 static int
13792 template_decl_level (tree decl)
13793 {
13794   switch (TREE_CODE (decl))
13795     {
13796     case TYPE_DECL:
13797     case TEMPLATE_DECL:
13798       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13799
13800     case PARM_DECL:
13801       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13802
13803     default:
13804       gcc_unreachable ();
13805     }
13806   return 0;
13807 }
13808
13809 /* Decide whether ARG can be unified with PARM, considering only the
13810    cv-qualifiers of each type, given STRICT as documented for unify.
13811    Returns nonzero iff the unification is OK on that basis.  */
13812
13813 static int
13814 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13815 {
13816   int arg_quals = cp_type_quals (arg);
13817   int parm_quals = cp_type_quals (parm);
13818
13819   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13820       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13821     {
13822       /*  Although a CVR qualifier is ignored when being applied to a
13823           substituted template parameter ([8.3.2]/1 for example), that
13824           does not apply during deduction [14.8.2.4]/1, (even though
13825           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13826           this).  Except when we're allowing additional CV qualifiers
13827           at the outer level [14.8.2.1]/3,1st bullet.  */
13828       if ((TREE_CODE (arg) == REFERENCE_TYPE
13829            || TREE_CODE (arg) == FUNCTION_TYPE
13830            || TREE_CODE (arg) == METHOD_TYPE)
13831           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13832         return 0;
13833
13834       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13835           && (parm_quals & TYPE_QUAL_RESTRICT))
13836         return 0;
13837     }
13838
13839   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13840       && (arg_quals & parm_quals) != parm_quals)
13841     return 0;
13842
13843   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13844       && (parm_quals & arg_quals) != arg_quals)
13845     return 0;
13846
13847   return 1;
13848 }
13849
13850 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13851 void 
13852 template_parm_level_and_index (tree parm, int* level, int* index)
13853 {
13854   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13855       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13856       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13857     {
13858       *index = TEMPLATE_TYPE_IDX (parm);
13859       *level = TEMPLATE_TYPE_LEVEL (parm);
13860     }
13861   else
13862     {
13863       *index = TEMPLATE_PARM_IDX (parm);
13864       *level = TEMPLATE_PARM_LEVEL (parm);
13865     }
13866 }
13867
13868 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13869    expansion at the end of PACKED_PARMS. Returns 0 if the type
13870    deduction succeeds, 1 otherwise. STRICT is the same as in
13871    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13872    call argument list. We'll need to adjust the arguments to make them
13873    types. SUBR tells us if this is from a recursive call to
13874    type_unification_real.  */
13875 int
13876 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13877                       tree packed_args, int strict, bool call_args_p,
13878                       bool subr)
13879 {
13880   tree parm 
13881     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13882   tree pattern = PACK_EXPANSION_PATTERN (parm);
13883   tree pack, packs = NULL_TREE;
13884   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13885   int len = TREE_VEC_LENGTH (packed_args);
13886
13887   /* Determine the parameter packs we will be deducing from the
13888      pattern, and record their current deductions.  */
13889   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13890        pack; pack = TREE_CHAIN (pack))
13891     {
13892       tree parm_pack = TREE_VALUE (pack);
13893       int idx, level;
13894
13895       /* Determine the index and level of this parameter pack.  */
13896       template_parm_level_and_index (parm_pack, &level, &idx);
13897
13898       /* Keep track of the parameter packs and their corresponding
13899          argument packs.  */
13900       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13901       TREE_TYPE (packs) = make_tree_vec (len - start);
13902     }
13903   
13904   /* Loop through all of the arguments that have not yet been
13905      unified and unify each with the pattern.  */
13906   for (i = start; i < len; i++)
13907     {
13908       tree parm = pattern;
13909
13910       /* For each parameter pack, clear out the deduced value so that
13911          we can deduce it again.  */
13912       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13913         {
13914           int idx, level;
13915           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13916
13917           TMPL_ARG (targs, level, idx) = NULL_TREE;
13918         }
13919
13920       /* Unify the pattern with the current argument.  */
13921       {
13922         tree arg = TREE_VEC_ELT (packed_args, i);
13923         tree arg_expr = NULL_TREE;
13924         int arg_strict = strict;
13925         bool skip_arg_p = false;
13926
13927         if (call_args_p)
13928           {
13929             int sub_strict;
13930
13931             /* This mirrors what we do in type_unification_real.  */
13932             switch (strict)
13933               {
13934               case DEDUCE_CALL:
13935                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13936                               | UNIFY_ALLOW_MORE_CV_QUAL
13937                               | UNIFY_ALLOW_DERIVED);
13938                 break;
13939                 
13940               case DEDUCE_CONV:
13941                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13942                 break;
13943                 
13944               case DEDUCE_EXACT:
13945                 sub_strict = UNIFY_ALLOW_NONE;
13946                 break;
13947                 
13948               default:
13949                 gcc_unreachable ();
13950               }
13951
13952             if (!TYPE_P (arg))
13953               {
13954                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13955                 if (type_unknown_p (arg))
13956                   {
13957                     /* [temp.deduct.type] A template-argument can be
13958                        deduced from a pointer to function or pointer
13959                        to member function argument if the set of
13960                        overloaded functions does not contain function
13961                        templates and at most one of a set of
13962                        overloaded functions provides a unique
13963                        match.  */
13964
13965                     if (resolve_overloaded_unification
13966                         (tparms, targs, parm, arg,
13967                          (unification_kind_t) strict,
13968                          sub_strict)
13969                         != 0)
13970                       return 1;
13971                     skip_arg_p = true;
13972                   }
13973
13974                 if (!skip_arg_p)
13975                   {
13976                     arg_expr = arg;
13977                     arg = unlowered_expr_type (arg);
13978                     if (arg == error_mark_node)
13979                       return 1;
13980                   }
13981               }
13982       
13983             arg_strict = sub_strict;
13984
13985             if (!subr)
13986               arg_strict |= 
13987                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13988                                                   &parm, &arg, arg_expr);
13989           }
13990
13991         if (!skip_arg_p)
13992           {
13993             if (unify (tparms, targs, parm, arg, arg_strict))
13994               return 1;
13995           }
13996       }
13997
13998       /* For each parameter pack, collect the deduced value.  */
13999       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14000         {
14001           int idx, level;
14002           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14003
14004           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14005             TMPL_ARG (targs, level, idx);
14006         }
14007     }
14008
14009   /* Verify that the results of unification with the parameter packs
14010      produce results consistent with what we've seen before, and make
14011      the deduced argument packs available.  */
14012   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14013     {
14014       tree old_pack = TREE_VALUE (pack);
14015       tree new_args = TREE_TYPE (pack);
14016       int i, len = TREE_VEC_LENGTH (new_args);
14017       bool nondeduced_p = false;
14018
14019       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14020          actually deduce anything.  */
14021       for (i = 0; i < len && !nondeduced_p; ++i)
14022         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14023           nondeduced_p = true;
14024       if (nondeduced_p)
14025         continue;
14026
14027       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14028         {
14029           /* Prepend the explicit arguments onto NEW_ARGS.  */
14030           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14031           tree old_args = new_args;
14032           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14033           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14034
14035           /* Copy the explicit arguments.  */
14036           new_args = make_tree_vec (len);
14037           for (i = 0; i < explicit_len; i++)
14038             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14039
14040           /* Copy the deduced arguments.  */
14041           for (; i < len; i++)
14042             TREE_VEC_ELT (new_args, i) =
14043               TREE_VEC_ELT (old_args, i - explicit_len);
14044         }
14045
14046       if (!old_pack)
14047         {
14048           tree result;
14049           int idx, level;
14050           
14051           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14052
14053           /* Build the deduced *_ARGUMENT_PACK.  */
14054           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14055             {
14056               result = make_node (NONTYPE_ARGUMENT_PACK);
14057               TREE_TYPE (result) = 
14058                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14059               TREE_CONSTANT (result) = 1;
14060             }
14061           else
14062             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14063
14064           SET_ARGUMENT_PACK_ARGS (result, new_args);
14065
14066           /* Note the deduced argument packs for this parameter
14067              pack.  */
14068           TMPL_ARG (targs, level, idx) = result;
14069         }
14070       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14071                && (ARGUMENT_PACK_ARGS (old_pack) 
14072                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14073         {
14074           /* We only had the explicitly-provided arguments before, but
14075              now we have a complete set of arguments.  */
14076           int idx, level;
14077           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14078           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14079
14080           /* Keep the original deduced argument pack.  */
14081           TMPL_ARG (targs, level, idx) = old_pack;
14082
14083           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14084           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14085           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14086         }
14087       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14088                                     new_args))
14089         /* Inconsistent unification of this parameter pack.  */
14090         return 1;
14091       else
14092         {
14093           int idx, level;
14094           
14095           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14096
14097           /* Keep the original deduced argument pack.  */
14098           TMPL_ARG (targs, level, idx) = old_pack;
14099         }
14100     }
14101
14102   return 0;
14103 }
14104
14105 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14106    set of template parameters to a template.  TARGS is the bindings
14107    for those template parameters, as determined thus far; TARGS may
14108    include template arguments for outer levels of template parameters
14109    as well.  PARM is a parameter to a template function, or a
14110    subcomponent of that parameter; ARG is the corresponding argument.
14111    This function attempts to match PARM with ARG in a manner
14112    consistent with the existing assignments in TARGS.  If more values
14113    are deduced, then TARGS is updated.
14114
14115    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14116    parameter STRICT is a bitwise or of the following flags:
14117
14118      UNIFY_ALLOW_NONE:
14119        Require an exact match between PARM and ARG.
14120      UNIFY_ALLOW_MORE_CV_QUAL:
14121        Allow the deduced ARG to be more cv-qualified (by qualification
14122        conversion) than ARG.
14123      UNIFY_ALLOW_LESS_CV_QUAL:
14124        Allow the deduced ARG to be less cv-qualified than ARG.
14125      UNIFY_ALLOW_DERIVED:
14126        Allow the deduced ARG to be a template base class of ARG,
14127        or a pointer to a template base class of the type pointed to by
14128        ARG.
14129      UNIFY_ALLOW_INTEGER:
14130        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14131        case for more information.
14132      UNIFY_ALLOW_OUTER_LEVEL:
14133        This is the outermost level of a deduction. Used to determine validity
14134        of qualification conversions. A valid qualification conversion must
14135        have const qualified pointers leading up to the inner type which
14136        requires additional CV quals, except at the outer level, where const
14137        is not required [conv.qual]. It would be normal to set this flag in
14138        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14139      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14140        This is the outermost level of a deduction, and PARM can be more CV
14141        qualified at this point.
14142      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14143        This is the outermost level of a deduction, and PARM can be less CV
14144        qualified at this point.  */
14145
14146 static int
14147 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14148 {
14149   int idx;
14150   tree targ;
14151   tree tparm;
14152   int strict_in = strict;
14153
14154   /* I don't think this will do the right thing with respect to types.
14155      But the only case I've seen it in so far has been array bounds, where
14156      signedness is the only information lost, and I think that will be
14157      okay.  */
14158   while (TREE_CODE (parm) == NOP_EXPR)
14159     parm = TREE_OPERAND (parm, 0);
14160
14161   if (arg == error_mark_node)
14162     return 1;
14163   if (arg == unknown_type_node
14164       || arg == init_list_type_node)
14165     /* We can't deduce anything from this, but we might get all the
14166        template args from other function args.  */
14167     return 0;
14168
14169   /* If PARM uses template parameters, then we can't bail out here,
14170      even if ARG == PARM, since we won't record unifications for the
14171      template parameters.  We might need them if we're trying to
14172      figure out which of two things is more specialized.  */
14173   if (arg == parm && !uses_template_parms (parm))
14174     return 0;
14175
14176   /* Handle init lists early, so the rest of the function can assume
14177      we're dealing with a type. */
14178   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14179     {
14180       tree elt, elttype;
14181       unsigned i;
14182       tree orig_parm = parm;
14183
14184       /* Replace T with std::initializer_list<T> for deduction.  */
14185       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14186           && flag_deduce_init_list)
14187         parm = listify (parm);
14188
14189       if (!is_std_init_list (parm))
14190         /* We can only deduce from an initializer list argument if the
14191            parameter is std::initializer_list; otherwise this is a
14192            non-deduced context. */
14193         return 0;
14194
14195       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14196
14197       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14198         {
14199           int elt_strict = strict;
14200           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14201             {
14202               tree type = TREE_TYPE (elt);
14203               /* It should only be possible to get here for a call.  */
14204               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14205               elt_strict |= maybe_adjust_types_for_deduction
14206                 (DEDUCE_CALL, &elttype, &type, elt);
14207               elt = type;
14208             }
14209
14210           if (unify (tparms, targs, elttype, elt, elt_strict))
14211             return 1;
14212         }
14213
14214       /* If the std::initializer_list<T> deduction worked, replace the
14215          deduced A with std::initializer_list<A>.  */
14216       if (orig_parm != parm)
14217         {
14218           idx = TEMPLATE_TYPE_IDX (orig_parm);
14219           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14220           targ = listify (targ);
14221           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14222         }
14223       return 0;
14224     }
14225
14226   /* Immediately reject some pairs that won't unify because of
14227      cv-qualification mismatches.  */
14228   if (TREE_CODE (arg) == TREE_CODE (parm)
14229       && TYPE_P (arg)
14230       /* It is the elements of the array which hold the cv quals of an array
14231          type, and the elements might be template type parms. We'll check
14232          when we recurse.  */
14233       && TREE_CODE (arg) != ARRAY_TYPE
14234       /* We check the cv-qualifiers when unifying with template type
14235          parameters below.  We want to allow ARG `const T' to unify with
14236          PARM `T' for example, when computing which of two templates
14237          is more specialized, for example.  */
14238       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14239       && !check_cv_quals_for_unify (strict_in, arg, parm))
14240     return 1;
14241
14242   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14243       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14244     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14245   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14246   strict &= ~UNIFY_ALLOW_DERIVED;
14247   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14248   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14249
14250   switch (TREE_CODE (parm))
14251     {
14252     case TYPENAME_TYPE:
14253     case SCOPE_REF:
14254     case UNBOUND_CLASS_TEMPLATE:
14255       /* In a type which contains a nested-name-specifier, template
14256          argument values cannot be deduced for template parameters used
14257          within the nested-name-specifier.  */
14258       return 0;
14259
14260     case TEMPLATE_TYPE_PARM:
14261     case TEMPLATE_TEMPLATE_PARM:
14262     case BOUND_TEMPLATE_TEMPLATE_PARM:
14263       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14264       if (tparm == error_mark_node)
14265         return 1;
14266
14267       if (TEMPLATE_TYPE_LEVEL (parm)
14268           != template_decl_level (tparm))
14269         /* The PARM is not one we're trying to unify.  Just check
14270            to see if it matches ARG.  */
14271         return (TREE_CODE (arg) == TREE_CODE (parm)
14272                 && same_type_p (parm, arg)) ? 0 : 1;
14273       idx = TEMPLATE_TYPE_IDX (parm);
14274       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14275       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14276
14277       /* Check for mixed types and values.  */
14278       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14279            && TREE_CODE (tparm) != TYPE_DECL)
14280           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14281               && TREE_CODE (tparm) != TEMPLATE_DECL))
14282         return 1;
14283
14284       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14285         {
14286           /* ARG must be constructed from a template class or a template
14287              template parameter.  */
14288           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14289               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14290             return 1;
14291
14292           {
14293             tree parmvec = TYPE_TI_ARGS (parm);
14294             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14295             tree parm_parms 
14296               = DECL_INNERMOST_TEMPLATE_PARMS
14297                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14298             int i, len;
14299             int parm_variadic_p = 0;
14300
14301             /* The resolution to DR150 makes clear that default
14302                arguments for an N-argument may not be used to bind T
14303                to a template template parameter with fewer than N
14304                parameters.  It is not safe to permit the binding of
14305                default arguments as an extension, as that may change
14306                the meaning of a conforming program.  Consider:
14307
14308                   struct Dense { static const unsigned int dim = 1; };
14309
14310                   template <template <typename> class View,
14311                             typename Block>
14312                   void operator+(float, View<Block> const&);
14313
14314                   template <typename Block,
14315                             unsigned int Dim = Block::dim>
14316                   struct Lvalue_proxy { operator float() const; };
14317
14318                   void
14319                   test_1d (void) {
14320                     Lvalue_proxy<Dense> p;
14321                     float b;
14322                     b + p;
14323                   }
14324
14325               Here, if Lvalue_proxy is permitted to bind to View, then
14326               the global operator+ will be used; if they are not, the
14327               Lvalue_proxy will be converted to float.  */
14328             if (coerce_template_parms (parm_parms,
14329                                        argvec,
14330                                        TYPE_TI_TEMPLATE (parm),
14331                                        tf_none,
14332                                        /*require_all_args=*/true,
14333                                        /*use_default_args=*/false)
14334                 == error_mark_node)
14335               return 1;
14336
14337             /* Deduce arguments T, i from TT<T> or TT<i>.
14338                We check each element of PARMVEC and ARGVEC individually
14339                rather than the whole TREE_VEC since they can have
14340                different number of elements.  */
14341
14342             parmvec = expand_template_argument_pack (parmvec);
14343             argvec = expand_template_argument_pack (argvec);
14344
14345             len = TREE_VEC_LENGTH (parmvec);
14346
14347             /* Check if the parameters end in a pack, making them
14348                variadic.  */
14349             if (len > 0
14350                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14351               parm_variadic_p = 1;
14352             
14353             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14354               return 1;
14355
14356              for (i = 0; i < len - parm_variadic_p; ++i)
14357               {
14358                 if (unify (tparms, targs,
14359                            TREE_VEC_ELT (parmvec, i),
14360                            TREE_VEC_ELT (argvec, i),
14361                            UNIFY_ALLOW_NONE))
14362                   return 1;
14363               }
14364
14365             if (parm_variadic_p
14366                 && unify_pack_expansion (tparms, targs,
14367                                          parmvec, argvec,
14368                                          UNIFY_ALLOW_NONE,
14369                                          /*call_args_p=*/false,
14370                                          /*subr=*/false))
14371               return 1;
14372           }
14373           arg = TYPE_TI_TEMPLATE (arg);
14374
14375           /* Fall through to deduce template name.  */
14376         }
14377
14378       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14379           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14380         {
14381           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14382
14383           /* Simple cases: Value already set, does match or doesn't.  */
14384           if (targ != NULL_TREE && template_args_equal (targ, arg))
14385             return 0;
14386           else if (targ)
14387             return 1;
14388         }
14389       else
14390         {
14391           /* If PARM is `const T' and ARG is only `int', we don't have
14392              a match unless we are allowing additional qualification.
14393              If ARG is `const int' and PARM is just `T' that's OK;
14394              that binds `const int' to `T'.  */
14395           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14396                                          arg, parm))
14397             return 1;
14398
14399           /* Consider the case where ARG is `const volatile int' and
14400              PARM is `const T'.  Then, T should be `volatile int'.  */
14401           arg = cp_build_qualified_type_real
14402             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14403           if (arg == error_mark_node)
14404             return 1;
14405
14406           /* Simple cases: Value already set, does match or doesn't.  */
14407           if (targ != NULL_TREE && same_type_p (targ, arg))
14408             return 0;
14409           else if (targ)
14410             return 1;
14411
14412           /* Make sure that ARG is not a variable-sized array.  (Note
14413              that were talking about variable-sized arrays (like
14414              `int[n]'), rather than arrays of unknown size (like
14415              `int[]').)  We'll get very confused by such a type since
14416              the bound of the array will not be computable in an
14417              instantiation.  Besides, such types are not allowed in
14418              ISO C++, so we can do as we please here.  */
14419           if (variably_modified_type_p (arg, NULL_TREE))
14420             return 1;
14421
14422           /* Strip typedefs as in convert_template_argument.  */
14423           arg = strip_typedefs (arg);
14424         }
14425
14426       /* If ARG is a parameter pack or an expansion, we cannot unify
14427          against it unless PARM is also a parameter pack.  */
14428       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14429           && !template_parameter_pack_p (parm))
14430         return 1;
14431
14432       /* If the argument deduction results is a METHOD_TYPE,
14433          then there is a problem.
14434          METHOD_TYPE doesn't map to any real C++ type the result of
14435          the deduction can not be of that type.  */
14436       if (TREE_CODE (arg) == METHOD_TYPE)
14437         return 1;
14438
14439       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14440       return 0;
14441
14442     case TEMPLATE_PARM_INDEX:
14443       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14444       if (tparm == error_mark_node)
14445         return 1;
14446
14447       if (TEMPLATE_PARM_LEVEL (parm)
14448           != template_decl_level (tparm))
14449         /* The PARM is not one we're trying to unify.  Just check
14450            to see if it matches ARG.  */
14451         return !(TREE_CODE (arg) == TREE_CODE (parm)
14452                  && cp_tree_equal (parm, arg));
14453
14454       idx = TEMPLATE_PARM_IDX (parm);
14455       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14456
14457       if (targ)
14458         return !cp_tree_equal (targ, arg);
14459
14460       /* [temp.deduct.type] If, in the declaration of a function template
14461          with a non-type template-parameter, the non-type
14462          template-parameter is used in an expression in the function
14463          parameter-list and, if the corresponding template-argument is
14464          deduced, the template-argument type shall match the type of the
14465          template-parameter exactly, except that a template-argument
14466          deduced from an array bound may be of any integral type.
14467          The non-type parameter might use already deduced type parameters.  */
14468       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14469       if (!TREE_TYPE (arg))
14470         /* Template-parameter dependent expression.  Just accept it for now.
14471            It will later be processed in convert_template_argument.  */
14472         ;
14473       else if (same_type_p (TREE_TYPE (arg), tparm))
14474         /* OK */;
14475       else if ((strict & UNIFY_ALLOW_INTEGER)
14476                && (TREE_CODE (tparm) == INTEGER_TYPE
14477                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14478         /* Convert the ARG to the type of PARM; the deduced non-type
14479            template argument must exactly match the types of the
14480            corresponding parameter.  */
14481         arg = fold (build_nop (tparm, arg));
14482       else if (uses_template_parms (tparm))
14483         /* We haven't deduced the type of this parameter yet.  Try again
14484            later.  */
14485         return 0;
14486       else
14487         return 1;
14488
14489       /* If ARG is a parameter pack or an expansion, we cannot unify
14490          against it unless PARM is also a parameter pack.  */
14491       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14492           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14493         return 1;
14494
14495       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14496       return 0;
14497
14498     case PTRMEM_CST:
14499      {
14500         /* A pointer-to-member constant can be unified only with
14501          another constant.  */
14502       if (TREE_CODE (arg) != PTRMEM_CST)
14503         return 1;
14504
14505       /* Just unify the class member. It would be useless (and possibly
14506          wrong, depending on the strict flags) to unify also
14507          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14508          arg refer to the same variable, even if through different
14509          classes. For instance:
14510
14511          struct A { int x; };
14512          struct B : A { };
14513
14514          Unification of &A::x and &B::x must succeed.  */
14515       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14516                     PTRMEM_CST_MEMBER (arg), strict);
14517      }
14518
14519     case POINTER_TYPE:
14520       {
14521         if (TREE_CODE (arg) != POINTER_TYPE)
14522           return 1;
14523
14524         /* [temp.deduct.call]
14525
14526            A can be another pointer or pointer to member type that can
14527            be converted to the deduced A via a qualification
14528            conversion (_conv.qual_).
14529
14530            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14531            This will allow for additional cv-qualification of the
14532            pointed-to types if appropriate.  */
14533
14534         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14535           /* The derived-to-base conversion only persists through one
14536              level of pointers.  */
14537           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14538
14539         return unify (tparms, targs, TREE_TYPE (parm),
14540                       TREE_TYPE (arg), strict);
14541       }
14542
14543     case REFERENCE_TYPE:
14544       if (TREE_CODE (arg) != REFERENCE_TYPE)
14545         return 1;
14546       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14547                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14548
14549     case ARRAY_TYPE:
14550       if (TREE_CODE (arg) != ARRAY_TYPE)
14551         return 1;
14552       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14553           != (TYPE_DOMAIN (arg) == NULL_TREE))
14554         return 1;
14555       if (TYPE_DOMAIN (parm) != NULL_TREE)
14556         {
14557           tree parm_max;
14558           tree arg_max;
14559           bool parm_cst;
14560           bool arg_cst;
14561
14562           /* Our representation of array types uses "N - 1" as the
14563              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14564              not an integer constant.  We cannot unify arbitrarily
14565              complex expressions, so we eliminate the MINUS_EXPRs
14566              here.  */
14567           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14568           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14569           if (!parm_cst)
14570             {
14571               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14572               parm_max = TREE_OPERAND (parm_max, 0);
14573             }
14574           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14575           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14576           if (!arg_cst)
14577             {
14578               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14579                  trying to unify the type of a variable with the type
14580                  of a template parameter.  For example:
14581
14582                    template <unsigned int N>
14583                    void f (char (&) [N]);
14584                    int g(); 
14585                    void h(int i) {
14586                      char a[g(i)];
14587                      f(a); 
14588                    }
14589
14590                 Here, the type of the ARG will be "int [g(i)]", and
14591                 may be a SAVE_EXPR, etc.  */
14592               if (TREE_CODE (arg_max) != MINUS_EXPR)
14593                 return 1;
14594               arg_max = TREE_OPERAND (arg_max, 0);
14595             }
14596
14597           /* If only one of the bounds used a MINUS_EXPR, compensate
14598              by adding one to the other bound.  */
14599           if (parm_cst && !arg_cst)
14600             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14601                                     integer_type_node,
14602                                     parm_max,
14603                                     integer_one_node);
14604           else if (arg_cst && !parm_cst)
14605             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14606                                    integer_type_node,
14607                                    arg_max,
14608                                    integer_one_node);
14609
14610           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14611             return 1;
14612         }
14613       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14614                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14615
14616     case REAL_TYPE:
14617     case COMPLEX_TYPE:
14618     case VECTOR_TYPE:
14619     case INTEGER_TYPE:
14620     case BOOLEAN_TYPE:
14621     case ENUMERAL_TYPE:
14622     case VOID_TYPE:
14623       if (TREE_CODE (arg) != TREE_CODE (parm))
14624         return 1;
14625
14626       /* We have already checked cv-qualification at the top of the
14627          function.  */
14628       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14629         return 1;
14630
14631       /* As far as unification is concerned, this wins.  Later checks
14632          will invalidate it if necessary.  */
14633       return 0;
14634
14635       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14636       /* Type INTEGER_CST can come from ordinary constant template args.  */
14637     case INTEGER_CST:
14638       while (TREE_CODE (arg) == NOP_EXPR)
14639         arg = TREE_OPERAND (arg, 0);
14640
14641       if (TREE_CODE (arg) != INTEGER_CST)
14642         return 1;
14643       return !tree_int_cst_equal (parm, arg);
14644
14645     case TREE_VEC:
14646       {
14647         int i;
14648         if (TREE_CODE (arg) != TREE_VEC)
14649           return 1;
14650         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14651           return 1;
14652         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14653           if (unify (tparms, targs,
14654                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14655                      UNIFY_ALLOW_NONE))
14656             return 1;
14657         return 0;
14658       }
14659
14660     case RECORD_TYPE:
14661     case UNION_TYPE:
14662       if (TREE_CODE (arg) != TREE_CODE (parm))
14663         return 1;
14664
14665       if (TYPE_PTRMEMFUNC_P (parm))
14666         {
14667           if (!TYPE_PTRMEMFUNC_P (arg))
14668             return 1;
14669
14670           return unify (tparms, targs,
14671                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14672                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14673                         strict);
14674         }
14675
14676       if (CLASSTYPE_TEMPLATE_INFO (parm))
14677         {
14678           tree t = NULL_TREE;
14679
14680           if (strict_in & UNIFY_ALLOW_DERIVED)
14681             {
14682               /* First, we try to unify the PARM and ARG directly.  */
14683               t = try_class_unification (tparms, targs,
14684                                          parm, arg);
14685
14686               if (!t)
14687                 {
14688                   /* Fallback to the special case allowed in
14689                      [temp.deduct.call]:
14690
14691                        If P is a class, and P has the form
14692                        template-id, then A can be a derived class of
14693                        the deduced A.  Likewise, if P is a pointer to
14694                        a class of the form template-id, A can be a
14695                        pointer to a derived class pointed to by the
14696                        deduced A.  */
14697                   t = get_template_base (tparms, targs, parm, arg);
14698
14699                   if (!t)
14700                     return 1;
14701                 }
14702             }
14703           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14704                    && (CLASSTYPE_TI_TEMPLATE (parm)
14705                        == CLASSTYPE_TI_TEMPLATE (arg)))
14706             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14707                Then, we should unify `int' and `U'.  */
14708             t = arg;
14709           else
14710             /* There's no chance of unification succeeding.  */
14711             return 1;
14712
14713           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14714                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14715         }
14716       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14717         return 1;
14718       return 0;
14719
14720     case METHOD_TYPE:
14721     case FUNCTION_TYPE:
14722       {
14723         unsigned int nargs;
14724         tree *args;
14725         tree a;
14726         unsigned int i;
14727
14728         if (TREE_CODE (arg) != TREE_CODE (parm))
14729           return 1;
14730
14731         /* CV qualifications for methods can never be deduced, they must
14732            match exactly.  We need to check them explicitly here,
14733            because type_unification_real treats them as any other
14734            cv-qualified parameter.  */
14735         if (TREE_CODE (parm) == METHOD_TYPE
14736             && (!check_cv_quals_for_unify
14737                 (UNIFY_ALLOW_NONE,
14738                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14739                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14740           return 1;
14741
14742         if (unify (tparms, targs, TREE_TYPE (parm),
14743                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14744           return 1;
14745
14746         nargs = list_length (TYPE_ARG_TYPES (arg));
14747         args = XALLOCAVEC (tree, nargs);
14748         for (a = TYPE_ARG_TYPES (arg), i = 0;
14749              a != NULL_TREE && a != void_list_node;
14750              a = TREE_CHAIN (a), ++i)
14751           args[i] = TREE_VALUE (a);
14752         nargs = i;
14753
14754         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14755                                       args, nargs, 1, DEDUCE_EXACT,
14756                                       LOOKUP_NORMAL);
14757       }
14758
14759     case OFFSET_TYPE:
14760       /* Unify a pointer to member with a pointer to member function, which
14761          deduces the type of the member as a function type. */
14762       if (TYPE_PTRMEMFUNC_P (arg))
14763         {
14764           tree method_type;
14765           tree fntype;
14766           cp_cv_quals cv_quals;
14767
14768           /* Check top-level cv qualifiers */
14769           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14770             return 1;
14771
14772           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14773                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14774             return 1;
14775
14776           /* Determine the type of the function we are unifying against. */
14777           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14778           fntype =
14779             build_function_type (TREE_TYPE (method_type),
14780                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14781
14782           /* Extract the cv-qualifiers of the member function from the
14783              implicit object parameter and place them on the function
14784              type to be restored later. */
14785           cv_quals =
14786             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14787           fntype = build_qualified_type (fntype, cv_quals);
14788           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14789         }
14790
14791       if (TREE_CODE (arg) != OFFSET_TYPE)
14792         return 1;
14793       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14794                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14795         return 1;
14796       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14797                     strict);
14798
14799     case CONST_DECL:
14800       if (DECL_TEMPLATE_PARM_P (parm))
14801         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14802       if (arg != integral_constant_value (parm))
14803         return 1;
14804       return 0;
14805
14806     case FIELD_DECL:
14807     case TEMPLATE_DECL:
14808       /* Matched cases are handled by the ARG == PARM test above.  */
14809       return 1;
14810
14811     case TYPE_ARGUMENT_PACK:
14812     case NONTYPE_ARGUMENT_PACK:
14813       {
14814         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14815         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14816         int i, len = TREE_VEC_LENGTH (packed_parms);
14817         int argslen = TREE_VEC_LENGTH (packed_args);
14818         int parm_variadic_p = 0;
14819
14820         for (i = 0; i < len; ++i)
14821           {
14822             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14823               {
14824                 if (i == len - 1)
14825                   /* We can unify against something with a trailing
14826                      parameter pack.  */
14827                   parm_variadic_p = 1;
14828                 else
14829                   /* Since there is something following the pack
14830                      expansion, we cannot unify this template argument
14831                      list.  */
14832                   return 0;
14833               }
14834           }
14835           
14836
14837         /* If we don't have enough arguments to satisfy the parameters
14838            (not counting the pack expression at the end), or we have
14839            too many arguments for a parameter list that doesn't end in
14840            a pack expression, we can't unify.  */
14841         if (argslen < (len - parm_variadic_p)
14842             || (argslen > len && !parm_variadic_p))
14843           return 1;
14844
14845         /* Unify all of the parameters that precede the (optional)
14846            pack expression.  */
14847         for (i = 0; i < len - parm_variadic_p; ++i)
14848           {
14849             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14850                        TREE_VEC_ELT (packed_args, i), strict))
14851               return 1;
14852           }
14853
14854         if (parm_variadic_p)
14855           return unify_pack_expansion (tparms, targs, 
14856                                        packed_parms, packed_args,
14857                                        strict, /*call_args_p=*/false,
14858                                        /*subr=*/false);
14859         return 0;
14860       }
14861
14862       break;
14863
14864     case TYPEOF_TYPE:
14865     case DECLTYPE_TYPE:
14866       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14867          nodes.  */
14868       return 0;
14869
14870     case ERROR_MARK:
14871       /* Unification fails if we hit an error node.  */
14872       return 1;
14873
14874     default:
14875       gcc_assert (EXPR_P (parm));
14876
14877       /* We must be looking at an expression.  This can happen with
14878          something like:
14879
14880            template <int I>
14881            void foo(S<I>, S<I + 2>);
14882
14883          This is a "nondeduced context":
14884
14885            [deduct.type]
14886
14887            The nondeduced contexts are:
14888
14889            --A type that is a template-id in which one or more of
14890              the template-arguments is an expression that references
14891              a template-parameter.
14892
14893          In these cases, we assume deduction succeeded, but don't
14894          actually infer any unifications.  */
14895
14896       if (!uses_template_parms (parm)
14897           && !template_args_equal (parm, arg))
14898         return 1;
14899       else
14900         return 0;
14901     }
14902 }
14903 \f
14904 /* Note that DECL can be defined in this translation unit, if
14905    required.  */
14906
14907 static void
14908 mark_definable (tree decl)
14909 {
14910   tree clone;
14911   DECL_NOT_REALLY_EXTERN (decl) = 1;
14912   FOR_EACH_CLONE (clone, decl)
14913     DECL_NOT_REALLY_EXTERN (clone) = 1;
14914 }
14915
14916 /* Called if RESULT is explicitly instantiated, or is a member of an
14917    explicitly instantiated class.  */
14918
14919 void
14920 mark_decl_instantiated (tree result, int extern_p)
14921 {
14922   SET_DECL_EXPLICIT_INSTANTIATION (result);
14923
14924   /* If this entity has already been written out, it's too late to
14925      make any modifications.  */
14926   if (TREE_ASM_WRITTEN (result))
14927     return;
14928
14929   if (TREE_CODE (result) != FUNCTION_DECL)
14930     /* The TREE_PUBLIC flag for function declarations will have been
14931        set correctly by tsubst.  */
14932     TREE_PUBLIC (result) = 1;
14933
14934   /* This might have been set by an earlier implicit instantiation.  */
14935   DECL_COMDAT (result) = 0;
14936
14937   if (extern_p)
14938     DECL_NOT_REALLY_EXTERN (result) = 0;
14939   else
14940     {
14941       mark_definable (result);
14942       /* Always make artificials weak.  */
14943       if (DECL_ARTIFICIAL (result) && flag_weak)
14944         comdat_linkage (result);
14945       /* For WIN32 we also want to put explicit instantiations in
14946          linkonce sections.  */
14947       else if (TREE_PUBLIC (result))
14948         maybe_make_one_only (result);
14949     }
14950
14951   /* If EXTERN_P, then this function will not be emitted -- unless
14952      followed by an explicit instantiation, at which point its linkage
14953      will be adjusted.  If !EXTERN_P, then this function will be
14954      emitted here.  In neither circumstance do we want
14955      import_export_decl to adjust the linkage.  */
14956   DECL_INTERFACE_KNOWN (result) = 1;
14957 }
14958
14959 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
14960    important template arguments.  If any are missing, we check whether
14961    they're important by using error_mark_node for substituting into any
14962    args that were used for partial ordering (the ones between ARGS and END)
14963    and seeing if it bubbles up.  */
14964
14965 static bool
14966 check_undeduced_parms (tree targs, tree args, tree end)
14967 {
14968   bool found = false;
14969   int i;
14970   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
14971     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
14972       {
14973         found = true;
14974         TREE_VEC_ELT (targs, i) = error_mark_node;
14975       }
14976   if (found)
14977     {
14978       for (; args != end; args = TREE_CHAIN (args))
14979         {
14980           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
14981           if (substed == error_mark_node)
14982             return true;
14983         }
14984     }
14985   return false;
14986 }
14987
14988 /* Given two function templates PAT1 and PAT2, return:
14989
14990    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14991    -1 if PAT2 is more specialized than PAT1.
14992    0 if neither is more specialized.
14993
14994    LEN indicates the number of parameters we should consider
14995    (defaulted parameters should not be considered).
14996
14997    The 1998 std underspecified function template partial ordering, and
14998    DR214 addresses the issue.  We take pairs of arguments, one from
14999    each of the templates, and deduce them against each other.  One of
15000    the templates will be more specialized if all the *other*
15001    template's arguments deduce against its arguments and at least one
15002    of its arguments *does* *not* deduce against the other template's
15003    corresponding argument.  Deduction is done as for class templates.
15004    The arguments used in deduction have reference and top level cv
15005    qualifiers removed.  Iff both arguments were originally reference
15006    types *and* deduction succeeds in both directions, the template
15007    with the more cv-qualified argument wins for that pairing (if
15008    neither is more cv-qualified, they both are equal).  Unlike regular
15009    deduction, after all the arguments have been deduced in this way,
15010    we do *not* verify the deduced template argument values can be
15011    substituted into non-deduced contexts.
15012
15013    The logic can be a bit confusing here, because we look at deduce1 and
15014    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15015    can find template arguments for pat1 to make arg1 look like arg2, that
15016    means that arg2 is at least as specialized as arg1.  */
15017
15018 int
15019 more_specialized_fn (tree pat1, tree pat2, int len)
15020 {
15021   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15022   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15023   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15024   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15025   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15026   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15027   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15028   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15029   tree origs1, origs2;
15030   bool lose1 = false;
15031   bool lose2 = false;
15032
15033   /* Remove the this parameter from non-static member functions.  If
15034      one is a non-static member function and the other is not a static
15035      member function, remove the first parameter from that function
15036      also.  This situation occurs for operator functions where we
15037      locate both a member function (with this pointer) and non-member
15038      operator (with explicit first operand).  */
15039   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15040     {
15041       len--; /* LEN is the number of significant arguments for DECL1 */
15042       args1 = TREE_CHAIN (args1);
15043       if (!DECL_STATIC_FUNCTION_P (decl2))
15044         args2 = TREE_CHAIN (args2);
15045     }
15046   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15047     {
15048       args2 = TREE_CHAIN (args2);
15049       if (!DECL_STATIC_FUNCTION_P (decl1))
15050         {
15051           len--;
15052           args1 = TREE_CHAIN (args1);
15053         }
15054     }
15055
15056   /* If only one is a conversion operator, they are unordered.  */
15057   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15058     return 0;
15059
15060   /* Consider the return type for a conversion function */
15061   if (DECL_CONV_FN_P (decl1))
15062     {
15063       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15064       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15065       len++;
15066     }
15067
15068   processing_template_decl++;
15069
15070   origs1 = args1;
15071   origs2 = args2;
15072
15073   while (len--
15074          /* Stop when an ellipsis is seen.  */
15075          && args1 != NULL_TREE && args2 != NULL_TREE)
15076     {
15077       tree arg1 = TREE_VALUE (args1);
15078       tree arg2 = TREE_VALUE (args2);
15079       int deduce1, deduce2;
15080       int quals1 = -1;
15081       int quals2 = -1;
15082
15083       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15084           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15085         {
15086           /* When both arguments are pack expansions, we need only
15087              unify the patterns themselves.  */
15088           arg1 = PACK_EXPANSION_PATTERN (arg1);
15089           arg2 = PACK_EXPANSION_PATTERN (arg2);
15090
15091           /* This is the last comparison we need to do.  */
15092           len = 0;
15093         }
15094
15095       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15096         {
15097           arg1 = TREE_TYPE (arg1);
15098           quals1 = cp_type_quals (arg1);
15099         }
15100
15101       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15102         {
15103           arg2 = TREE_TYPE (arg2);
15104           quals2 = cp_type_quals (arg2);
15105         }
15106
15107       if ((quals1 < 0) != (quals2 < 0))
15108         {
15109           /* Only of the args is a reference, see if we should apply
15110              array/function pointer decay to it.  This is not part of
15111              DR214, but is, IMHO, consistent with the deduction rules
15112              for the function call itself, and with our earlier
15113              implementation of the underspecified partial ordering
15114              rules.  (nathan).  */
15115           if (quals1 >= 0)
15116             {
15117               switch (TREE_CODE (arg1))
15118                 {
15119                 case ARRAY_TYPE:
15120                   arg1 = TREE_TYPE (arg1);
15121                   /* FALLTHROUGH. */
15122                 case FUNCTION_TYPE:
15123                   arg1 = build_pointer_type (arg1);
15124                   break;
15125
15126                 default:
15127                   break;
15128                 }
15129             }
15130           else
15131             {
15132               switch (TREE_CODE (arg2))
15133                 {
15134                 case ARRAY_TYPE:
15135                   arg2 = TREE_TYPE (arg2);
15136                   /* FALLTHROUGH. */
15137                 case FUNCTION_TYPE:
15138                   arg2 = build_pointer_type (arg2);
15139                   break;
15140
15141                 default:
15142                   break;
15143                 }
15144             }
15145         }
15146
15147       arg1 = TYPE_MAIN_VARIANT (arg1);
15148       arg2 = TYPE_MAIN_VARIANT (arg2);
15149
15150       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15151         {
15152           int i, len2 = list_length (args2);
15153           tree parmvec = make_tree_vec (1);
15154           tree argvec = make_tree_vec (len2);
15155           tree ta = args2;
15156
15157           /* Setup the parameter vector, which contains only ARG1.  */
15158           TREE_VEC_ELT (parmvec, 0) = arg1;
15159
15160           /* Setup the argument vector, which contains the remaining
15161              arguments.  */
15162           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15163             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15164
15165           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15166                                            argvec, UNIFY_ALLOW_NONE, 
15167                                            /*call_args_p=*/false, 
15168                                            /*subr=*/0);
15169
15170           /* We cannot deduce in the other direction, because ARG1 is
15171              a pack expansion but ARG2 is not.  */
15172           deduce2 = 0;
15173         }
15174       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15175         {
15176           int i, len1 = list_length (args1);
15177           tree parmvec = make_tree_vec (1);
15178           tree argvec = make_tree_vec (len1);
15179           tree ta = args1;
15180
15181           /* Setup the parameter vector, which contains only ARG1.  */
15182           TREE_VEC_ELT (parmvec, 0) = arg2;
15183
15184           /* Setup the argument vector, which contains the remaining
15185              arguments.  */
15186           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15187             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15188
15189           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15190                                            argvec, UNIFY_ALLOW_NONE, 
15191                                            /*call_args_p=*/false, 
15192                                            /*subr=*/0);
15193
15194           /* We cannot deduce in the other direction, because ARG2 is
15195              a pack expansion but ARG1 is not.*/
15196           deduce1 = 0;
15197         }
15198
15199       else
15200         {
15201           /* The normal case, where neither argument is a pack
15202              expansion.  */
15203           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15204           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15205         }
15206
15207       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15208          arg2, then arg2 is not as specialized as arg1.  */
15209       if (!deduce1)
15210         lose2 = true;
15211       if (!deduce2)
15212         lose1 = true;
15213
15214       /* "If, for a given type, deduction succeeds in both directions
15215          (i.e., the types are identical after the transformations above)
15216          and if the type from the argument template is more cv-qualified
15217          than the type from the parameter template (as described above)
15218          that type is considered to be more specialized than the other. If
15219          neither type is more cv-qualified than the other then neither type
15220          is more specialized than the other."
15221
15222          We check same_type_p explicitly because deduction can also succeed
15223          in both directions when there is a nondeduced context.  */
15224       if (deduce1 && deduce2
15225           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15226           && same_type_p (arg1, arg2))
15227         {
15228           if ((quals1 & quals2) == quals2)
15229             lose2 = true;
15230           if ((quals1 & quals2) == quals1)
15231             lose1 = true;
15232         }
15233
15234       if (lose1 && lose2)
15235         /* We've failed to deduce something in either direction.
15236            These must be unordered.  */
15237         break;
15238
15239       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15240           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15241         /* We have already processed all of the arguments in our
15242            handing of the pack expansion type.  */
15243         len = 0;
15244
15245       args1 = TREE_CHAIN (args1);
15246       args2 = TREE_CHAIN (args2);
15247     }
15248
15249   /* "In most cases, all template parameters must have values in order for
15250      deduction to succeed, but for partial ordering purposes a template
15251      parameter may remain without a value provided it is not used in the
15252      types being used for partial ordering."
15253
15254      Thus, if we are missing any of the targs1 we need to substitute into
15255      origs1, then pat2 is not as specialized as pat1.  This can happen when
15256      there is a nondeduced context.  */
15257   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15258     lose2 = true;
15259   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15260     lose1 = true;
15261
15262   processing_template_decl--;
15263
15264   /* All things being equal, if the next argument is a pack expansion
15265      for one function but not for the other, prefer the
15266      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15267   if (lose1 == lose2
15268       && args1 && TREE_VALUE (args1)
15269       && args2 && TREE_VALUE (args2))
15270     {
15271       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15272       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15273     }
15274
15275   if (lose1 == lose2)
15276     return 0;
15277   else if (!lose1)
15278     return 1;
15279   else
15280     return -1;
15281 }
15282
15283 /* Determine which of two partial specializations is more specialized.
15284
15285    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15286    to the first partial specialization.  The TREE_VALUE is the
15287    innermost set of template parameters for the partial
15288    specialization.  PAT2 is similar, but for the second template.
15289
15290    Return 1 if the first partial specialization is more specialized;
15291    -1 if the second is more specialized; 0 if neither is more
15292    specialized.
15293
15294    See [temp.class.order] for information about determining which of
15295    two templates is more specialized.  */
15296
15297 static int
15298 more_specialized_class (tree pat1, tree pat2)
15299 {
15300   tree targs;
15301   tree tmpl1, tmpl2;
15302   int winner = 0;
15303   bool any_deductions = false;
15304
15305   tmpl1 = TREE_TYPE (pat1);
15306   tmpl2 = TREE_TYPE (pat2);
15307
15308   /* Just like what happens for functions, if we are ordering between
15309      different class template specializations, we may encounter dependent
15310      types in the arguments, and we need our dependency check functions
15311      to behave correctly.  */
15312   ++processing_template_decl;
15313   targs = get_class_bindings (TREE_VALUE (pat1),
15314                               CLASSTYPE_TI_ARGS (tmpl1),
15315                               CLASSTYPE_TI_ARGS (tmpl2));
15316   if (targs)
15317     {
15318       --winner;
15319       any_deductions = true;
15320     }
15321
15322   targs = get_class_bindings (TREE_VALUE (pat2),
15323                               CLASSTYPE_TI_ARGS (tmpl2),
15324                               CLASSTYPE_TI_ARGS (tmpl1));
15325   if (targs)
15326     {
15327       ++winner;
15328       any_deductions = true;
15329     }
15330   --processing_template_decl;
15331
15332   /* In the case of a tie where at least one of the class templates
15333      has a parameter pack at the end, the template with the most
15334      non-packed parameters wins.  */
15335   if (winner == 0
15336       && any_deductions
15337       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15338           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15339     {
15340       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15341       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15342       int len1 = TREE_VEC_LENGTH (args1);
15343       int len2 = TREE_VEC_LENGTH (args2);
15344
15345       /* We don't count the pack expansion at the end.  */
15346       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15347         --len1;
15348       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15349         --len2;
15350
15351       if (len1 > len2)
15352         return 1;
15353       else if (len1 < len2)
15354         return -1;
15355     }
15356
15357   return winner;
15358 }
15359
15360 /* Return the template arguments that will produce the function signature
15361    DECL from the function template FN, with the explicit template
15362    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15363    also match.  Return NULL_TREE if no satisfactory arguments could be
15364    found.  */
15365
15366 static tree
15367 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15368 {
15369   int ntparms = DECL_NTPARMS (fn);
15370   tree targs = make_tree_vec (ntparms);
15371   tree decl_type;
15372   tree decl_arg_types;
15373   tree *args;
15374   unsigned int nargs, ix;
15375   tree arg;
15376
15377   /* Substitute the explicit template arguments into the type of DECL.
15378      The call to fn_type_unification will handle substitution into the
15379      FN.  */
15380   decl_type = TREE_TYPE (decl);
15381   if (explicit_args && uses_template_parms (decl_type))
15382     {
15383       tree tmpl;
15384       tree converted_args;
15385
15386       if (DECL_TEMPLATE_INFO (decl))
15387         tmpl = DECL_TI_TEMPLATE (decl);
15388       else
15389         /* We can get here for some invalid specializations.  */
15390         return NULL_TREE;
15391
15392       converted_args
15393         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15394                                  explicit_args, NULL_TREE,
15395                                  tf_none,
15396                                  /*require_all_args=*/false,
15397                                  /*use_default_args=*/false);
15398       if (converted_args == error_mark_node)
15399         return NULL_TREE;
15400
15401       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15402       if (decl_type == error_mark_node)
15403         return NULL_TREE;
15404     }
15405
15406   /* Never do unification on the 'this' parameter.  */
15407   decl_arg_types = skip_artificial_parms_for (decl, 
15408                                               TYPE_ARG_TYPES (decl_type));
15409
15410   nargs = list_length (decl_arg_types);
15411   args = XALLOCAVEC (tree, nargs);
15412   for (arg = decl_arg_types, ix = 0;
15413        arg != NULL_TREE && arg != void_list_node;
15414        arg = TREE_CHAIN (arg), ++ix)
15415     args[ix] = TREE_VALUE (arg);
15416
15417   if (fn_type_unification (fn, explicit_args, targs,
15418                            args, ix,
15419                            (check_rettype || DECL_CONV_FN_P (fn)
15420                             ? TREE_TYPE (decl_type) : NULL_TREE),
15421                            DEDUCE_EXACT, LOOKUP_NORMAL))
15422     return NULL_TREE;
15423
15424   return targs;
15425 }
15426
15427 /* Return the innermost template arguments that, when applied to a
15428    template specialization whose innermost template parameters are
15429    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15430    ARGS.
15431
15432    For example, suppose we have:
15433
15434      template <class T, class U> struct S {};
15435      template <class T> struct S<T*, int> {};
15436
15437    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15438    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15439    int}.  The resulting vector will be {double}, indicating that `T'
15440    is bound to `double'.  */
15441
15442 static tree
15443 get_class_bindings (tree tparms, tree spec_args, tree args)
15444 {
15445   int i, ntparms = TREE_VEC_LENGTH (tparms);
15446   tree deduced_args;
15447   tree innermost_deduced_args;
15448
15449   innermost_deduced_args = make_tree_vec (ntparms);
15450   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15451     {
15452       deduced_args = copy_node (args);
15453       SET_TMPL_ARGS_LEVEL (deduced_args,
15454                            TMPL_ARGS_DEPTH (deduced_args),
15455                            innermost_deduced_args);
15456     }
15457   else
15458     deduced_args = innermost_deduced_args;
15459
15460   if (unify (tparms, deduced_args,
15461              INNERMOST_TEMPLATE_ARGS (spec_args),
15462              INNERMOST_TEMPLATE_ARGS (args),
15463              UNIFY_ALLOW_NONE))
15464     return NULL_TREE;
15465
15466   for (i =  0; i < ntparms; ++i)
15467     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15468       return NULL_TREE;
15469
15470   /* Verify that nondeduced template arguments agree with the type
15471      obtained from argument deduction.
15472
15473      For example:
15474
15475        struct A { typedef int X; };
15476        template <class T, class U> struct C {};
15477        template <class T> struct C<T, typename T::X> {};
15478
15479      Then with the instantiation `C<A, int>', we can deduce that
15480      `T' is `A' but unify () does not check whether `typename T::X'
15481      is `int'.  */
15482   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15483   if (spec_args == error_mark_node
15484       /* We only need to check the innermost arguments; the other
15485          arguments will always agree.  */
15486       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15487                               INNERMOST_TEMPLATE_ARGS (args)))
15488     return NULL_TREE;
15489
15490   /* Now that we have bindings for all of the template arguments,
15491      ensure that the arguments deduced for the template template
15492      parameters have compatible template parameter lists.  See the use
15493      of template_template_parm_bindings_ok_p in fn_type_unification
15494      for more information.  */
15495   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15496     return NULL_TREE;
15497
15498   return deduced_args;
15499 }
15500
15501 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15502    Return the TREE_LIST node with the most specialized template, if
15503    any.  If there is no most specialized template, the error_mark_node
15504    is returned.
15505
15506    Note that this function does not look at, or modify, the
15507    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15508    returned is one of the elements of INSTANTIATIONS, callers may
15509    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15510    and retrieve it from the value returned.  */
15511
15512 tree
15513 most_specialized_instantiation (tree templates)
15514 {
15515   tree fn, champ;
15516
15517   ++processing_template_decl;
15518
15519   champ = templates;
15520   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15521     {
15522       int fate = 0;
15523
15524       if (get_bindings (TREE_VALUE (champ),
15525                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15526                         NULL_TREE, /*check_ret=*/false))
15527         fate--;
15528
15529       if (get_bindings (TREE_VALUE (fn),
15530                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15531                         NULL_TREE, /*check_ret=*/false))
15532         fate++;
15533
15534       if (fate == -1)
15535         champ = fn;
15536       else if (!fate)
15537         {
15538           /* Equally specialized, move to next function.  If there
15539              is no next function, nothing's most specialized.  */
15540           fn = TREE_CHAIN (fn);
15541           champ = fn;
15542           if (!fn)
15543             break;
15544         }
15545     }
15546
15547   if (champ)
15548     /* Now verify that champ is better than everything earlier in the
15549        instantiation list.  */
15550     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15551       if (get_bindings (TREE_VALUE (champ),
15552                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15553                         NULL_TREE, /*check_ret=*/false)
15554           || !get_bindings (TREE_VALUE (fn),
15555                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15556                             NULL_TREE, /*check_ret=*/false))
15557         {
15558           champ = NULL_TREE;
15559           break;
15560         }
15561
15562   processing_template_decl--;
15563
15564   if (!champ)
15565     return error_mark_node;
15566
15567   return champ;
15568 }
15569
15570 /* If DECL is a specialization of some template, return the most
15571    general such template.  Otherwise, returns NULL_TREE.
15572
15573    For example, given:
15574
15575      template <class T> struct S { template <class U> void f(U); };
15576
15577    if TMPL is `template <class U> void S<int>::f(U)' this will return
15578    the full template.  This function will not trace past partial
15579    specializations, however.  For example, given in addition:
15580
15581      template <class T> struct S<T*> { template <class U> void f(U); };
15582
15583    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15584    `template <class T> template <class U> S<T*>::f(U)'.  */
15585
15586 tree
15587 most_general_template (tree decl)
15588 {
15589   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15590      an immediate specialization.  */
15591   if (TREE_CODE (decl) == FUNCTION_DECL)
15592     {
15593       if (DECL_TEMPLATE_INFO (decl)) {
15594         decl = DECL_TI_TEMPLATE (decl);
15595
15596         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15597            template friend.  */
15598         if (TREE_CODE (decl) != TEMPLATE_DECL)
15599           return NULL_TREE;
15600       } else
15601         return NULL_TREE;
15602     }
15603
15604   /* Look for more and more general templates.  */
15605   while (DECL_TEMPLATE_INFO (decl))
15606     {
15607       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15608          (See cp-tree.h for details.)  */
15609       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15610         break;
15611
15612       if (CLASS_TYPE_P (TREE_TYPE (decl))
15613           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15614         break;
15615
15616       /* Stop if we run into an explicitly specialized class template.  */
15617       if (!DECL_NAMESPACE_SCOPE_P (decl)
15618           && DECL_CONTEXT (decl)
15619           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15620         break;
15621
15622       decl = DECL_TI_TEMPLATE (decl);
15623     }
15624
15625   return decl;
15626 }
15627
15628 /* Return the most specialized of the class template partial
15629    specializations of TMPL which can produce TYPE, a specialization of
15630    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15631    a _TYPE node corresponding to the partial specialization, while the
15632    TREE_PURPOSE is the set of template arguments that must be
15633    substituted into the TREE_TYPE in order to generate TYPE.
15634
15635    If the choice of partial specialization is ambiguous, a diagnostic
15636    is issued, and the error_mark_node is returned.  If there are no
15637    partial specializations of TMPL matching TYPE, then NULL_TREE is
15638    returned.  */
15639
15640 static tree
15641 most_specialized_class (tree type, tree tmpl)
15642 {
15643   tree list = NULL_TREE;
15644   tree t;
15645   tree champ;
15646   int fate;
15647   bool ambiguous_p;
15648   tree args;
15649   tree outer_args = NULL_TREE;
15650
15651   tmpl = most_general_template (tmpl);
15652   args = CLASSTYPE_TI_ARGS (type);
15653
15654   /* For determining which partial specialization to use, only the
15655      innermost args are interesting.  */
15656   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15657     {
15658       outer_args = strip_innermost_template_args (args, 1);
15659       args = INNERMOST_TEMPLATE_ARGS (args);
15660     }
15661
15662   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15663     {
15664       tree partial_spec_args;
15665       tree spec_args;
15666       tree parms = TREE_VALUE (t);
15667
15668       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15669       if (outer_args)
15670         {
15671           int i;
15672
15673           ++processing_template_decl;
15674
15675           /* Discard the outer levels of args, and then substitute in the
15676              template args from the enclosing class.  */
15677           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15678           partial_spec_args = tsubst_template_args
15679             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15680
15681           /* PARMS already refers to just the innermost parms, but the
15682              template parms in partial_spec_args had their levels lowered
15683              by tsubst, so we need to do the same for the parm list.  We
15684              can't just tsubst the TREE_VEC itself, as tsubst wants to
15685              treat a TREE_VEC as an argument vector.  */
15686           parms = copy_node (parms);
15687           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15688             TREE_VEC_ELT (parms, i) =
15689               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15690
15691           --processing_template_decl;
15692         }
15693       spec_args = get_class_bindings (parms,
15694                                       partial_spec_args,
15695                                       args);
15696       if (spec_args)
15697         {
15698           if (outer_args)
15699             spec_args = add_to_template_args (outer_args, spec_args);
15700           list = tree_cons (spec_args, TREE_VALUE (t), list);
15701           TREE_TYPE (list) = TREE_TYPE (t);
15702         }
15703     }
15704
15705   if (! list)
15706     return NULL_TREE;
15707
15708   ambiguous_p = false;
15709   t = list;
15710   champ = t;
15711   t = TREE_CHAIN (t);
15712   for (; t; t = TREE_CHAIN (t))
15713     {
15714       fate = more_specialized_class (champ, t);
15715       if (fate == 1)
15716         ;
15717       else
15718         {
15719           if (fate == 0)
15720             {
15721               t = TREE_CHAIN (t);
15722               if (! t)
15723                 {
15724                   ambiguous_p = true;
15725                   break;
15726                 }
15727             }
15728           champ = t;
15729         }
15730     }
15731
15732   if (!ambiguous_p)
15733     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15734       {
15735         fate = more_specialized_class (champ, t);
15736         if (fate != 1)
15737           {
15738             ambiguous_p = true;
15739             break;
15740           }
15741       }
15742
15743   if (ambiguous_p)
15744     {
15745       const char *str = "candidates are:";
15746       error ("ambiguous class template instantiation for %q#T", type);
15747       for (t = list; t; t = TREE_CHAIN (t))
15748         {
15749           error ("%s %+#T", str, TREE_TYPE (t));
15750           str = "               ";
15751         }
15752       return error_mark_node;
15753     }
15754
15755   return champ;
15756 }
15757
15758 /* Explicitly instantiate DECL.  */
15759
15760 void
15761 do_decl_instantiation (tree decl, tree storage)
15762 {
15763   tree result = NULL_TREE;
15764   int extern_p = 0;
15765
15766   if (!decl || decl == error_mark_node)
15767     /* An error occurred, for which grokdeclarator has already issued
15768        an appropriate message.  */
15769     return;
15770   else if (! DECL_LANG_SPECIFIC (decl))
15771     {
15772       error ("explicit instantiation of non-template %q#D", decl);
15773       return;
15774     }
15775   else if (TREE_CODE (decl) == VAR_DECL)
15776     {
15777       /* There is an asymmetry here in the way VAR_DECLs and
15778          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15779          the latter, the DECL we get back will be marked as a
15780          template instantiation, and the appropriate
15781          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15782          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15783          should handle VAR_DECLs as it currently handles
15784          FUNCTION_DECLs.  */
15785       if (!DECL_CLASS_SCOPE_P (decl))
15786         {
15787           error ("%qD is not a static data member of a class template", decl);
15788           return;
15789         }
15790       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15791       if (!result || TREE_CODE (result) != VAR_DECL)
15792         {
15793           error ("no matching template for %qD found", decl);
15794           return;
15795         }
15796       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15797         {
15798           error ("type %qT for explicit instantiation %qD does not match "
15799                  "declared type %qT", TREE_TYPE (result), decl,
15800                  TREE_TYPE (decl));
15801           return;
15802         }
15803     }
15804   else if (TREE_CODE (decl) != FUNCTION_DECL)
15805     {
15806       error ("explicit instantiation of %q#D", decl);
15807       return;
15808     }
15809   else
15810     result = decl;
15811
15812   /* Check for various error cases.  Note that if the explicit
15813      instantiation is valid the RESULT will currently be marked as an
15814      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15815      until we get here.  */
15816
15817   if (DECL_TEMPLATE_SPECIALIZATION (result))
15818     {
15819       /* DR 259 [temp.spec].
15820
15821          Both an explicit instantiation and a declaration of an explicit
15822          specialization shall not appear in a program unless the explicit
15823          instantiation follows a declaration of the explicit specialization.
15824
15825          For a given set of template parameters, if an explicit
15826          instantiation of a template appears after a declaration of an
15827          explicit specialization for that template, the explicit
15828          instantiation has no effect.  */
15829       return;
15830     }
15831   else if (DECL_EXPLICIT_INSTANTIATION (result))
15832     {
15833       /* [temp.spec]
15834
15835          No program shall explicitly instantiate any template more
15836          than once.
15837
15838          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15839          the first instantiation was `extern' and the second is not,
15840          and EXTERN_P for the opposite case.  */
15841       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15842         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15843       /* If an "extern" explicit instantiation follows an ordinary
15844          explicit instantiation, the template is instantiated.  */
15845       if (extern_p)
15846         return;
15847     }
15848   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15849     {
15850       error ("no matching template for %qD found", result);
15851       return;
15852     }
15853   else if (!DECL_TEMPLATE_INFO (result))
15854     {
15855       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15856       return;
15857     }
15858
15859   if (storage == NULL_TREE)
15860     ;
15861   else if (storage == ridpointers[(int) RID_EXTERN])
15862     {
15863       if (!in_system_header && (cxx_dialect == cxx98))
15864         pedwarn (input_location, OPT_pedantic, 
15865                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15866                  "instantiations");
15867       extern_p = 1;
15868     }
15869   else
15870     error ("storage class %qD applied to template instantiation", storage);
15871
15872   check_explicit_instantiation_namespace (result);
15873   mark_decl_instantiated (result, extern_p);
15874   if (! extern_p)
15875     instantiate_decl (result, /*defer_ok=*/1,
15876                       /*expl_inst_class_mem_p=*/false);
15877 }
15878
15879 static void
15880 mark_class_instantiated (tree t, int extern_p)
15881 {
15882   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15883   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15884   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15885   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15886   if (! extern_p)
15887     {
15888       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15889       rest_of_type_compilation (t, 1);
15890     }
15891 }
15892
15893 /* Called from do_type_instantiation through binding_table_foreach to
15894    do recursive instantiation for the type bound in ENTRY.  */
15895 static void
15896 bt_instantiate_type_proc (binding_entry entry, void *data)
15897 {
15898   tree storage = *(tree *) data;
15899
15900   if (MAYBE_CLASS_TYPE_P (entry->type)
15901       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15902     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15903 }
15904
15905 /* Called from do_type_instantiation to instantiate a member
15906    (a member function or a static member variable) of an
15907    explicitly instantiated class template.  */
15908 static void
15909 instantiate_class_member (tree decl, int extern_p)
15910 {
15911   mark_decl_instantiated (decl, extern_p);
15912   if (! extern_p)
15913     instantiate_decl (decl, /*defer_ok=*/1,
15914                       /*expl_inst_class_mem_p=*/true);
15915 }
15916
15917 /* Perform an explicit instantiation of template class T.  STORAGE, if
15918    non-null, is the RID for extern, inline or static.  COMPLAIN is
15919    nonzero if this is called from the parser, zero if called recursively,
15920    since the standard is unclear (as detailed below).  */
15921
15922 void
15923 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15924 {
15925   int extern_p = 0;
15926   int nomem_p = 0;
15927   int static_p = 0;
15928   int previous_instantiation_extern_p = 0;
15929
15930   if (TREE_CODE (t) == TYPE_DECL)
15931     t = TREE_TYPE (t);
15932
15933   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15934     {
15935       error ("explicit instantiation of non-template type %qT", t);
15936       return;
15937     }
15938
15939   complete_type (t);
15940
15941   if (!COMPLETE_TYPE_P (t))
15942     {
15943       if (complain & tf_error)
15944         error ("explicit instantiation of %q#T before definition of template",
15945                t);
15946       return;
15947     }
15948
15949   if (storage != NULL_TREE)
15950     {
15951       if (!in_system_header)
15952         {
15953           if (storage == ridpointers[(int) RID_EXTERN])
15954             {
15955               if (cxx_dialect == cxx98)
15956                 pedwarn (input_location, OPT_pedantic, 
15957                          "ISO C++ 1998 forbids the use of %<extern%> on "
15958                          "explicit instantiations");
15959             }
15960           else
15961             pedwarn (input_location, OPT_pedantic, 
15962                      "ISO C++ forbids the use of %qE"
15963                      " on explicit instantiations", storage);
15964         }
15965
15966       if (storage == ridpointers[(int) RID_INLINE])
15967         nomem_p = 1;
15968       else if (storage == ridpointers[(int) RID_EXTERN])
15969         extern_p = 1;
15970       else if (storage == ridpointers[(int) RID_STATIC])
15971         static_p = 1;
15972       else
15973         {
15974           error ("storage class %qD applied to template instantiation",
15975                  storage);
15976           extern_p = 0;
15977         }
15978     }
15979
15980   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15981     {
15982       /* DR 259 [temp.spec].
15983
15984          Both an explicit instantiation and a declaration of an explicit
15985          specialization shall not appear in a program unless the explicit
15986          instantiation follows a declaration of the explicit specialization.
15987
15988          For a given set of template parameters, if an explicit
15989          instantiation of a template appears after a declaration of an
15990          explicit specialization for that template, the explicit
15991          instantiation has no effect.  */
15992       return;
15993     }
15994   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15995     {
15996       /* [temp.spec]
15997
15998          No program shall explicitly instantiate any template more
15999          than once.
16000
16001          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16002          instantiation was `extern'.  If EXTERN_P then the second is.
16003          These cases are OK.  */
16004       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16005
16006       if (!previous_instantiation_extern_p && !extern_p
16007           && (complain & tf_error))
16008         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16009
16010       /* If we've already instantiated the template, just return now.  */
16011       if (!CLASSTYPE_INTERFACE_ONLY (t))
16012         return;
16013     }
16014
16015   check_explicit_instantiation_namespace (TYPE_NAME (t));
16016   mark_class_instantiated (t, extern_p);
16017
16018   if (nomem_p)
16019     return;
16020
16021   {
16022     tree tmp;
16023
16024     /* In contrast to implicit instantiation, where only the
16025        declarations, and not the definitions, of members are
16026        instantiated, we have here:
16027
16028          [temp.explicit]
16029
16030          The explicit instantiation of a class template specialization
16031          implies the instantiation of all of its members not
16032          previously explicitly specialized in the translation unit
16033          containing the explicit instantiation.
16034
16035        Of course, we can't instantiate member template classes, since
16036        we don't have any arguments for them.  Note that the standard
16037        is unclear on whether the instantiation of the members are
16038        *explicit* instantiations or not.  However, the most natural
16039        interpretation is that it should be an explicit instantiation.  */
16040
16041     if (! static_p)
16042       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16043         if (TREE_CODE (tmp) == FUNCTION_DECL
16044             && DECL_TEMPLATE_INSTANTIATION (tmp))
16045           instantiate_class_member (tmp, extern_p);
16046
16047     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16048       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16049         instantiate_class_member (tmp, extern_p);
16050
16051     if (CLASSTYPE_NESTED_UTDS (t))
16052       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16053                              bt_instantiate_type_proc, &storage);
16054   }
16055 }
16056
16057 /* Given a function DECL, which is a specialization of TMPL, modify
16058    DECL to be a re-instantiation of TMPL with the same template
16059    arguments.  TMPL should be the template into which tsubst'ing
16060    should occur for DECL, not the most general template.
16061
16062    One reason for doing this is a scenario like this:
16063
16064      template <class T>
16065      void f(const T&, int i);
16066
16067      void g() { f(3, 7); }
16068
16069      template <class T>
16070      void f(const T& t, const int i) { }
16071
16072    Note that when the template is first instantiated, with
16073    instantiate_template, the resulting DECL will have no name for the
16074    first parameter, and the wrong type for the second.  So, when we go
16075    to instantiate the DECL, we regenerate it.  */
16076
16077 static void
16078 regenerate_decl_from_template (tree decl, tree tmpl)
16079 {
16080   /* The arguments used to instantiate DECL, from the most general
16081      template.  */
16082   tree args;
16083   tree code_pattern;
16084
16085   args = DECL_TI_ARGS (decl);
16086   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16087
16088   /* Make sure that we can see identifiers, and compute access
16089      correctly.  */
16090   push_access_scope (decl);
16091
16092   if (TREE_CODE (decl) == FUNCTION_DECL)
16093     {
16094       tree decl_parm;
16095       tree pattern_parm;
16096       tree specs;
16097       int args_depth;
16098       int parms_depth;
16099
16100       args_depth = TMPL_ARGS_DEPTH (args);
16101       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16102       if (args_depth > parms_depth)
16103         args = get_innermost_template_args (args, parms_depth);
16104
16105       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16106                                               args, tf_error, NULL_TREE);
16107       if (specs)
16108         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16109                                                     specs);
16110
16111       /* Merge parameter declarations.  */
16112       decl_parm = skip_artificial_parms_for (decl,
16113                                              DECL_ARGUMENTS (decl));
16114       pattern_parm
16115         = skip_artificial_parms_for (code_pattern,
16116                                      DECL_ARGUMENTS (code_pattern));
16117       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16118         {
16119           tree parm_type;
16120           tree attributes;
16121           
16122           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16123             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16124           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16125                               NULL_TREE);
16126           parm_type = type_decays_to (parm_type);
16127           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16128             TREE_TYPE (decl_parm) = parm_type;
16129           attributes = DECL_ATTRIBUTES (pattern_parm);
16130           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16131             {
16132               DECL_ATTRIBUTES (decl_parm) = attributes;
16133               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16134             }
16135           decl_parm = TREE_CHAIN (decl_parm);
16136           pattern_parm = TREE_CHAIN (pattern_parm);
16137         }
16138       /* Merge any parameters that match with the function parameter
16139          pack.  */
16140       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16141         {
16142           int i, len;
16143           tree expanded_types;
16144           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16145              the parameters in this function parameter pack.  */
16146           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16147                                                  args, tf_error, NULL_TREE);
16148           len = TREE_VEC_LENGTH (expanded_types);
16149           for (i = 0; i < len; i++)
16150             {
16151               tree parm_type;
16152               tree attributes;
16153           
16154               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16155                 /* Rename the parameter to include the index.  */
16156                 DECL_NAME (decl_parm) = 
16157                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16158               parm_type = TREE_VEC_ELT (expanded_types, i);
16159               parm_type = type_decays_to (parm_type);
16160               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16161                 TREE_TYPE (decl_parm) = parm_type;
16162               attributes = DECL_ATTRIBUTES (pattern_parm);
16163               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16164                 {
16165                   DECL_ATTRIBUTES (decl_parm) = attributes;
16166                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16167                 }
16168               decl_parm = TREE_CHAIN (decl_parm);
16169             }
16170         }
16171       /* Merge additional specifiers from the CODE_PATTERN.  */
16172       if (DECL_DECLARED_INLINE_P (code_pattern)
16173           && !DECL_DECLARED_INLINE_P (decl))
16174         DECL_DECLARED_INLINE_P (decl) = 1;
16175     }
16176   else if (TREE_CODE (decl) == VAR_DECL)
16177     DECL_INITIAL (decl) =
16178       tsubst_expr (DECL_INITIAL (code_pattern), args,
16179                    tf_error, DECL_TI_TEMPLATE (decl),
16180                    /*integral_constant_expression_p=*/false);
16181   else
16182     gcc_unreachable ();
16183
16184   pop_access_scope (decl);
16185 }
16186
16187 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16188    substituted to get DECL.  */
16189
16190 tree
16191 template_for_substitution (tree decl)
16192 {
16193   tree tmpl = DECL_TI_TEMPLATE (decl);
16194
16195   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16196      for the instantiation.  This is not always the most general
16197      template.  Consider, for example:
16198
16199         template <class T>
16200         struct S { template <class U> void f();
16201                    template <> void f<int>(); };
16202
16203      and an instantiation of S<double>::f<int>.  We want TD to be the
16204      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16205   while (/* An instantiation cannot have a definition, so we need a
16206             more general template.  */
16207          DECL_TEMPLATE_INSTANTIATION (tmpl)
16208            /* We must also deal with friend templates.  Given:
16209
16210                 template <class T> struct S {
16211                   template <class U> friend void f() {};
16212                 };
16213
16214               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16215               so far as the language is concerned, but that's still
16216               where we get the pattern for the instantiation from.  On
16217               other hand, if the definition comes outside the class, say:
16218
16219                 template <class T> struct S {
16220                   template <class U> friend void f();
16221                 };
16222                 template <class U> friend void f() {}
16223
16224               we don't need to look any further.  That's what the check for
16225               DECL_INITIAL is for.  */
16226           || (TREE_CODE (decl) == FUNCTION_DECL
16227               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16228               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16229     {
16230       /* The present template, TD, should not be a definition.  If it
16231          were a definition, we should be using it!  Note that we
16232          cannot restructure the loop to just keep going until we find
16233          a template with a definition, since that might go too far if
16234          a specialization was declared, but not defined.  */
16235       gcc_assert (TREE_CODE (decl) != VAR_DECL
16236                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16237
16238       /* Fetch the more general template.  */
16239       tmpl = DECL_TI_TEMPLATE (tmpl);
16240     }
16241
16242   return tmpl;
16243 }
16244
16245 /* Returns true if we need to instantiate this template instance even if we
16246    know we aren't going to emit it..  */
16247
16248 bool
16249 always_instantiate_p (tree decl)
16250 {
16251   /* We always instantiate inline functions so that we can inline them.  An
16252      explicit instantiation declaration prohibits implicit instantiation of
16253      non-inline functions.  With high levels of optimization, we would
16254      normally inline non-inline functions -- but we're not allowed to do
16255      that for "extern template" functions.  Therefore, we check
16256      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16257   return ((TREE_CODE (decl) == FUNCTION_DECL
16258            && DECL_DECLARED_INLINE_P (decl))
16259           /* And we need to instantiate static data members so that
16260              their initializers are available in integral constant
16261              expressions.  */
16262           || (TREE_CODE (decl) == VAR_DECL
16263               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16264 }
16265
16266 /* Produce the definition of D, a _DECL generated from a template.  If
16267    DEFER_OK is nonzero, then we don't have to actually do the
16268    instantiation now; we just have to do it sometime.  Normally it is
16269    an error if this is an explicit instantiation but D is undefined.
16270    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16271    explicitly instantiated class template.  */
16272
16273 tree
16274 instantiate_decl (tree d, int defer_ok,
16275                   bool expl_inst_class_mem_p)
16276 {
16277   tree tmpl = DECL_TI_TEMPLATE (d);
16278   tree gen_args;
16279   tree args;
16280   tree td;
16281   tree code_pattern;
16282   tree spec;
16283   tree gen_tmpl;
16284   bool pattern_defined;
16285   int need_push;
16286   location_t saved_loc = input_location;
16287   bool external_p;
16288
16289   /* This function should only be used to instantiate templates for
16290      functions and static member variables.  */
16291   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16292               || TREE_CODE (d) == VAR_DECL);
16293
16294   /* Variables are never deferred; if instantiation is required, they
16295      are instantiated right away.  That allows for better code in the
16296      case that an expression refers to the value of the variable --
16297      if the variable has a constant value the referring expression can
16298      take advantage of that fact.  */
16299   if (TREE_CODE (d) == VAR_DECL)
16300     defer_ok = 0;
16301
16302   /* Don't instantiate cloned functions.  Instead, instantiate the
16303      functions they cloned.  */
16304   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16305     d = DECL_CLONED_FUNCTION (d);
16306
16307   if (DECL_TEMPLATE_INSTANTIATED (d)
16308       || DECL_TEMPLATE_SPECIALIZATION (d))
16309     /* D has already been instantiated or explicitly specialized, so
16310        there's nothing for us to do here.
16311
16312        It might seem reasonable to check whether or not D is an explicit
16313        instantiation, and, if so, stop here.  But when an explicit
16314        instantiation is deferred until the end of the compilation,
16315        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16316        the instantiation.  */
16317     return d;
16318
16319   /* Check to see whether we know that this template will be
16320      instantiated in some other file, as with "extern template"
16321      extension.  */
16322   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16323
16324   /* In general, we do not instantiate such templates.  */
16325   if (external_p && !always_instantiate_p (d))
16326     return d;
16327
16328   gen_tmpl = most_general_template (tmpl);
16329   gen_args = DECL_TI_ARGS (d);
16330
16331   if (tmpl != gen_tmpl)
16332     /* We should already have the extra args.  */
16333     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16334                 == TMPL_ARGS_DEPTH (gen_args));
16335   /* And what's in the hash table should match D.  */
16336   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16337               || spec == NULL_TREE);
16338
16339   /* This needs to happen before any tsubsting.  */
16340   if (! push_tinst_level (d))
16341     return d;
16342
16343   timevar_push (TV_PARSE);
16344
16345   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16346      for the instantiation.  */
16347   td = template_for_substitution (d);
16348   code_pattern = DECL_TEMPLATE_RESULT (td);
16349
16350   /* We should never be trying to instantiate a member of a class
16351      template or partial specialization.  */
16352   gcc_assert (d != code_pattern);
16353
16354   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16355       || DECL_TEMPLATE_SPECIALIZATION (td))
16356     /* In the case of a friend template whose definition is provided
16357        outside the class, we may have too many arguments.  Drop the
16358        ones we don't need.  The same is true for specializations.  */
16359     args = get_innermost_template_args
16360       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16361   else
16362     args = gen_args;
16363
16364   if (TREE_CODE (d) == FUNCTION_DECL)
16365     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16366   else
16367     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16368
16369   /* We may be in the middle of deferred access check.  Disable it now.  */
16370   push_deferring_access_checks (dk_no_deferred);
16371
16372   /* Unless an explicit instantiation directive has already determined
16373      the linkage of D, remember that a definition is available for
16374      this entity.  */
16375   if (pattern_defined
16376       && !DECL_INTERFACE_KNOWN (d)
16377       && !DECL_NOT_REALLY_EXTERN (d))
16378     mark_definable (d);
16379
16380   input_location = DECL_SOURCE_LOCATION (d);
16381
16382   /* If D is a member of an explicitly instantiated class template,
16383      and no definition is available, treat it like an implicit
16384      instantiation.  */
16385   if (!pattern_defined && expl_inst_class_mem_p
16386       && DECL_EXPLICIT_INSTANTIATION (d))
16387     {
16388       DECL_NOT_REALLY_EXTERN (d) = 0;
16389       DECL_INTERFACE_KNOWN (d) = 0;
16390       SET_DECL_IMPLICIT_INSTANTIATION (d);
16391     }
16392
16393   /* Recheck the substitutions to obtain any warning messages
16394      about ignoring cv qualifiers.  Don't do this for artificial decls,
16395      as it breaks the context-sensitive substitution for lambda op(). */
16396   if (!defer_ok && !DECL_ARTIFICIAL (d))
16397     {
16398       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16399       tree type = TREE_TYPE (gen);
16400
16401       /* Make sure that we can see identifiers, and compute access
16402          correctly.  D is already the target FUNCTION_DECL with the
16403          right context.  */
16404       push_access_scope (d);
16405
16406       if (TREE_CODE (gen) == FUNCTION_DECL)
16407         {
16408           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16409           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16410                                           d);
16411           /* Don't simply tsubst the function type, as that will give
16412              duplicate warnings about poor parameter qualifications.
16413              The function arguments are the same as the decl_arguments
16414              without the top level cv qualifiers.  */
16415           type = TREE_TYPE (type);
16416         }
16417       tsubst (type, gen_args, tf_warning_or_error, d);
16418
16419       pop_access_scope (d);
16420     }
16421
16422   /* Defer all other templates, unless we have been explicitly
16423      forbidden from doing so.  */
16424   if (/* If there is no definition, we cannot instantiate the
16425          template.  */
16426       ! pattern_defined
16427       /* If it's OK to postpone instantiation, do so.  */
16428       || defer_ok
16429       /* If this is a static data member that will be defined
16430          elsewhere, we don't want to instantiate the entire data
16431          member, but we do want to instantiate the initializer so that
16432          we can substitute that elsewhere.  */
16433       || (external_p && TREE_CODE (d) == VAR_DECL))
16434     {
16435       /* The definition of the static data member is now required so
16436          we must substitute the initializer.  */
16437       if (TREE_CODE (d) == VAR_DECL
16438           && !DECL_INITIAL (d)
16439           && DECL_INITIAL (code_pattern))
16440         {
16441           tree ns;
16442           tree init;
16443
16444           ns = decl_namespace_context (d);
16445           push_nested_namespace (ns);
16446           push_nested_class (DECL_CONTEXT (d));
16447           init = tsubst_expr (DECL_INITIAL (code_pattern),
16448                               args,
16449                               tf_warning_or_error, NULL_TREE,
16450                               /*integral_constant_expression_p=*/false);
16451           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16452                           /*asmspec_tree=*/NULL_TREE,
16453                           LOOKUP_ONLYCONVERTING);
16454           pop_nested_class ();
16455           pop_nested_namespace (ns);
16456         }
16457
16458       /* We restore the source position here because it's used by
16459          add_pending_template.  */
16460       input_location = saved_loc;
16461
16462       if (at_eof && !pattern_defined
16463           && DECL_EXPLICIT_INSTANTIATION (d)
16464           && DECL_NOT_REALLY_EXTERN (d))
16465         /* [temp.explicit]
16466
16467            The definition of a non-exported function template, a
16468            non-exported member function template, or a non-exported
16469            member function or static data member of a class template
16470            shall be present in every translation unit in which it is
16471            explicitly instantiated.  */
16472         permerror (input_location,  "explicit instantiation of %qD "
16473                    "but no definition available", d);
16474
16475       /* ??? Historically, we have instantiated inline functions, even
16476          when marked as "extern template".  */
16477       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16478         add_pending_template (d);
16479       goto out;
16480     }
16481   /* Tell the repository that D is available in this translation unit
16482      -- and see if it is supposed to be instantiated here.  */
16483   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16484     {
16485       /* In a PCH file, despite the fact that the repository hasn't
16486          requested instantiation in the PCH it is still possible that
16487          an instantiation will be required in a file that includes the
16488          PCH.  */
16489       if (pch_file)
16490         add_pending_template (d);
16491       /* Instantiate inline functions so that the inliner can do its
16492          job, even though we'll not be emitting a copy of this
16493          function.  */
16494       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16495         goto out;
16496     }
16497
16498   need_push = !cfun || !global_bindings_p ();
16499   if (need_push)
16500     push_to_top_level ();
16501
16502   /* Mark D as instantiated so that recursive calls to
16503      instantiate_decl do not try to instantiate it again.  */
16504   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16505
16506   /* Regenerate the declaration in case the template has been modified
16507      by a subsequent redeclaration.  */
16508   regenerate_decl_from_template (d, td);
16509
16510   /* We already set the file and line above.  Reset them now in case
16511      they changed as a result of calling regenerate_decl_from_template.  */
16512   input_location = DECL_SOURCE_LOCATION (d);
16513
16514   if (TREE_CODE (d) == VAR_DECL)
16515     {
16516       tree init;
16517
16518       /* Clear out DECL_RTL; whatever was there before may not be right
16519          since we've reset the type of the declaration.  */
16520       SET_DECL_RTL (d, NULL_RTX);
16521       DECL_IN_AGGR_P (d) = 0;
16522
16523       /* The initializer is placed in DECL_INITIAL by
16524          regenerate_decl_from_template.  Pull it out so that
16525          cp_finish_decl can process it.  */
16526       init = DECL_INITIAL (d);
16527       DECL_INITIAL (d) = NULL_TREE;
16528       DECL_INITIALIZED_P (d) = 0;
16529
16530       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16531          initializer.  That function will defer actual emission until
16532          we have a chance to determine linkage.  */
16533       DECL_EXTERNAL (d) = 0;
16534
16535       /* Enter the scope of D so that access-checking works correctly.  */
16536       push_nested_class (DECL_CONTEXT (d));
16537       cp_finish_decl (d, init, false, NULL_TREE, 0);
16538       pop_nested_class ();
16539     }
16540   else if (TREE_CODE (d) == FUNCTION_DECL)
16541     {
16542       htab_t saved_local_specializations;
16543       tree subst_decl;
16544       tree tmpl_parm;
16545       tree spec_parm;
16546
16547       /* Save away the current list, in case we are instantiating one
16548          template from within the body of another.  */
16549       saved_local_specializations = local_specializations;
16550
16551       /* Set up the list of local specializations.  */
16552       local_specializations = htab_create (37,
16553                                            hash_local_specialization,
16554                                            eq_local_specializations,
16555                                            NULL);
16556
16557       /* Set up context.  */
16558       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16559
16560       /* Create substitution entries for the parameters.  */
16561       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16562       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16563       spec_parm = DECL_ARGUMENTS (d);
16564       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16565         {
16566           register_local_specialization (spec_parm, tmpl_parm);
16567           spec_parm = skip_artificial_parms_for (d, spec_parm);
16568           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16569         }
16570       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16571         {
16572           register_local_specialization (spec_parm, tmpl_parm);
16573           tmpl_parm = TREE_CHAIN (tmpl_parm);
16574           spec_parm = TREE_CHAIN (spec_parm);
16575         }
16576       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16577         {
16578           /* Register the (value) argument pack as a specialization of
16579              TMPL_PARM, then move on.  */
16580           tree argpack = make_fnparm_pack (spec_parm);
16581           register_local_specialization (argpack, tmpl_parm);
16582           tmpl_parm = TREE_CHAIN (tmpl_parm);
16583           spec_parm = NULL_TREE;
16584         }
16585       gcc_assert (!spec_parm);
16586
16587       /* Substitute into the body of the function.  */
16588       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16589                    tf_warning_or_error, tmpl,
16590                    /*integral_constant_expression_p=*/false);
16591
16592       /* Set the current input_location to the end of the function
16593          so that finish_function knows where we are.  */
16594       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16595
16596       /* We don't need the local specializations any more.  */
16597       htab_delete (local_specializations);
16598       local_specializations = saved_local_specializations;
16599
16600       /* Finish the function.  */
16601       d = finish_function (0);
16602       expand_or_defer_fn (d);
16603     }
16604
16605   /* We're not deferring instantiation any more.  */
16606   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16607
16608   if (need_push)
16609     pop_from_top_level ();
16610
16611 out:
16612   input_location = saved_loc;
16613   pop_deferring_access_checks ();
16614   pop_tinst_level ();
16615
16616   timevar_pop (TV_PARSE);
16617
16618   return d;
16619 }
16620
16621 /* Run through the list of templates that we wish we could
16622    instantiate, and instantiate any we can.  RETRIES is the
16623    number of times we retry pending template instantiation.  */
16624
16625 void
16626 instantiate_pending_templates (int retries)
16627 {
16628   int reconsider;
16629   location_t saved_loc = input_location;
16630
16631   /* Instantiating templates may trigger vtable generation.  This in turn
16632      may require further template instantiations.  We place a limit here
16633      to avoid infinite loop.  */
16634   if (pending_templates && retries >= max_tinst_depth)
16635     {
16636       tree decl = pending_templates->tinst->decl;
16637
16638       error ("template instantiation depth exceeds maximum of %d"
16639              " instantiating %q+D, possibly from virtual table generation"
16640              " (use -ftemplate-depth-NN to increase the maximum)",
16641              max_tinst_depth, decl);
16642       if (TREE_CODE (decl) == FUNCTION_DECL)
16643         /* Pretend that we defined it.  */
16644         DECL_INITIAL (decl) = error_mark_node;
16645       return;
16646     }
16647
16648   do
16649     {
16650       struct pending_template **t = &pending_templates;
16651       struct pending_template *last = NULL;
16652       reconsider = 0;
16653       while (*t)
16654         {
16655           tree instantiation = reopen_tinst_level ((*t)->tinst);
16656           bool complete = false;
16657
16658           if (TYPE_P (instantiation))
16659             {
16660               tree fn;
16661
16662               if (!COMPLETE_TYPE_P (instantiation))
16663                 {
16664                   instantiate_class_template (instantiation);
16665                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16666                     for (fn = TYPE_METHODS (instantiation);
16667                          fn;
16668                          fn = TREE_CHAIN (fn))
16669                       if (! DECL_ARTIFICIAL (fn))
16670                         instantiate_decl (fn,
16671                                           /*defer_ok=*/0,
16672                                           /*expl_inst_class_mem_p=*/false);
16673                   if (COMPLETE_TYPE_P (instantiation))
16674                     reconsider = 1;
16675                 }
16676
16677               complete = COMPLETE_TYPE_P (instantiation);
16678             }
16679           else
16680             {
16681               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16682                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16683                 {
16684                   instantiation
16685                     = instantiate_decl (instantiation,
16686                                         /*defer_ok=*/0,
16687                                         /*expl_inst_class_mem_p=*/false);
16688                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16689                     reconsider = 1;
16690                 }
16691
16692               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16693                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16694             }
16695
16696           if (complete)
16697             /* If INSTANTIATION has been instantiated, then we don't
16698                need to consider it again in the future.  */
16699             *t = (*t)->next;
16700           else
16701             {
16702               last = *t;
16703               t = &(*t)->next;
16704             }
16705           tinst_depth = 0;
16706           current_tinst_level = NULL;
16707         }
16708       last_pending_template = last;
16709     }
16710   while (reconsider);
16711
16712   input_location = saved_loc;
16713 }
16714
16715 /* Substitute ARGVEC into T, which is a list of initializers for
16716    either base class or a non-static data member.  The TREE_PURPOSEs
16717    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16718    instantiate_decl.  */
16719
16720 static tree
16721 tsubst_initializer_list (tree t, tree argvec)
16722 {
16723   tree inits = NULL_TREE;
16724
16725   for (; t; t = TREE_CHAIN (t))
16726     {
16727       tree decl;
16728       tree init;
16729       tree expanded_bases = NULL_TREE;
16730       tree expanded_arguments = NULL_TREE;
16731       int i, len = 1;
16732
16733       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16734         {
16735           tree expr;
16736           tree arg;
16737
16738           /* Expand the base class expansion type into separate base
16739              classes.  */
16740           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16741                                                  tf_warning_or_error,
16742                                                  NULL_TREE);
16743           if (expanded_bases == error_mark_node)
16744             continue;
16745           
16746           /* We'll be building separate TREE_LISTs of arguments for
16747              each base.  */
16748           len = TREE_VEC_LENGTH (expanded_bases);
16749           expanded_arguments = make_tree_vec (len);
16750           for (i = 0; i < len; i++)
16751             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16752
16753           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16754              expand each argument in the TREE_VALUE of t.  */
16755           expr = make_node (EXPR_PACK_EXPANSION);
16756           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16757             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16758
16759           if (TREE_VALUE (t) == void_type_node)
16760             /* VOID_TYPE_NODE is used to indicate
16761                value-initialization.  */
16762             {
16763               for (i = 0; i < len; i++)
16764                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16765             }
16766           else
16767             {
16768               /* Substitute parameter packs into each argument in the
16769                  TREE_LIST.  */
16770               in_base_initializer = 1;
16771               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16772                 {
16773                   tree expanded_exprs;
16774
16775                   /* Expand the argument.  */
16776                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16777                   expanded_exprs 
16778                     = tsubst_pack_expansion (expr, argvec,
16779                                              tf_warning_or_error,
16780                                              NULL_TREE);
16781                   if (expanded_exprs == error_mark_node)
16782                     continue;
16783
16784                   /* Prepend each of the expanded expressions to the
16785                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16786                   for (i = 0; i < len; i++)
16787                     {
16788                       TREE_VEC_ELT (expanded_arguments, i) = 
16789                         tree_cons (NULL_TREE, 
16790                                    TREE_VEC_ELT (expanded_exprs, i),
16791                                    TREE_VEC_ELT (expanded_arguments, i));
16792                     }
16793                 }
16794               in_base_initializer = 0;
16795
16796               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16797                  since we built them backwards.  */
16798               for (i = 0; i < len; i++)
16799                 {
16800                   TREE_VEC_ELT (expanded_arguments, i) = 
16801                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16802                 }
16803             }
16804         }
16805
16806       for (i = 0; i < len; ++i)
16807         {
16808           if (expanded_bases)
16809             {
16810               decl = TREE_VEC_ELT (expanded_bases, i);
16811               decl = expand_member_init (decl);
16812               init = TREE_VEC_ELT (expanded_arguments, i);
16813             }
16814           else
16815             {
16816               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16817                                   tf_warning_or_error, NULL_TREE);
16818
16819               decl = expand_member_init (decl);
16820               if (decl && !DECL_P (decl))
16821                 in_base_initializer = 1;
16822
16823               init = tsubst_expr (TREE_VALUE (t), argvec, 
16824                                   tf_warning_or_error, NULL_TREE,
16825                                   /*integral_constant_expression_p=*/false);
16826               in_base_initializer = 0;
16827             }
16828
16829           if (decl)
16830             {
16831               init = build_tree_list (decl, init);
16832               TREE_CHAIN (init) = inits;
16833               inits = init;
16834             }
16835         }
16836     }
16837   return inits;
16838 }
16839
16840 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16841
16842 static void
16843 set_current_access_from_decl (tree decl)
16844 {
16845   if (TREE_PRIVATE (decl))
16846     current_access_specifier = access_private_node;
16847   else if (TREE_PROTECTED (decl))
16848     current_access_specifier = access_protected_node;
16849   else
16850     current_access_specifier = access_public_node;
16851 }
16852
16853 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16854    is the instantiation (which should have been created with
16855    start_enum) and ARGS are the template arguments to use.  */
16856
16857 static void
16858 tsubst_enum (tree tag, tree newtag, tree args)
16859 {
16860   tree e;
16861
16862   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16863     {
16864       tree value;
16865       tree decl;
16866
16867       decl = TREE_VALUE (e);
16868       /* Note that in a template enum, the TREE_VALUE is the
16869          CONST_DECL, not the corresponding INTEGER_CST.  */
16870       value = tsubst_expr (DECL_INITIAL (decl),
16871                            args, tf_warning_or_error, NULL_TREE,
16872                            /*integral_constant_expression_p=*/true);
16873
16874       /* Give this enumeration constant the correct access.  */
16875       set_current_access_from_decl (decl);
16876
16877       /* Actually build the enumerator itself.  */
16878       build_enumerator (DECL_NAME (decl), value, newtag);
16879     }
16880
16881   finish_enum (newtag);
16882   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16883     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16884 }
16885
16886 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16887    its type -- but without substituting the innermost set of template
16888    arguments.  So, innermost set of template parameters will appear in
16889    the type.  */
16890
16891 tree
16892 get_mostly_instantiated_function_type (tree decl)
16893 {
16894   tree fn_type;
16895   tree tmpl;
16896   tree targs;
16897   tree tparms;
16898   int parm_depth;
16899
16900   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16901   targs = DECL_TI_ARGS (decl);
16902   tparms = DECL_TEMPLATE_PARMS (tmpl);
16903   parm_depth = TMPL_PARMS_DEPTH (tparms);
16904
16905   /* There should be as many levels of arguments as there are levels
16906      of parameters.  */
16907   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16908
16909   fn_type = TREE_TYPE (tmpl);
16910
16911   if (parm_depth == 1)
16912     /* No substitution is necessary.  */
16913     ;
16914   else
16915     {
16916       int i, save_access_control;
16917       tree partial_args;
16918
16919       /* Replace the innermost level of the TARGS with NULL_TREEs to
16920          let tsubst know not to substitute for those parameters.  */
16921       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16922       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16923         SET_TMPL_ARGS_LEVEL (partial_args, i,
16924                              TMPL_ARGS_LEVEL (targs, i));
16925       SET_TMPL_ARGS_LEVEL (partial_args,
16926                            TMPL_ARGS_DEPTH (targs),
16927                            make_tree_vec (DECL_NTPARMS (tmpl)));
16928
16929       /* Disable access control as this function is used only during
16930          name-mangling.  */
16931       save_access_control = flag_access_control;
16932       flag_access_control = 0;
16933
16934       ++processing_template_decl;
16935       /* Now, do the (partial) substitution to figure out the
16936          appropriate function type.  */
16937       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16938       --processing_template_decl;
16939
16940       /* Substitute into the template parameters to obtain the real
16941          innermost set of parameters.  This step is important if the
16942          innermost set of template parameters contains value
16943          parameters whose types depend on outer template parameters.  */
16944       TREE_VEC_LENGTH (partial_args)--;
16945       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16946
16947       flag_access_control = save_access_control;
16948     }
16949
16950   return fn_type;
16951 }
16952
16953 /* Return truthvalue if we're processing a template different from
16954    the last one involved in diagnostics.  */
16955 int
16956 problematic_instantiation_changed (void)
16957 {
16958   return last_template_error_tick != tinst_level_tick;
16959 }
16960
16961 /* Remember current template involved in diagnostics.  */
16962 void
16963 record_last_problematic_instantiation (void)
16964 {
16965   last_template_error_tick = tinst_level_tick;
16966 }
16967
16968 struct tinst_level *
16969 current_instantiation (void)
16970 {
16971   return current_tinst_level;
16972 }
16973
16974 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16975    type. Return zero for ok, nonzero for disallowed. Issue error and
16976    warning messages under control of COMPLAIN.  */
16977
16978 static int
16979 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16980 {
16981   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16982     return 0;
16983   else if (POINTER_TYPE_P (type))
16984     return 0;
16985   else if (TYPE_PTR_TO_MEMBER_P (type))
16986     return 0;
16987   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16988     return 0;
16989   else if (TREE_CODE (type) == TYPENAME_TYPE)
16990     return 0;
16991
16992   if (complain & tf_error)
16993     error ("%q#T is not a valid type for a template constant parameter", type);
16994   return 1;
16995 }
16996
16997 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16998    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16999
17000 static bool
17001 dependent_type_p_r (tree type)
17002 {
17003   tree scope;
17004
17005   /* [temp.dep.type]
17006
17007      A type is dependent if it is:
17008
17009      -- a template parameter. Template template parameters are types
17010         for us (since TYPE_P holds true for them) so we handle
17011         them here.  */
17012   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17013       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17014     return true;
17015   /* -- a qualified-id with a nested-name-specifier which contains a
17016         class-name that names a dependent type or whose unqualified-id
17017         names a dependent type.  */
17018   if (TREE_CODE (type) == TYPENAME_TYPE)
17019     return true;
17020   /* -- a cv-qualified type where the cv-unqualified type is
17021         dependent.  */
17022   type = TYPE_MAIN_VARIANT (type);
17023   /* -- a compound type constructed from any dependent type.  */
17024   if (TYPE_PTR_TO_MEMBER_P (type))
17025     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17026             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17027                                            (type)));
17028   else if (TREE_CODE (type) == POINTER_TYPE
17029            || TREE_CODE (type) == REFERENCE_TYPE)
17030     return dependent_type_p (TREE_TYPE (type));
17031   else if (TREE_CODE (type) == FUNCTION_TYPE
17032            || TREE_CODE (type) == METHOD_TYPE)
17033     {
17034       tree arg_type;
17035
17036       if (dependent_type_p (TREE_TYPE (type)))
17037         return true;
17038       for (arg_type = TYPE_ARG_TYPES (type);
17039            arg_type;
17040            arg_type = TREE_CHAIN (arg_type))
17041         if (dependent_type_p (TREE_VALUE (arg_type)))
17042           return true;
17043       return false;
17044     }
17045   /* -- an array type constructed from any dependent type or whose
17046         size is specified by a constant expression that is
17047         value-dependent.  */
17048   if (TREE_CODE (type) == ARRAY_TYPE)
17049     {
17050       if (TYPE_DOMAIN (type)
17051           && dependent_type_p (TYPE_DOMAIN (type)))
17052         return true;
17053       return dependent_type_p (TREE_TYPE (type));
17054     }
17055   else if (TREE_CODE (type) == INTEGER_TYPE
17056            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17057     {
17058       /* If this is the TYPE_DOMAIN of an array type, consider it
17059          dependent.  We already checked for value-dependence in
17060          compute_array_index_type.  */
17061       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17062     }
17063
17064   /* -- a template-id in which either the template name is a template
17065      parameter ...  */
17066   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17067     return true;
17068   /* ... or any of the template arguments is a dependent type or
17069         an expression that is type-dependent or value-dependent.  */
17070   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17071            && (any_dependent_template_arguments_p
17072                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17073     return true;
17074
17075   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17076      argument of the `typeof' expression is not type-dependent, then
17077      it should already been have resolved.  */
17078   if (TREE_CODE (type) == TYPEOF_TYPE
17079       || TREE_CODE (type) == DECLTYPE_TYPE)
17080     return true;
17081
17082   /* A template argument pack is dependent if any of its packed
17083      arguments are.  */
17084   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17085     {
17086       tree args = ARGUMENT_PACK_ARGS (type);
17087       int i, len = TREE_VEC_LENGTH (args);
17088       for (i = 0; i < len; ++i)
17089         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17090           return true;
17091     }
17092
17093   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17094      be template parameters.  */
17095   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17096     return true;
17097
17098   /* The standard does not specifically mention types that are local
17099      to template functions or local classes, but they should be
17100      considered dependent too.  For example:
17101
17102        template <int I> void f() {
17103          enum E { a = I };
17104          S<sizeof (E)> s;
17105        }
17106
17107      The size of `E' cannot be known until the value of `I' has been
17108      determined.  Therefore, `E' must be considered dependent.  */
17109   scope = TYPE_CONTEXT (type);
17110   if (scope && TYPE_P (scope))
17111     return dependent_type_p (scope);
17112   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17113     return type_dependent_expression_p (scope);
17114
17115   /* Other types are non-dependent.  */
17116   return false;
17117 }
17118
17119 /* Returns TRUE if TYPE is dependent, in the sense of
17120    [temp.dep.type].  */
17121
17122 bool
17123 dependent_type_p (tree type)
17124 {
17125   /* If there are no template parameters in scope, then there can't be
17126      any dependent types.  */
17127   if (!processing_template_decl)
17128     {
17129       /* If we are not processing a template, then nobody should be
17130          providing us with a dependent type.  */
17131       gcc_assert (type);
17132       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17133       return false;
17134     }
17135
17136   /* If the type is NULL, we have not computed a type for the entity
17137      in question; in that case, the type is dependent.  */
17138   if (!type)
17139     return true;
17140
17141   /* Erroneous types can be considered non-dependent.  */
17142   if (type == error_mark_node)
17143     return false;
17144
17145   /* If we have not already computed the appropriate value for TYPE,
17146      do so now.  */
17147   if (!TYPE_DEPENDENT_P_VALID (type))
17148     {
17149       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17150       TYPE_DEPENDENT_P_VALID (type) = 1;
17151     }
17152
17153   return TYPE_DEPENDENT_P (type);
17154 }
17155
17156 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17157    lookup.  In other words, a dependent type that is not the current
17158    instantiation.  */
17159
17160 bool
17161 dependent_scope_p (tree scope)
17162 {
17163   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17164           && !currently_open_class (scope));
17165 }
17166
17167 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17168
17169 static bool
17170 dependent_scope_ref_p (tree expression, bool criterion (tree))
17171 {
17172   tree scope;
17173   tree name;
17174
17175   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17176
17177   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17178     return true;
17179
17180   scope = TREE_OPERAND (expression, 0);
17181   name = TREE_OPERAND (expression, 1);
17182
17183   /* [temp.dep.expr]
17184
17185      An id-expression is type-dependent if it contains a
17186      nested-name-specifier that contains a class-name that names a
17187      dependent type.  */
17188   /* The suggested resolution to Core Issue 224 implies that if the
17189      qualifying type is the current class, then we must peek
17190      inside it.  */
17191   if (DECL_P (name)
17192       && currently_open_class (scope)
17193       && !criterion (name))
17194     return false;
17195   if (dependent_type_p (scope))
17196     return true;
17197
17198   return false;
17199 }
17200
17201 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17202    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17203    expression.  */
17204
17205 bool
17206 value_dependent_expression_p (tree expression)
17207 {
17208   if (!processing_template_decl)
17209     return false;
17210
17211   /* A name declared with a dependent type.  */
17212   if (DECL_P (expression) && type_dependent_expression_p (expression))
17213     return true;
17214
17215   switch (TREE_CODE (expression))
17216     {
17217     case IDENTIFIER_NODE:
17218       /* A name that has not been looked up -- must be dependent.  */
17219       return true;
17220
17221     case TEMPLATE_PARM_INDEX:
17222       /* A non-type template parm.  */
17223       return true;
17224
17225     case CONST_DECL:
17226       /* A non-type template parm.  */
17227       if (DECL_TEMPLATE_PARM_P (expression))
17228         return true;
17229       return value_dependent_expression_p (DECL_INITIAL (expression));
17230
17231     case VAR_DECL:
17232        /* A constant with integral or enumeration type and is initialized
17233           with an expression that is value-dependent.  */
17234       if (DECL_INITIAL (expression)
17235           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17236           && value_dependent_expression_p (DECL_INITIAL (expression)))
17237         return true;
17238       return false;
17239
17240     case DYNAMIC_CAST_EXPR:
17241     case STATIC_CAST_EXPR:
17242     case CONST_CAST_EXPR:
17243     case REINTERPRET_CAST_EXPR:
17244     case CAST_EXPR:
17245       /* These expressions are value-dependent if the type to which
17246          the cast occurs is dependent or the expression being casted
17247          is value-dependent.  */
17248       {
17249         tree type = TREE_TYPE (expression);
17250
17251         if (dependent_type_p (type))
17252           return true;
17253
17254         /* A functional cast has a list of operands.  */
17255         expression = TREE_OPERAND (expression, 0);
17256         if (!expression)
17257           {
17258             /* If there are no operands, it must be an expression such
17259                as "int()". This should not happen for aggregate types
17260                because it would form non-constant expressions.  */
17261             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17262
17263             return false;
17264           }
17265
17266         if (TREE_CODE (expression) == TREE_LIST)
17267           return any_value_dependent_elements_p (expression);
17268
17269         return value_dependent_expression_p (expression);
17270       }
17271
17272     case SIZEOF_EXPR:
17273     case ALIGNOF_EXPR:
17274       /* A `sizeof' expression is value-dependent if the operand is
17275          type-dependent or is a pack expansion.  */
17276       expression = TREE_OPERAND (expression, 0);
17277       if (PACK_EXPANSION_P (expression))
17278         return true;
17279       else if (TYPE_P (expression))
17280         return dependent_type_p (expression);
17281       return type_dependent_expression_p (expression);
17282
17283     case SCOPE_REF:
17284       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17285
17286     case COMPONENT_REF:
17287       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17288               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17289
17290     case CALL_EXPR:
17291       /* A CALL_EXPR may appear in a constant expression if it is a
17292          call to a builtin function, e.g., __builtin_constant_p.  All
17293          such calls are value-dependent.  */
17294       return true;
17295
17296     case NONTYPE_ARGUMENT_PACK:
17297       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17298          is value-dependent.  */
17299       {
17300         tree values = ARGUMENT_PACK_ARGS (expression);
17301         int i, len = TREE_VEC_LENGTH (values);
17302         
17303         for (i = 0; i < len; ++i)
17304           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17305             return true;
17306         
17307         return false;
17308       }
17309
17310     case TRAIT_EXPR:
17311       {
17312         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17313         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17314                 || (type2 ? dependent_type_p (type2) : false));
17315       }
17316
17317     case MODOP_EXPR:
17318       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17319               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17320
17321     default:
17322       /* A constant expression is value-dependent if any subexpression is
17323          value-dependent.  */
17324       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17325         {
17326         case tcc_reference:
17327         case tcc_unary:
17328           return (value_dependent_expression_p
17329                   (TREE_OPERAND (expression, 0)));
17330
17331         case tcc_comparison:
17332         case tcc_binary:
17333           return ((value_dependent_expression_p
17334                    (TREE_OPERAND (expression, 0)))
17335                   || (value_dependent_expression_p
17336                       (TREE_OPERAND (expression, 1))));
17337
17338         case tcc_expression:
17339         case tcc_vl_exp:
17340           {
17341             int i;
17342             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17343               /* In some cases, some of the operands may be missing.
17344                  (For example, in the case of PREDECREMENT_EXPR, the
17345                  amount to increment by may be missing.)  That doesn't
17346                  make the expression dependent.  */
17347               if (TREE_OPERAND (expression, i)
17348                   && (value_dependent_expression_p
17349                       (TREE_OPERAND (expression, i))))
17350                 return true;
17351             return false;
17352           }
17353
17354         default:
17355           break;
17356         }
17357     }
17358
17359   /* The expression is not value-dependent.  */
17360   return false;
17361 }
17362
17363 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17364    [temp.dep.expr].  */
17365
17366 bool
17367 type_dependent_expression_p (tree expression)
17368 {
17369   if (!processing_template_decl)
17370     return false;
17371
17372   if (expression == error_mark_node)
17373     return false;
17374
17375   /* An unresolved name is always dependent.  */
17376   if (TREE_CODE (expression) == IDENTIFIER_NODE
17377       || TREE_CODE (expression) == USING_DECL)
17378     return true;
17379
17380   /* Some expression forms are never type-dependent.  */
17381   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17382       || TREE_CODE (expression) == SIZEOF_EXPR
17383       || TREE_CODE (expression) == ALIGNOF_EXPR
17384       || TREE_CODE (expression) == TRAIT_EXPR
17385       || TREE_CODE (expression) == TYPEID_EXPR
17386       || TREE_CODE (expression) == DELETE_EXPR
17387       || TREE_CODE (expression) == VEC_DELETE_EXPR
17388       || TREE_CODE (expression) == THROW_EXPR)
17389     return false;
17390
17391   /* The types of these expressions depends only on the type to which
17392      the cast occurs.  */
17393   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17394       || TREE_CODE (expression) == STATIC_CAST_EXPR
17395       || TREE_CODE (expression) == CONST_CAST_EXPR
17396       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17397       || TREE_CODE (expression) == CAST_EXPR)
17398     return dependent_type_p (TREE_TYPE (expression));
17399
17400   /* The types of these expressions depends only on the type created
17401      by the expression.  */
17402   if (TREE_CODE (expression) == NEW_EXPR
17403       || TREE_CODE (expression) == VEC_NEW_EXPR)
17404     {
17405       /* For NEW_EXPR tree nodes created inside a template, either
17406          the object type itself or a TREE_LIST may appear as the
17407          operand 1.  */
17408       tree type = TREE_OPERAND (expression, 1);
17409       if (TREE_CODE (type) == TREE_LIST)
17410         /* This is an array type.  We need to check array dimensions
17411            as well.  */
17412         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17413                || value_dependent_expression_p
17414                     (TREE_OPERAND (TREE_VALUE (type), 1));
17415       else
17416         return dependent_type_p (type);
17417     }
17418
17419   if (TREE_CODE (expression) == SCOPE_REF
17420       && dependent_scope_ref_p (expression,
17421                                 type_dependent_expression_p))
17422     return true;
17423
17424   if (TREE_CODE (expression) == FUNCTION_DECL
17425       && DECL_LANG_SPECIFIC (expression)
17426       && DECL_TEMPLATE_INFO (expression)
17427       && (any_dependent_template_arguments_p
17428           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17429     return true;
17430
17431   if (TREE_CODE (expression) == TEMPLATE_DECL
17432       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17433     return false;
17434
17435   if (TREE_CODE (expression) == STMT_EXPR)
17436     expression = stmt_expr_value_expr (expression);
17437
17438   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17439     {
17440       tree elt;
17441       unsigned i;
17442
17443       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17444         {
17445           if (type_dependent_expression_p (elt))
17446             return true;
17447         }
17448       return false;
17449     }
17450
17451   if (TREE_TYPE (expression) == unknown_type_node)
17452     {
17453       if (TREE_CODE (expression) == ADDR_EXPR)
17454         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17455       if (TREE_CODE (expression) == COMPONENT_REF
17456           || TREE_CODE (expression) == OFFSET_REF)
17457         {
17458           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17459             return true;
17460           expression = TREE_OPERAND (expression, 1);
17461           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17462             return false;
17463         }
17464       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17465       if (TREE_CODE (expression) == SCOPE_REF)
17466         return false;
17467
17468       if (TREE_CODE (expression) == BASELINK)
17469         expression = BASELINK_FUNCTIONS (expression);
17470
17471       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17472         {
17473           if (any_dependent_template_arguments_p
17474               (TREE_OPERAND (expression, 1)))
17475             return true;
17476           expression = TREE_OPERAND (expression, 0);
17477         }
17478       gcc_assert (TREE_CODE (expression) == OVERLOAD
17479                   || TREE_CODE (expression) == FUNCTION_DECL);
17480
17481       while (expression)
17482         {
17483           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17484             return true;
17485           expression = OVL_NEXT (expression);
17486         }
17487       return false;
17488     }
17489
17490   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17491
17492   return (dependent_type_p (TREE_TYPE (expression)));
17493 }
17494
17495 /* Like type_dependent_expression_p, but it also works while not processing
17496    a template definition, i.e. during substitution or mangling.  */
17497
17498 bool
17499 type_dependent_expression_p_push (tree expr)
17500 {
17501   bool b;
17502   ++processing_template_decl;
17503   b = type_dependent_expression_p (expr);
17504   --processing_template_decl;
17505   return b;
17506 }
17507
17508 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17509
17510 bool
17511 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17512 {
17513   unsigned int i;
17514   tree arg;
17515
17516   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17517     {
17518       if (type_dependent_expression_p (arg))
17519         return true;
17520     }
17521   return false;
17522 }
17523
17524 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17525    expressions) contains any value-dependent expressions.  */
17526
17527 bool
17528 any_value_dependent_elements_p (const_tree list)
17529 {
17530   for (; list; list = TREE_CHAIN (list))
17531     if (value_dependent_expression_p (TREE_VALUE (list)))
17532       return true;
17533
17534   return false;
17535 }
17536
17537 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17538
17539 bool
17540 dependent_template_arg_p (tree arg)
17541 {
17542   if (!processing_template_decl)
17543     return false;
17544
17545   if (TREE_CODE (arg) == TEMPLATE_DECL
17546       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17547     return dependent_template_p (arg);
17548   else if (ARGUMENT_PACK_P (arg))
17549     {
17550       tree args = ARGUMENT_PACK_ARGS (arg);
17551       int i, len = TREE_VEC_LENGTH (args);
17552       for (i = 0; i < len; ++i)
17553         {
17554           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17555             return true;
17556         }
17557
17558       return false;
17559     }
17560   else if (TYPE_P (arg))
17561     return dependent_type_p (arg);
17562   else
17563     return (type_dependent_expression_p (arg)
17564             || value_dependent_expression_p (arg));
17565 }
17566
17567 /* Returns true if ARGS (a collection of template arguments) contains
17568    any types that require structural equality testing.  */
17569
17570 bool
17571 any_template_arguments_need_structural_equality_p (tree args)
17572 {
17573   int i;
17574   int j;
17575
17576   if (!args)
17577     return false;
17578   if (args == error_mark_node)
17579     return true;
17580
17581   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17582     {
17583       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17584       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17585         {
17586           tree arg = TREE_VEC_ELT (level, j);
17587           tree packed_args = NULL_TREE;
17588           int k, len = 1;
17589
17590           if (ARGUMENT_PACK_P (arg))
17591             {
17592               /* Look inside the argument pack.  */
17593               packed_args = ARGUMENT_PACK_ARGS (arg);
17594               len = TREE_VEC_LENGTH (packed_args);
17595             }
17596
17597           for (k = 0; k < len; ++k)
17598             {
17599               if (packed_args)
17600                 arg = TREE_VEC_ELT (packed_args, k);
17601
17602               if (error_operand_p (arg))
17603                 return true;
17604               else if (TREE_CODE (arg) == TEMPLATE_DECL
17605                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17606                 continue;
17607               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17608                 return true;
17609               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17610                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17611                 return true;
17612             }
17613         }
17614     }
17615
17616   return false;
17617 }
17618
17619 /* Returns true if ARGS (a collection of template arguments) contains
17620    any dependent arguments.  */
17621
17622 bool
17623 any_dependent_template_arguments_p (const_tree args)
17624 {
17625   int i;
17626   int j;
17627
17628   if (!args)
17629     return false;
17630   if (args == error_mark_node)
17631     return true;
17632
17633   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17634     {
17635       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17636       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17637         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17638           return true;
17639     }
17640
17641   return false;
17642 }
17643
17644 /* Returns TRUE if the template TMPL is dependent.  */
17645
17646 bool
17647 dependent_template_p (tree tmpl)
17648 {
17649   if (TREE_CODE (tmpl) == OVERLOAD)
17650     {
17651       while (tmpl)
17652         {
17653           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17654             return true;
17655           tmpl = OVL_CHAIN (tmpl);
17656         }
17657       return false;
17658     }
17659
17660   /* Template template parameters are dependent.  */
17661   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17662       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17663     return true;
17664   /* So are names that have not been looked up.  */
17665   if (TREE_CODE (tmpl) == SCOPE_REF
17666       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17667     return true;
17668   /* So are member templates of dependent classes.  */
17669   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17670     return dependent_type_p (DECL_CONTEXT (tmpl));
17671   return false;
17672 }
17673
17674 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17675
17676 bool
17677 dependent_template_id_p (tree tmpl, tree args)
17678 {
17679   return (dependent_template_p (tmpl)
17680           || any_dependent_template_arguments_p (args));
17681 }
17682
17683 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17684    is dependent.  */
17685
17686 bool
17687 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17688 {
17689   int i;
17690
17691   if (!processing_template_decl)
17692     return false;
17693
17694   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17695     {
17696       tree decl = TREE_VEC_ELT (declv, i);
17697       tree init = TREE_VEC_ELT (initv, i);
17698       tree cond = TREE_VEC_ELT (condv, i);
17699       tree incr = TREE_VEC_ELT (incrv, i);
17700
17701       if (type_dependent_expression_p (decl))
17702         return true;
17703
17704       if (init && type_dependent_expression_p (init))
17705         return true;
17706
17707       if (type_dependent_expression_p (cond))
17708         return true;
17709
17710       if (COMPARISON_CLASS_P (cond)
17711           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17712               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17713         return true;
17714
17715       if (TREE_CODE (incr) == MODOP_EXPR)
17716         {
17717           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17718               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17719             return true;
17720         }
17721       else if (type_dependent_expression_p (incr))
17722         return true;
17723       else if (TREE_CODE (incr) == MODIFY_EXPR)
17724         {
17725           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17726             return true;
17727           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17728             {
17729               tree t = TREE_OPERAND (incr, 1);
17730               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17731                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17732                 return true;
17733             }
17734         }
17735     }
17736
17737   return false;
17738 }
17739
17740 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17741    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17742    no such TYPE can be found.  Note that this function peers inside
17743    uninstantiated templates and therefore should be used only in
17744    extremely limited situations.  ONLY_CURRENT_P restricts this
17745    peering to the currently open classes hierarchy (which is required
17746    when comparing types).  */
17747
17748 tree
17749 resolve_typename_type (tree type, bool only_current_p)
17750 {
17751   tree scope;
17752   tree name;
17753   tree decl;
17754   int quals;
17755   tree pushed_scope;
17756   tree result;
17757
17758   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17759
17760   scope = TYPE_CONTEXT (type);
17761   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17762      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17763      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17764      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17765      identifier  of the TYPENAME_TYPE anymore.
17766      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17767      TYPENAME_TYPE instead, we avoid messing up with a possible
17768      typedef variant case.  */
17769   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17770
17771   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17772      it first before we can figure out what NAME refers to.  */
17773   if (TREE_CODE (scope) == TYPENAME_TYPE)
17774     scope = resolve_typename_type (scope, only_current_p);
17775   /* If we don't know what SCOPE refers to, then we cannot resolve the
17776      TYPENAME_TYPE.  */
17777   if (TREE_CODE (scope) == TYPENAME_TYPE)
17778     return type;
17779   /* If the SCOPE is a template type parameter, we have no way of
17780      resolving the name.  */
17781   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17782     return type;
17783   /* If the SCOPE is not the current instantiation, there's no reason
17784      to look inside it.  */
17785   if (only_current_p && !currently_open_class (scope))
17786     return type;
17787   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17788   if (typedef_variant_p (type))
17789     return type;
17790   /* If SCOPE isn't the template itself, it will not have a valid
17791      TYPE_FIELDS list.  */
17792   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17793     /* scope is either the template itself or a compatible instantiation
17794        like X<T>, so look up the name in the original template.  */
17795     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17796   else
17797     /* scope is a partial instantiation, so we can't do the lookup or we
17798        will lose the template arguments.  */
17799     return type;
17800   /* Enter the SCOPE so that name lookup will be resolved as if we
17801      were in the class definition.  In particular, SCOPE will no
17802      longer be considered a dependent type.  */
17803   pushed_scope = push_scope (scope);
17804   /* Look up the declaration.  */
17805   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17806
17807   result = NULL_TREE;
17808   
17809   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17810      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17811   if (!decl)
17812     /*nop*/;
17813   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17814            && TREE_CODE (decl) == TYPE_DECL)
17815     {
17816       result = TREE_TYPE (decl);
17817       if (result == error_mark_node)
17818         result = NULL_TREE;
17819     }
17820   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17821            && DECL_CLASS_TEMPLATE_P (decl))
17822     {
17823       tree tmpl;
17824       tree args;
17825       /* Obtain the template and the arguments.  */
17826       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17827       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17828       /* Instantiate the template.  */
17829       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17830                                       /*entering_scope=*/0,
17831                                       tf_error | tf_user);
17832       if (result == error_mark_node)
17833         result = NULL_TREE;
17834     }
17835   
17836   /* Leave the SCOPE.  */
17837   if (pushed_scope)
17838     pop_scope (pushed_scope);
17839
17840   /* If we failed to resolve it, return the original typename.  */
17841   if (!result)
17842     return type;
17843   
17844   /* If lookup found a typename type, resolve that too.  */
17845   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17846     {
17847       /* Ill-formed programs can cause infinite recursion here, so we
17848          must catch that.  */
17849       TYPENAME_IS_RESOLVING_P (type) = 1;
17850       result = resolve_typename_type (result, only_current_p);
17851       TYPENAME_IS_RESOLVING_P (type) = 0;
17852     }
17853   
17854   /* Qualify the resulting type.  */
17855   quals = cp_type_quals (type);
17856   if (quals)
17857     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17858
17859   return result;
17860 }
17861
17862 /* EXPR is an expression which is not type-dependent.  Return a proxy
17863    for EXPR that can be used to compute the types of larger
17864    expressions containing EXPR.  */
17865
17866 tree
17867 build_non_dependent_expr (tree expr)
17868 {
17869   tree inner_expr;
17870
17871   /* Preserve null pointer constants so that the type of things like
17872      "p == 0" where "p" is a pointer can be determined.  */
17873   if (null_ptr_cst_p (expr))
17874     return expr;
17875   /* Preserve OVERLOADs; the functions must be available to resolve
17876      types.  */
17877   inner_expr = expr;
17878   if (TREE_CODE (inner_expr) == STMT_EXPR)
17879     inner_expr = stmt_expr_value_expr (inner_expr);
17880   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17881     inner_expr = TREE_OPERAND (inner_expr, 0);
17882   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17883     inner_expr = TREE_OPERAND (inner_expr, 1);
17884   if (is_overloaded_fn (inner_expr)
17885       || TREE_CODE (inner_expr) == OFFSET_REF)
17886     return expr;
17887   /* There is no need to return a proxy for a variable.  */
17888   if (TREE_CODE (expr) == VAR_DECL)
17889     return expr;
17890   /* Preserve string constants; conversions from string constants to
17891      "char *" are allowed, even though normally a "const char *"
17892      cannot be used to initialize a "char *".  */
17893   if (TREE_CODE (expr) == STRING_CST)
17894     return expr;
17895   /* Preserve arithmetic constants, as an optimization -- there is no
17896      reason to create a new node.  */
17897   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17898     return expr;
17899   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17900      There is at least one place where we want to know that a
17901      particular expression is a throw-expression: when checking a ?:
17902      expression, there are special rules if the second or third
17903      argument is a throw-expression.  */
17904   if (TREE_CODE (expr) == THROW_EXPR)
17905     return expr;
17906
17907   if (TREE_CODE (expr) == COND_EXPR)
17908     return build3 (COND_EXPR,
17909                    TREE_TYPE (expr),
17910                    TREE_OPERAND (expr, 0),
17911                    (TREE_OPERAND (expr, 1)
17912                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17913                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17914                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17915   if (TREE_CODE (expr) == COMPOUND_EXPR
17916       && !COMPOUND_EXPR_OVERLOADED (expr))
17917     return build2 (COMPOUND_EXPR,
17918                    TREE_TYPE (expr),
17919                    TREE_OPERAND (expr, 0),
17920                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17921
17922   /* If the type is unknown, it can't really be non-dependent */
17923   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17924
17925   /* Otherwise, build a NON_DEPENDENT_EXPR.
17926
17927      REFERENCE_TYPEs are not stripped for expressions in templates
17928      because doing so would play havoc with mangling.  Consider, for
17929      example:
17930
17931        template <typename T> void f<T& g>() { g(); }
17932
17933      In the body of "f", the expression for "g" will have
17934      REFERENCE_TYPE, even though the standard says that it should
17935      not.  The reason is that we must preserve the syntactic form of
17936      the expression so that mangling (say) "f<g>" inside the body of
17937      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17938      stripped here.  */
17939   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17940 }
17941
17942 /* ARGS is a vector of expressions as arguments to a function call.
17943    Replace the arguments with equivalent non-dependent expressions.
17944    This modifies ARGS in place.  */
17945
17946 void
17947 make_args_non_dependent (VEC(tree,gc) *args)
17948 {
17949   unsigned int ix;
17950   tree arg;
17951
17952   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17953     {
17954       tree newarg = build_non_dependent_expr (arg);
17955       if (newarg != arg)
17956         VEC_replace (tree, args, ix, newarg);
17957     }
17958 }
17959
17960 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17961    with a level one deeper than the actual template parms.  */
17962
17963 tree
17964 make_auto (void)
17965 {
17966   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
17967   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17968                                TYPE_DECL, get_identifier ("auto"), au);
17969   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17970   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17971     (0, processing_template_decl + 1, processing_template_decl + 1,
17972      TYPE_NAME (au), NULL_TREE);
17973   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17974   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17975   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17976
17977   return au;
17978 }
17979
17980 /* Given type ARG, return std::initializer_list<ARG>.  */
17981
17982 static tree
17983 listify (tree arg)
17984 {
17985   tree std_init_list = namespace_binding
17986     (get_identifier ("initializer_list"), std_node);
17987   tree argvec;
17988   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17989     {    
17990       error ("deducing from brace-enclosed initializer list requires "
17991              "#include <initializer_list>");
17992       return error_mark_node;
17993     }
17994   argvec = make_tree_vec (1);
17995   TREE_VEC_ELT (argvec, 0) = arg;
17996   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17997                                 NULL_TREE, 0, tf_warning_or_error);
17998 }
17999
18000 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18001
18002 static tree
18003 listify_autos (tree type, tree auto_node)
18004 {
18005   tree init_auto = listify (auto_node);
18006   tree argvec = make_tree_vec (1);
18007   TREE_VEC_ELT (argvec, 0) = init_auto;
18008   if (processing_template_decl)
18009     argvec = add_to_template_args (current_template_args (), argvec);
18010   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18011 }
18012
18013 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18014    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18015
18016 tree
18017 do_auto_deduction (tree type, tree init, tree auto_node)
18018 {
18019   tree parms, tparms, targs;
18020   tree args[1];
18021   int val;
18022
18023   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18024      with either a new invented type template parameter U or, if the
18025      initializer is a braced-init-list (8.5.4), with
18026      std::initializer_list<U>.  */
18027   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18028     type = listify_autos (type, auto_node);
18029
18030   parms = build_tree_list (NULL_TREE, type);
18031   args[0] = init;
18032   tparms = make_tree_vec (1);
18033   targs = make_tree_vec (1);
18034   TREE_VEC_ELT (tparms, 0)
18035     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18036   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18037                                DEDUCE_CALL, LOOKUP_NORMAL);
18038   if (val > 0)
18039     {
18040       error ("unable to deduce %qT from %qE", type, init);
18041       return error_mark_node;
18042     }
18043
18044   /* If the list of declarators contains more than one declarator, the type
18045      of each declared variable is determined as described above. If the
18046      type deduced for the template parameter U is not the same in each
18047      deduction, the program is ill-formed.  */
18048   if (TREE_TYPE (auto_node)
18049       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18050     {
18051       error ("inconsistent deduction for %qT: %qT and then %qT",
18052              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18053       return error_mark_node;
18054     }
18055   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18056
18057   if (processing_template_decl)
18058     targs = add_to_template_args (current_template_args (), targs);
18059   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18060 }
18061
18062 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18063    result.  */
18064
18065 tree
18066 splice_late_return_type (tree type, tree late_return_type)
18067 {
18068   tree argvec;
18069
18070   if (late_return_type == NULL_TREE)
18071     return type;
18072   argvec = make_tree_vec (1);
18073   TREE_VEC_ELT (argvec, 0) = late_return_type;
18074   if (processing_template_decl)
18075     argvec = add_to_template_args (current_template_args (), argvec);
18076   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18077 }
18078
18079 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18080
18081 bool
18082 is_auto (const_tree type)
18083 {
18084   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18085       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18086     return true;
18087   else
18088     return false;
18089 }
18090
18091 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18092    appear as a type-specifier for the declaration in question, we don't
18093    have to look through the whole type.  */
18094
18095 tree
18096 type_uses_auto (tree type)
18097 {
18098   enum tree_code code;
18099   if (is_auto (type))
18100     return type;
18101
18102   code = TREE_CODE (type);
18103
18104   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18105       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18106       || code == METHOD_TYPE || code == ARRAY_TYPE)
18107     return type_uses_auto (TREE_TYPE (type));
18108
18109   if (TYPE_PTRMEMFUNC_P (type))
18110     return type_uses_auto (TREE_TYPE (TREE_TYPE
18111                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18112
18113   return NULL_TREE;
18114 }
18115
18116 /* For a given template T, return the vector of typedefs referenced
18117    in T for which access check is needed at T instantiation time.
18118    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18119    Those typedefs were added to T by the function
18120    append_type_to_template_for_access_check.  */
18121
18122 VEC(qualified_typedef_usage_t,gc)*
18123 get_types_needing_access_check (tree t)
18124 {
18125   tree ti;
18126   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18127
18128   if (!t || t == error_mark_node)
18129     return NULL;
18130
18131   if (!(ti = get_template_info (t)))
18132     return NULL;
18133
18134   if (CLASS_TYPE_P (t)
18135       || TREE_CODE (t) == FUNCTION_DECL)
18136     {
18137       if (!TI_TEMPLATE (ti))
18138         return NULL;
18139
18140       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18141     }
18142
18143   return result;
18144 }
18145
18146 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18147    tied to T. That list of typedefs will be access checked at
18148    T instantiation time.
18149    T is either a FUNCTION_DECL or a RECORD_TYPE.
18150    TYPE_DECL is a TYPE_DECL node representing a typedef.
18151    SCOPE is the scope through which TYPE_DECL is accessed.
18152    LOCATION is the location of the usage point of TYPE_DECL.
18153
18154    This function is a subroutine of
18155    append_type_to_template_for_access_check.  */
18156
18157 static void
18158 append_type_to_template_for_access_check_1 (tree t,
18159                                             tree type_decl,
18160                                             tree scope,
18161                                             location_t location)
18162 {
18163   qualified_typedef_usage_t typedef_usage;
18164   tree ti;
18165
18166   if (!t || t == error_mark_node)
18167     return;
18168
18169   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18170                || CLASS_TYPE_P (t))
18171               && type_decl
18172               && TREE_CODE (type_decl) == TYPE_DECL
18173               && scope);
18174
18175   if (!(ti = get_template_info (t)))
18176     return;
18177
18178   gcc_assert (TI_TEMPLATE (ti));
18179
18180   typedef_usage.typedef_decl = type_decl;
18181   typedef_usage.context = scope;
18182   typedef_usage.locus = location;
18183
18184   VEC_safe_push (qualified_typedef_usage_t, gc,
18185                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18186                  &typedef_usage);
18187 }
18188
18189 /* Append TYPE_DECL to the template TEMPL.
18190    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18191    At TEMPL instanciation time, TYPE_DECL will be checked to see
18192    if it can be accessed through SCOPE.
18193    LOCATION is the location of the usage point of TYPE_DECL.
18194
18195    e.g. consider the following code snippet:
18196
18197      class C
18198      {
18199        typedef int myint;
18200      };
18201
18202      template<class U> struct S
18203      {
18204        C::myint mi; // <-- usage point of the typedef C::myint
18205      };
18206
18207      S<char> s;
18208
18209    At S<char> instantiation time, we need to check the access of C::myint
18210    In other words, we need to check the access of the myint typedef through
18211    the C scope. For that purpose, this function will add the myint typedef
18212    and the scope C through which its being accessed to a list of typedefs
18213    tied to the template S. That list will be walked at template instantiation
18214    time and access check performed on each typedefs it contains.
18215    Note that this particular code snippet should yield an error because
18216    myint is private to C.  */
18217
18218 void
18219 append_type_to_template_for_access_check (tree templ,
18220                                           tree type_decl,
18221                                           tree scope,
18222                                           location_t location)
18223 {
18224   qualified_typedef_usage_t *iter;
18225   int i;
18226
18227   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18228
18229   /* Make sure we don't append the type to the template twice.  */
18230   for (i = 0;
18231        VEC_iterate (qualified_typedef_usage_t,
18232                     get_types_needing_access_check (templ),
18233                     i, iter);
18234        ++i)
18235     if (iter->typedef_decl == type_decl && scope == iter->context)
18236       return;
18237
18238   append_type_to_template_for_access_check_1 (templ, type_decl,
18239                                               scope, location);
18240 }
18241
18242 /* Set up the hash tables for template instantiations.  */
18243
18244 void
18245 init_template_processing (void)
18246 {
18247   decl_specializations = htab_create_ggc (37,
18248                                           hash_specialization,
18249                                           eq_specializations,
18250                                           ggc_free);
18251   type_specializations = htab_create_ggc (37,
18252                                           hash_specialization,
18253                                           eq_specializations,
18254                                           ggc_free);
18255 }
18256
18257 #include "gt-cp-pt.h"