OSDN Git Service

PR middle-end/42095
[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 candidate FNS in an error message.  */
1650
1651 void
1652 print_candidates (tree fns)
1653 {
1654   tree fn;
1655   tree f;
1656
1657   const char *str = "candidates are:";
1658
1659   if (is_overloaded_fn (fns))
1660     {
1661       for (f = fns; f; f = OVL_NEXT (f))
1662         {
1663           error ("%s %+#D", str, OVL_CURRENT (f));
1664           str = "               ";
1665         }
1666     }
1667   else for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1668     {
1669       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1670         error ("%s %+#D", str, OVL_CURRENT (f));
1671       str = "               ";
1672     }
1673 }
1674
1675 /* Returns the template (one of the functions given by TEMPLATE_ID)
1676    which can be specialized to match the indicated DECL with the
1677    explicit template args given in TEMPLATE_ID.  The DECL may be
1678    NULL_TREE if none is available.  In that case, the functions in
1679    TEMPLATE_ID are non-members.
1680
1681    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1682    specialization of a member template.
1683
1684    The TEMPLATE_COUNT is the number of references to qualifying
1685    template classes that appeared in the name of the function. See
1686    check_explicit_specialization for a more accurate description.
1687
1688    TSK indicates what kind of template declaration (if any) is being
1689    declared.  TSK_TEMPLATE indicates that the declaration given by
1690    DECL, though a FUNCTION_DECL, has template parameters, and is
1691    therefore a template function.
1692
1693    The template args (those explicitly specified and those deduced)
1694    are output in a newly created vector *TARGS_OUT.
1695
1696    If it is impossible to determine the result, an error message is
1697    issued.  The error_mark_node is returned to indicate failure.  */
1698
1699 static tree
1700 determine_specialization (tree template_id,
1701                           tree decl,
1702                           tree* targs_out,
1703                           int need_member_template,
1704                           int template_count,
1705                           tmpl_spec_kind tsk)
1706 {
1707   tree fns;
1708   tree targs;
1709   tree explicit_targs;
1710   tree candidates = NULL_TREE;
1711   /* A TREE_LIST of templates of which DECL may be a specialization.
1712      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1713      corresponding TREE_PURPOSE is the set of template arguments that,
1714      when used to instantiate the template, would produce a function
1715      with the signature of DECL.  */
1716   tree templates = NULL_TREE;
1717   int header_count;
1718   struct cp_binding_level *b;
1719
1720   *targs_out = NULL_TREE;
1721
1722   if (template_id == error_mark_node || decl == error_mark_node)
1723     return error_mark_node;
1724
1725   fns = TREE_OPERAND (template_id, 0);
1726   explicit_targs = TREE_OPERAND (template_id, 1);
1727
1728   if (fns == error_mark_node)
1729     return error_mark_node;
1730
1731   /* Check for baselinks.  */
1732   if (BASELINK_P (fns))
1733     fns = BASELINK_FUNCTIONS (fns);
1734
1735   if (!is_overloaded_fn (fns))
1736     {
1737       error ("%qD is not a function template", fns);
1738       return error_mark_node;
1739     }
1740
1741   /* Count the number of template headers specified for this
1742      specialization.  */
1743   header_count = 0;
1744   for (b = current_binding_level;
1745        b->kind == sk_template_parms;
1746        b = b->level_chain)
1747     ++header_count;
1748
1749   for (; fns; fns = OVL_NEXT (fns))
1750     {
1751       tree fn = OVL_CURRENT (fns);
1752
1753       if (TREE_CODE (fn) == TEMPLATE_DECL)
1754         {
1755           tree decl_arg_types;
1756           tree fn_arg_types;
1757
1758           /* In case of explicit specialization, we need to check if
1759              the number of template headers appearing in the specialization
1760              is correct. This is usually done in check_explicit_specialization,
1761              but the check done there cannot be exhaustive when specializing
1762              member functions. Consider the following code:
1763
1764              template <> void A<int>::f(int);
1765              template <> template <> void A<int>::f(int);
1766
1767              Assuming that A<int> is not itself an explicit specialization
1768              already, the first line specializes "f" which is a non-template
1769              member function, whilst the second line specializes "f" which
1770              is a template member function. So both lines are syntactically
1771              correct, and check_explicit_specialization does not reject
1772              them.
1773
1774              Here, we can do better, as we are matching the specialization
1775              against the declarations. We count the number of template
1776              headers, and we check if they match TEMPLATE_COUNT + 1
1777              (TEMPLATE_COUNT is the number of qualifying template classes,
1778              plus there must be another header for the member template
1779              itself).
1780
1781              Notice that if header_count is zero, this is not a
1782              specialization but rather a template instantiation, so there
1783              is no check we can perform here.  */
1784           if (header_count && header_count != template_count + 1)
1785             continue;
1786
1787           /* Check that the number of template arguments at the
1788              innermost level for DECL is the same as for FN.  */
1789           if (current_binding_level->kind == sk_template_parms
1790               && !current_binding_level->explicit_spec_p
1791               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1792                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1793                                       (current_template_parms))))
1794             continue;
1795
1796           /* DECL might be a specialization of FN.  */
1797           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1798           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1799
1800           /* For a non-static member function, we need to make sure
1801              that the const qualification is the same.  Since
1802              get_bindings does not try to merge the "this" parameter,
1803              we must do the comparison explicitly.  */
1804           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1805               && !same_type_p (TREE_VALUE (fn_arg_types),
1806                                TREE_VALUE (decl_arg_types)))
1807             continue;
1808
1809           /* Skip the "this" parameter and, for constructors of
1810              classes with virtual bases, the VTT parameter.  A
1811              full specialization of a constructor will have a VTT
1812              parameter, but a template never will.  */ 
1813           decl_arg_types 
1814             = skip_artificial_parms_for (decl, decl_arg_types);
1815           fn_arg_types 
1816             = skip_artificial_parms_for (fn, fn_arg_types);
1817
1818           /* Check that the number of function parameters matches.
1819              For example,
1820                template <class T> void f(int i = 0);
1821                template <> void f<int>();
1822              The specialization f<int> is invalid but is not caught
1823              by get_bindings below.  */
1824           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1825             continue;
1826
1827           /* Function templates cannot be specializations; there are
1828              no partial specializations of functions.  Therefore, if
1829              the type of DECL does not match FN, there is no
1830              match.  */
1831           if (tsk == tsk_template)
1832             {
1833               if (compparms (fn_arg_types, decl_arg_types))
1834                 candidates = tree_cons (NULL_TREE, fn, candidates);
1835               continue;
1836             }
1837
1838           /* See whether this function might be a specialization of this
1839              template.  */
1840           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1841
1842           if (!targs)
1843             /* We cannot deduce template arguments that when used to
1844                specialize TMPL will produce DECL.  */
1845             continue;
1846
1847           /* Save this template, and the arguments deduced.  */
1848           templates = tree_cons (targs, fn, templates);
1849         }
1850       else if (need_member_template)
1851         /* FN is an ordinary member function, and we need a
1852            specialization of a member template.  */
1853         ;
1854       else if (TREE_CODE (fn) != FUNCTION_DECL)
1855         /* We can get IDENTIFIER_NODEs here in certain erroneous
1856            cases.  */
1857         ;
1858       else if (!DECL_FUNCTION_MEMBER_P (fn))
1859         /* This is just an ordinary non-member function.  Nothing can
1860            be a specialization of that.  */
1861         ;
1862       else if (DECL_ARTIFICIAL (fn))
1863         /* Cannot specialize functions that are created implicitly.  */
1864         ;
1865       else
1866         {
1867           tree decl_arg_types;
1868
1869           /* This is an ordinary member function.  However, since
1870              we're here, we can assume it's enclosing class is a
1871              template class.  For example,
1872
1873                template <typename T> struct S { void f(); };
1874                template <> void S<int>::f() {}
1875
1876              Here, S<int>::f is a non-template, but S<int> is a
1877              template class.  If FN has the same type as DECL, we
1878              might be in business.  */
1879
1880           if (!DECL_TEMPLATE_INFO (fn))
1881             /* Its enclosing class is an explicit specialization
1882                of a template class.  This is not a candidate.  */
1883             continue;
1884
1885           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1886                             TREE_TYPE (TREE_TYPE (fn))))
1887             /* The return types differ.  */
1888             continue;
1889
1890           /* Adjust the type of DECL in case FN is a static member.  */
1891           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1892           if (DECL_STATIC_FUNCTION_P (fn)
1893               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1894             decl_arg_types = TREE_CHAIN (decl_arg_types);
1895
1896           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1897                          decl_arg_types))
1898             /* They match!  */
1899             candidates = tree_cons (NULL_TREE, fn, candidates);
1900         }
1901     }
1902
1903   if (templates && TREE_CHAIN (templates))
1904     {
1905       /* We have:
1906
1907            [temp.expl.spec]
1908
1909            It is possible for a specialization with a given function
1910            signature to be instantiated from more than one function
1911            template.  In such cases, explicit specification of the
1912            template arguments must be used to uniquely identify the
1913            function template specialization being specialized.
1914
1915          Note that here, there's no suggestion that we're supposed to
1916          determine which of the candidate templates is most
1917          specialized.  However, we, also have:
1918
1919            [temp.func.order]
1920
1921            Partial ordering of overloaded function template
1922            declarations is used in the following contexts to select
1923            the function template to which a function template
1924            specialization refers:
1925
1926            -- when an explicit specialization refers to a function
1927               template.
1928
1929          So, we do use the partial ordering rules, at least for now.
1930          This extension can only serve to make invalid programs valid,
1931          so it's safe.  And, there is strong anecdotal evidence that
1932          the committee intended the partial ordering rules to apply;
1933          the EDG front end has that behavior, and John Spicer claims
1934          that the committee simply forgot to delete the wording in
1935          [temp.expl.spec].  */
1936       tree tmpl = most_specialized_instantiation (templates);
1937       if (tmpl != error_mark_node)
1938         {
1939           templates = tmpl;
1940           TREE_CHAIN (templates) = NULL_TREE;
1941         }
1942     }
1943
1944   if (templates == NULL_TREE && candidates == NULL_TREE)
1945     {
1946       error ("template-id %qD for %q+D does not match any template "
1947              "declaration", template_id, decl);
1948       return error_mark_node;
1949     }
1950   else if ((templates && TREE_CHAIN (templates))
1951            || (candidates && TREE_CHAIN (candidates))
1952            || (templates && candidates))
1953     {
1954       error ("ambiguous template specialization %qD for %q+D",
1955              template_id, decl);
1956       candidates = chainon (candidates, templates);
1957       print_candidates (candidates);
1958       return error_mark_node;
1959     }
1960
1961   /* We have one, and exactly one, match.  */
1962   if (candidates)
1963     {
1964       tree fn = TREE_VALUE (candidates);
1965       *targs_out = copy_node (DECL_TI_ARGS (fn));
1966       /* DECL is a re-declaration or partial instantiation of a template
1967          function.  */
1968       if (TREE_CODE (fn) == TEMPLATE_DECL)
1969         return fn;
1970       /* It was a specialization of an ordinary member function in a
1971          template class.  */
1972       return DECL_TI_TEMPLATE (fn);
1973     }
1974
1975   /* It was a specialization of a template.  */
1976   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1977   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1978     {
1979       *targs_out = copy_node (targs);
1980       SET_TMPL_ARGS_LEVEL (*targs_out,
1981                            TMPL_ARGS_DEPTH (*targs_out),
1982                            TREE_PURPOSE (templates));
1983     }
1984   else
1985     *targs_out = TREE_PURPOSE (templates);
1986   return TREE_VALUE (templates);
1987 }
1988
1989 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1990    but with the default argument values filled in from those in the
1991    TMPL_TYPES.  */
1992
1993 static tree
1994 copy_default_args_to_explicit_spec_1 (tree spec_types,
1995                                       tree tmpl_types)
1996 {
1997   tree new_spec_types;
1998
1999   if (!spec_types)
2000     return NULL_TREE;
2001
2002   if (spec_types == void_list_node)
2003     return void_list_node;
2004
2005   /* Substitute into the rest of the list.  */
2006   new_spec_types =
2007     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2008                                           TREE_CHAIN (tmpl_types));
2009
2010   /* Add the default argument for this parameter.  */
2011   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2012                          TREE_VALUE (spec_types),
2013                          new_spec_types);
2014 }
2015
2016 /* DECL is an explicit specialization.  Replicate default arguments
2017    from the template it specializes.  (That way, code like:
2018
2019      template <class T> void f(T = 3);
2020      template <> void f(double);
2021      void g () { f (); }
2022
2023    works, as required.)  An alternative approach would be to look up
2024    the correct default arguments at the call-site, but this approach
2025    is consistent with how implicit instantiations are handled.  */
2026
2027 static void
2028 copy_default_args_to_explicit_spec (tree decl)
2029 {
2030   tree tmpl;
2031   tree spec_types;
2032   tree tmpl_types;
2033   tree new_spec_types;
2034   tree old_type;
2035   tree new_type;
2036   tree t;
2037   tree object_type = NULL_TREE;
2038   tree in_charge = NULL_TREE;
2039   tree vtt = NULL_TREE;
2040
2041   /* See if there's anything we need to do.  */
2042   tmpl = DECL_TI_TEMPLATE (decl);
2043   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2044   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2045     if (TREE_PURPOSE (t))
2046       break;
2047   if (!t)
2048     return;
2049
2050   old_type = TREE_TYPE (decl);
2051   spec_types = TYPE_ARG_TYPES (old_type);
2052
2053   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2054     {
2055       /* Remove the this pointer, but remember the object's type for
2056          CV quals.  */
2057       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2058       spec_types = TREE_CHAIN (spec_types);
2059       tmpl_types = TREE_CHAIN (tmpl_types);
2060
2061       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2062         {
2063           /* DECL may contain more parameters than TMPL due to the extra
2064              in-charge parameter in constructors and destructors.  */
2065           in_charge = spec_types;
2066           spec_types = TREE_CHAIN (spec_types);
2067         }
2068       if (DECL_HAS_VTT_PARM_P (decl))
2069         {
2070           vtt = spec_types;
2071           spec_types = TREE_CHAIN (spec_types);
2072         }
2073     }
2074
2075   /* Compute the merged default arguments.  */
2076   new_spec_types =
2077     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2078
2079   /* Compute the new FUNCTION_TYPE.  */
2080   if (object_type)
2081     {
2082       if (vtt)
2083         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2084                                          TREE_VALUE (vtt),
2085                                          new_spec_types);
2086
2087       if (in_charge)
2088         /* Put the in-charge parameter back.  */
2089         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2090                                          TREE_VALUE (in_charge),
2091                                          new_spec_types);
2092
2093       new_type = build_method_type_directly (object_type,
2094                                              TREE_TYPE (old_type),
2095                                              new_spec_types);
2096     }
2097   else
2098     new_type = build_function_type (TREE_TYPE (old_type),
2099                                     new_spec_types);
2100   new_type = cp_build_type_attribute_variant (new_type,
2101                                               TYPE_ATTRIBUTES (old_type));
2102   new_type = build_exception_variant (new_type,
2103                                       TYPE_RAISES_EXCEPTIONS (old_type));
2104   TREE_TYPE (decl) = new_type;
2105 }
2106
2107 /* Check to see if the function just declared, as indicated in
2108    DECLARATOR, and in DECL, is a specialization of a function
2109    template.  We may also discover that the declaration is an explicit
2110    instantiation at this point.
2111
2112    Returns DECL, or an equivalent declaration that should be used
2113    instead if all goes well.  Issues an error message if something is
2114    amiss.  Returns error_mark_node if the error is not easily
2115    recoverable.
2116
2117    FLAGS is a bitmask consisting of the following flags:
2118
2119    2: The function has a definition.
2120    4: The function is a friend.
2121
2122    The TEMPLATE_COUNT is the number of references to qualifying
2123    template classes that appeared in the name of the function.  For
2124    example, in
2125
2126      template <class T> struct S { void f(); };
2127      void S<int>::f();
2128
2129    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2130    classes are not counted in the TEMPLATE_COUNT, so that in
2131
2132      template <class T> struct S {};
2133      template <> struct S<int> { void f(); }
2134      template <> void S<int>::f();
2135
2136    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2137    invalid; there should be no template <>.)
2138
2139    If the function is a specialization, it is marked as such via
2140    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2141    is set up correctly, and it is added to the list of specializations
2142    for that template.  */
2143
2144 tree
2145 check_explicit_specialization (tree declarator,
2146                                tree decl,
2147                                int template_count,
2148                                int flags)
2149 {
2150   int have_def = flags & 2;
2151   int is_friend = flags & 4;
2152   int specialization = 0;
2153   int explicit_instantiation = 0;
2154   int member_specialization = 0;
2155   tree ctype = DECL_CLASS_CONTEXT (decl);
2156   tree dname = DECL_NAME (decl);
2157   tmpl_spec_kind tsk;
2158
2159   if (is_friend)
2160     {
2161       if (!processing_specialization)
2162         tsk = tsk_none;
2163       else
2164         tsk = tsk_excessive_parms;
2165     }
2166   else
2167     tsk = current_tmpl_spec_kind (template_count);
2168
2169   switch (tsk)
2170     {
2171     case tsk_none:
2172       if (processing_specialization)
2173         {
2174           specialization = 1;
2175           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2176         }
2177       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2178         {
2179           if (is_friend)
2180             /* This could be something like:
2181
2182                template <class T> void f(T);
2183                class S { friend void f<>(int); }  */
2184             specialization = 1;
2185           else
2186             {
2187               /* This case handles bogus declarations like template <>
2188                  template <class T> void f<int>(); */
2189
2190               error ("template-id %qD in declaration of primary template",
2191                      declarator);
2192               return decl;
2193             }
2194         }
2195       break;
2196
2197     case tsk_invalid_member_spec:
2198       /* The error has already been reported in
2199          check_specialization_scope.  */
2200       return error_mark_node;
2201
2202     case tsk_invalid_expl_inst:
2203       error ("template parameter list used in explicit instantiation");
2204
2205       /* Fall through.  */
2206
2207     case tsk_expl_inst:
2208       if (have_def)
2209         error ("definition provided for explicit instantiation");
2210
2211       explicit_instantiation = 1;
2212       break;
2213
2214     case tsk_excessive_parms:
2215     case tsk_insufficient_parms:
2216       if (tsk == tsk_excessive_parms)
2217         error ("too many template parameter lists in declaration of %qD",
2218                decl);
2219       else if (template_header_count)
2220         error("too few template parameter lists in declaration of %qD", decl);
2221       else
2222         error("explicit specialization of %qD must be introduced by "
2223               "%<template <>%>", decl);
2224
2225       /* Fall through.  */
2226     case tsk_expl_spec:
2227       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2228       if (ctype)
2229         member_specialization = 1;
2230       else
2231         specialization = 1;
2232       break;
2233
2234     case tsk_template:
2235       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2236         {
2237           /* This case handles bogus declarations like template <>
2238              template <class T> void f<int>(); */
2239
2240           if (uses_template_parms (declarator))
2241             error ("function template partial specialization %qD "
2242                    "is not allowed", declarator);
2243           else
2244             error ("template-id %qD in declaration of primary template",
2245                    declarator);
2246           return decl;
2247         }
2248
2249       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2250         /* This is a specialization of a member template, without
2251            specialization the containing class.  Something like:
2252
2253              template <class T> struct S {
2254                template <class U> void f (U);
2255              };
2256              template <> template <class U> void S<int>::f(U) {}
2257
2258            That's a specialization -- but of the entire template.  */
2259         specialization = 1;
2260       break;
2261
2262     default:
2263       gcc_unreachable ();
2264     }
2265
2266   if (specialization || member_specialization)
2267     {
2268       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2269       for (; t; t = TREE_CHAIN (t))
2270         if (TREE_PURPOSE (t))
2271           {
2272             permerror (input_location, 
2273                        "default argument specified in explicit specialization");
2274             break;
2275           }
2276     }
2277
2278   if (specialization || member_specialization || explicit_instantiation)
2279     {
2280       tree tmpl = NULL_TREE;
2281       tree targs = NULL_TREE;
2282
2283       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2284       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2285         {
2286           tree fns;
2287
2288           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2289           if (ctype)
2290             fns = dname;
2291           else
2292             {
2293               /* If there is no class context, the explicit instantiation
2294                  must be at namespace scope.  */
2295               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2296
2297               /* Find the namespace binding, using the declaration
2298                  context.  */
2299               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2300                                            false, true);
2301               if (fns == error_mark_node || !is_overloaded_fn (fns))
2302                 {
2303                   error ("%qD is not a template function", dname);
2304                   fns = error_mark_node;
2305                 }
2306               else
2307                 {
2308                   tree fn = OVL_CURRENT (fns);
2309                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2310                                                 CP_DECL_CONTEXT (fn)))
2311                     error ("%qD is not declared in %qD",
2312                            decl, current_namespace);
2313                 }
2314             }
2315
2316           declarator = lookup_template_function (fns, NULL_TREE);
2317         }
2318
2319       if (declarator == error_mark_node)
2320         return error_mark_node;
2321
2322       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2323         {
2324           if (!explicit_instantiation)
2325             /* A specialization in class scope.  This is invalid,
2326                but the error will already have been flagged by
2327                check_specialization_scope.  */
2328             return error_mark_node;
2329           else
2330             {
2331               /* It's not valid to write an explicit instantiation in
2332                  class scope, e.g.:
2333
2334                    class C { template void f(); }
2335
2336                    This case is caught by the parser.  However, on
2337                    something like:
2338
2339                    template class C { void f(); };
2340
2341                    (which is invalid) we can get here.  The error will be
2342                    issued later.  */
2343               ;
2344             }
2345
2346           return decl;
2347         }
2348       else if (ctype != NULL_TREE
2349                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2350                    IDENTIFIER_NODE))
2351         {
2352           /* Find the list of functions in ctype that have the same
2353              name as the declared function.  */
2354           tree name = TREE_OPERAND (declarator, 0);
2355           tree fns = NULL_TREE;
2356           int idx;
2357
2358           if (constructor_name_p (name, ctype))
2359             {
2360               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2361
2362               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2363                   : !CLASSTYPE_DESTRUCTORS (ctype))
2364                 {
2365                   /* From [temp.expl.spec]:
2366
2367                      If such an explicit specialization for the member
2368                      of a class template names an implicitly-declared
2369                      special member function (clause _special_), the
2370                      program is ill-formed.
2371
2372                      Similar language is found in [temp.explicit].  */
2373                   error ("specialization of implicitly-declared special member function");
2374                   return error_mark_node;
2375                 }
2376
2377               name = is_constructor ? ctor_identifier : dtor_identifier;
2378             }
2379
2380           if (!DECL_CONV_FN_P (decl))
2381             {
2382               idx = lookup_fnfields_1 (ctype, name);
2383               if (idx >= 0)
2384                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2385             }
2386           else
2387             {
2388               VEC(tree,gc) *methods;
2389               tree ovl;
2390
2391               /* For a type-conversion operator, we cannot do a
2392                  name-based lookup.  We might be looking for `operator
2393                  int' which will be a specialization of `operator T'.
2394                  So, we find *all* the conversion operators, and then
2395                  select from them.  */
2396               fns = NULL_TREE;
2397
2398               methods = CLASSTYPE_METHOD_VEC (ctype);
2399               if (methods)
2400                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2401                      VEC_iterate (tree, methods, idx, ovl);
2402                      ++idx)
2403                   {
2404                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2405                       /* There are no more conversion functions.  */
2406                       break;
2407
2408                     /* Glue all these conversion functions together
2409                        with those we already have.  */
2410                     for (; ovl; ovl = OVL_NEXT (ovl))
2411                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2412                   }
2413             }
2414
2415           if (fns == NULL_TREE)
2416             {
2417               error ("no member function %qD declared in %qT", name, ctype);
2418               return error_mark_node;
2419             }
2420           else
2421             TREE_OPERAND (declarator, 0) = fns;
2422         }
2423
2424       /* Figure out what exactly is being specialized at this point.
2425          Note that for an explicit instantiation, even one for a
2426          member function, we cannot tell apriori whether the
2427          instantiation is for a member template, or just a member
2428          function of a template class.  Even if a member template is
2429          being instantiated, the member template arguments may be
2430          elided if they can be deduced from the rest of the
2431          declaration.  */
2432       tmpl = determine_specialization (declarator, decl,
2433                                        &targs,
2434                                        member_specialization,
2435                                        template_count,
2436                                        tsk);
2437
2438       if (!tmpl || tmpl == error_mark_node)
2439         /* We couldn't figure out what this declaration was
2440            specializing.  */
2441         return error_mark_node;
2442       else
2443         {
2444           tree gen_tmpl = most_general_template (tmpl);
2445
2446           if (explicit_instantiation)
2447             {
2448               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2449                  is done by do_decl_instantiation later.  */
2450
2451               int arg_depth = TMPL_ARGS_DEPTH (targs);
2452               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2453
2454               if (arg_depth > parm_depth)
2455                 {
2456                   /* If TMPL is not the most general template (for
2457                      example, if TMPL is a friend template that is
2458                      injected into namespace scope), then there will
2459                      be too many levels of TARGS.  Remove some of them
2460                      here.  */
2461                   int i;
2462                   tree new_targs;
2463
2464                   new_targs = make_tree_vec (parm_depth);
2465                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2466                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2467                       = TREE_VEC_ELT (targs, i);
2468                   targs = new_targs;
2469                 }
2470
2471               return instantiate_template (tmpl, targs, tf_error);
2472             }
2473
2474           /* If we thought that the DECL was a member function, but it
2475              turns out to be specializing a static member function,
2476              make DECL a static member function as well.  */
2477           if (DECL_STATIC_FUNCTION_P (tmpl)
2478               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2479             revert_static_member_fn (decl);
2480
2481           /* If this is a specialization of a member template of a
2482              template class, we want to return the TEMPLATE_DECL, not
2483              the specialization of it.  */
2484           if (tsk == tsk_template)
2485             {
2486               tree result = DECL_TEMPLATE_RESULT (tmpl);
2487               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2488               DECL_INITIAL (result) = NULL_TREE;
2489               if (have_def)
2490                 {
2491                   tree parm;
2492                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2493                   DECL_SOURCE_LOCATION (result)
2494                     = DECL_SOURCE_LOCATION (decl);
2495                   /* We want to use the argument list specified in the
2496                      definition, not in the original declaration.  */
2497                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2498                   for (parm = DECL_ARGUMENTS (result); parm;
2499                        parm = TREE_CHAIN (parm))
2500                     DECL_CONTEXT (parm) = result;
2501                 }
2502               return register_specialization (tmpl, gen_tmpl, targs,
2503                                               is_friend, 0);
2504             }
2505
2506           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2507           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2508
2509           /* Inherit default function arguments from the template
2510              DECL is specializing.  */
2511           copy_default_args_to_explicit_spec (decl);
2512
2513           /* This specialization has the same protection as the
2514              template it specializes.  */
2515           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2516           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2517
2518           /* 7.1.1-1 [dcl.stc]
2519
2520              A storage-class-specifier shall not be specified in an
2521              explicit specialization...
2522
2523              The parser rejects these, so unless action is taken here,
2524              explicit function specializations will always appear with
2525              global linkage.
2526
2527              The action recommended by the C++ CWG in response to C++
2528              defect report 605 is to make the storage class and linkage
2529              of the explicit specialization match the templated function:
2530
2531              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2532            */
2533           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2534             {
2535               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2536               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2537
2538               /* This specialization has the same linkage and visibility as
2539                  the function template it specializes.  */
2540               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2541               if (! TREE_PUBLIC (decl))
2542                 {
2543                   DECL_INTERFACE_KNOWN (decl) = 1;
2544                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2545                 }
2546               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2547               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2548                 {
2549                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2550                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2551                 }
2552             }
2553
2554           /* If DECL is a friend declaration, declared using an
2555              unqualified name, the namespace associated with DECL may
2556              have been set incorrectly.  For example, in:
2557
2558                template <typename T> void f(T);
2559                namespace N {
2560                  struct S { friend void f<int>(int); }
2561                }
2562
2563              we will have set the DECL_CONTEXT for the friend
2564              declaration to N, rather than to the global namespace.  */
2565           if (DECL_NAMESPACE_SCOPE_P (decl))
2566             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2567
2568           if (is_friend && !have_def)
2569             /* This is not really a declaration of a specialization.
2570                It's just the name of an instantiation.  But, it's not
2571                a request for an instantiation, either.  */
2572             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2573           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2574             /* This is indeed a specialization.  In case of constructors
2575                and destructors, we need in-charge and not-in-charge
2576                versions in V3 ABI.  */
2577             clone_function_decl (decl, /*update_method_vec_p=*/0);
2578
2579           /* Register this specialization so that we can find it
2580              again.  */
2581           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2582         }
2583     }
2584
2585   return decl;
2586 }
2587
2588 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2589    parameters.  These are represented in the same format used for
2590    DECL_TEMPLATE_PARMS.  */
2591
2592 int
2593 comp_template_parms (const_tree parms1, const_tree parms2)
2594 {
2595   const_tree p1;
2596   const_tree p2;
2597
2598   if (parms1 == parms2)
2599     return 1;
2600
2601   for (p1 = parms1, p2 = parms2;
2602        p1 != NULL_TREE && p2 != NULL_TREE;
2603        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2604     {
2605       tree t1 = TREE_VALUE (p1);
2606       tree t2 = TREE_VALUE (p2);
2607       int i;
2608
2609       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2610       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2611
2612       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2613         return 0;
2614
2615       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2616         {
2617           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2618           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2619
2620           /* If either of the template parameters are invalid, assume
2621              they match for the sake of error recovery. */
2622           if (parm1 == error_mark_node || parm2 == error_mark_node)
2623             return 1;
2624
2625           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2626             return 0;
2627
2628           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2629               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2630                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2631             continue;
2632           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2633             return 0;
2634         }
2635     }
2636
2637   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2638     /* One set of parameters has more parameters lists than the
2639        other.  */
2640     return 0;
2641
2642   return 1;
2643 }
2644
2645 /* Determine whether PARM is a parameter pack.  */
2646
2647 bool 
2648 template_parameter_pack_p (const_tree parm)
2649 {
2650   /* Determine if we have a non-type template parameter pack.  */
2651   if (TREE_CODE (parm) == PARM_DECL)
2652     return (DECL_TEMPLATE_PARM_P (parm) 
2653             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2654
2655   /* If this is a list of template parameters, we could get a
2656      TYPE_DECL or a TEMPLATE_DECL.  */ 
2657   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2658     parm = TREE_TYPE (parm);
2659
2660   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2661            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2662           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2663 }
2664
2665 /* Determine if T is a function parameter pack.  */
2666
2667 bool
2668 function_parameter_pack_p (const_tree t)
2669 {
2670   if (t && TREE_CODE (t) == PARM_DECL)
2671     return FUNCTION_PARAMETER_PACK_P (t);
2672   return false;
2673 }
2674
2675 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2676    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2677
2678 tree
2679 get_function_template_decl (const_tree primary_func_tmpl_inst)
2680 {
2681   if (! primary_func_tmpl_inst
2682       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2683       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2684     return NULL;
2685
2686   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2687 }
2688
2689 /* Return true iff the function parameter PARAM_DECL was expanded
2690    from the function parameter pack PACK.  */
2691
2692 bool
2693 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2694 {
2695     if (DECL_ARTIFICIAL (param_decl)
2696         || !function_parameter_pack_p (pack))
2697       return false;
2698
2699     gcc_assert (DECL_NAME (param_decl) && DECL_NAME (pack));
2700
2701     /* The parameter pack and its pack arguments have the same
2702        DECL_PARM_INDEX.  */
2703     return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2704 }
2705
2706 /* Determine whether ARGS describes a variadic template args list,
2707    i.e., one that is terminated by a template argument pack.  */
2708
2709 static bool 
2710 template_args_variadic_p (tree args)
2711 {
2712   int nargs;
2713   tree last_parm;
2714
2715   if (args == NULL_TREE)
2716     return false;
2717
2718   args = INNERMOST_TEMPLATE_ARGS (args);
2719   nargs = TREE_VEC_LENGTH (args);
2720
2721   if (nargs == 0)
2722     return false;
2723
2724   last_parm = TREE_VEC_ELT (args, nargs - 1);
2725
2726   return ARGUMENT_PACK_P (last_parm);
2727 }
2728
2729 /* Generate a new name for the parameter pack name NAME (an
2730    IDENTIFIER_NODE) that incorporates its */
2731
2732 static tree
2733 make_ith_pack_parameter_name (tree name, int i)
2734 {
2735   /* Munge the name to include the parameter index.  */
2736 #define NUMBUF_LEN 128
2737   char numbuf[NUMBUF_LEN];
2738   char* newname;
2739   int newname_len;
2740
2741   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2742   newname_len = IDENTIFIER_LENGTH (name)
2743                 + strlen (numbuf) + 2;
2744   newname = (char*)alloca (newname_len);
2745   snprintf (newname, newname_len,
2746             "%s#%i", IDENTIFIER_POINTER (name), i);
2747   return get_identifier (newname);
2748 }
2749
2750 /* Return true if T is a primary function
2751    or class template instantiation.  */
2752
2753 bool
2754 primary_template_instantiation_p (const_tree t)
2755 {
2756   if (!t)
2757     return false;
2758
2759   if (TREE_CODE (t) == FUNCTION_DECL)
2760     return DECL_LANG_SPECIFIC (t)
2761            && DECL_TEMPLATE_INSTANTIATION (t)
2762            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2763   else if (CLASS_TYPE_P (t))
2764     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2765            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2766   return false;
2767 }
2768
2769 /* Return true if PARM is a template template parameter.  */
2770
2771 bool
2772 template_template_parameter_p (const_tree parm)
2773 {
2774   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2775 }
2776
2777 /* Return the template parameters of T if T is a
2778    primary template instantiation, NULL otherwise.  */
2779
2780 tree
2781 get_primary_template_innermost_parameters (const_tree t)
2782 {
2783   tree parms = NULL, template_info = NULL;
2784
2785   if ((template_info = get_template_info (t))
2786       && primary_template_instantiation_p (t))
2787     parms = INNERMOST_TEMPLATE_PARMS
2788         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2789
2790   return parms;
2791 }
2792
2793 /* Returns the template arguments of T if T is a template instantiation,
2794    NULL otherwise.  */
2795
2796 tree
2797 get_template_innermost_arguments (const_tree t)
2798 {
2799   tree args = NULL, template_info = NULL;
2800
2801   if ((template_info = get_template_info (t))
2802       && TI_ARGS (template_info))
2803     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2804
2805   return args;
2806 }
2807
2808 /* Return the argument pack elements of T if T is a template argument pack,
2809    NULL otherwise.  */
2810
2811 tree
2812 get_template_argument_pack_elems (const_tree t)
2813 {
2814   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2815       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2816     return NULL;
2817
2818   return ARGUMENT_PACK_ARGS (t);
2819 }
2820
2821 /* Structure used to track the progress of find_parameter_packs_r.  */
2822 struct find_parameter_pack_data 
2823 {
2824   /* TREE_LIST that will contain all of the parameter packs found by
2825      the traversal.  */
2826   tree* parameter_packs;
2827
2828   /* Set of AST nodes that have been visited by the traversal.  */
2829   struct pointer_set_t *visited;
2830 };
2831
2832 /* Identifies all of the argument packs that occur in a template
2833    argument and appends them to the TREE_LIST inside DATA, which is a
2834    find_parameter_pack_data structure. This is a subroutine of
2835    make_pack_expansion and uses_parameter_packs.  */
2836 static tree
2837 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2838 {
2839   tree t = *tp;
2840   struct find_parameter_pack_data* ppd = 
2841     (struct find_parameter_pack_data*)data;
2842   bool parameter_pack_p = false;
2843
2844   /* Identify whether this is a parameter pack or not.  */
2845   switch (TREE_CODE (t))
2846     {
2847     case TEMPLATE_PARM_INDEX:
2848       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2849         parameter_pack_p = true;
2850       break;
2851
2852     case TEMPLATE_TYPE_PARM:
2853     case TEMPLATE_TEMPLATE_PARM:
2854       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2855         parameter_pack_p = true;
2856       break;
2857
2858     case PARM_DECL:
2859       if (FUNCTION_PARAMETER_PACK_P (t))
2860         {
2861           /* We don't want to walk into the type of a PARM_DECL,
2862              because we don't want to see the type parameter pack.  */
2863           *walk_subtrees = 0;
2864           parameter_pack_p = true;
2865         }
2866       break;
2867
2868     default:
2869       /* Not a parameter pack.  */
2870       break;
2871     }
2872
2873   if (parameter_pack_p)
2874     {
2875       /* Add this parameter pack to the list.  */
2876       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2877     }
2878
2879   if (TYPE_P (t))
2880     cp_walk_tree (&TYPE_CONTEXT (t), 
2881                   &find_parameter_packs_r, ppd, ppd->visited);
2882
2883   /* This switch statement will return immediately if we don't find a
2884      parameter pack.  */
2885   switch (TREE_CODE (t)) 
2886     {
2887     case TEMPLATE_PARM_INDEX:
2888       return NULL_TREE;
2889
2890     case BOUND_TEMPLATE_TEMPLATE_PARM:
2891       /* Check the template itself.  */
2892       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2893                     &find_parameter_packs_r, ppd, ppd->visited);
2894       /* Check the template arguments.  */
2895       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2896                     ppd->visited);
2897       *walk_subtrees = 0;
2898       return NULL_TREE;
2899
2900     case TEMPLATE_TYPE_PARM:
2901     case TEMPLATE_TEMPLATE_PARM:
2902       return NULL_TREE;
2903
2904     case PARM_DECL:
2905       return NULL_TREE;
2906
2907     case RECORD_TYPE:
2908       if (TYPE_PTRMEMFUNC_P (t))
2909         return NULL_TREE;
2910       /* Fall through.  */
2911
2912     case UNION_TYPE:
2913     case ENUMERAL_TYPE:
2914       if (TYPE_TEMPLATE_INFO (t))
2915         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2916                       &find_parameter_packs_r, ppd, ppd->visited);
2917
2918       *walk_subtrees = 0;
2919       return NULL_TREE;
2920
2921     case TEMPLATE_DECL:
2922       cp_walk_tree (&TREE_TYPE (t),
2923                     &find_parameter_packs_r, ppd, ppd->visited);
2924       return NULL_TREE;
2925  
2926     case TYPENAME_TYPE:
2927       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2928                    ppd, ppd->visited);
2929       *walk_subtrees = 0;
2930       return NULL_TREE;
2931       
2932     case TYPE_PACK_EXPANSION:
2933     case EXPR_PACK_EXPANSION:
2934       *walk_subtrees = 0;
2935       return NULL_TREE;
2936
2937     case INTEGER_TYPE:
2938       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2939                     ppd, ppd->visited);
2940       *walk_subtrees = 0;
2941       return NULL_TREE;
2942
2943     case IDENTIFIER_NODE:
2944       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2945                     ppd->visited);
2946       *walk_subtrees = 0;
2947       return NULL_TREE;
2948
2949     default:
2950       return NULL_TREE;
2951     }
2952
2953   return NULL_TREE;
2954 }
2955
2956 /* Determines if the expression or type T uses any parameter packs.  */
2957 bool
2958 uses_parameter_packs (tree t)
2959 {
2960   tree parameter_packs = NULL_TREE;
2961   struct find_parameter_pack_data ppd;
2962   ppd.parameter_packs = &parameter_packs;
2963   ppd.visited = pointer_set_create ();
2964   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2965   pointer_set_destroy (ppd.visited);
2966   return parameter_packs != NULL_TREE;
2967 }
2968
2969 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2970    representation a base-class initializer into a parameter pack
2971    expansion. If all goes well, the resulting node will be an
2972    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2973    respectively.  */
2974 tree 
2975 make_pack_expansion (tree arg)
2976 {
2977   tree result;
2978   tree parameter_packs = NULL_TREE;
2979   bool for_types = false;
2980   struct find_parameter_pack_data ppd;
2981
2982   if (!arg || arg == error_mark_node)
2983     return arg;
2984
2985   if (TREE_CODE (arg) == TREE_LIST)
2986     {
2987       /* The only time we will see a TREE_LIST here is for a base
2988          class initializer.  In this case, the TREE_PURPOSE will be a
2989          _TYPE node (representing the base class expansion we're
2990          initializing) and the TREE_VALUE will be a TREE_LIST
2991          containing the initialization arguments. 
2992
2993          The resulting expansion looks somewhat different from most
2994          expansions. Rather than returning just one _EXPANSION, we
2995          return a TREE_LIST whose TREE_PURPOSE is a
2996          TYPE_PACK_EXPANSION containing the bases that will be
2997          initialized.  The TREE_VALUE will be identical to the
2998          original TREE_VALUE, which is a list of arguments that will
2999          be passed to each base.  We do not introduce any new pack
3000          expansion nodes into the TREE_VALUE (although it is possible
3001          that some already exist), because the TREE_PURPOSE and
3002          TREE_VALUE all need to be expanded together with the same
3003          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3004          resulting TREE_PURPOSE will mention the parameter packs in
3005          both the bases and the arguments to the bases.  */
3006       tree purpose;
3007       tree value;
3008       tree parameter_packs = NULL_TREE;
3009
3010       /* Determine which parameter packs will be used by the base
3011          class expansion.  */
3012       ppd.visited = pointer_set_create ();
3013       ppd.parameter_packs = &parameter_packs;
3014       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3015                     &ppd, ppd.visited);
3016
3017       if (parameter_packs == NULL_TREE)
3018         {
3019           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3020           pointer_set_destroy (ppd.visited);
3021           return error_mark_node;
3022         }
3023
3024       if (TREE_VALUE (arg) != void_type_node)
3025         {
3026           /* Collect the sets of parameter packs used in each of the
3027              initialization arguments.  */
3028           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3029             {
3030               /* Determine which parameter packs will be expanded in this
3031                  argument.  */
3032               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3033                             &ppd, ppd.visited);
3034             }
3035         }
3036
3037       pointer_set_destroy (ppd.visited);
3038
3039       /* Create the pack expansion type for the base type.  */
3040       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3041       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3042       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3043
3044       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3045          they will rarely be compared to anything.  */
3046       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3047
3048       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3049     }
3050
3051   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3052     for_types = true;
3053
3054   /* Build the PACK_EXPANSION_* node.  */
3055   result = for_types
3056      ? cxx_make_type (TYPE_PACK_EXPANSION)
3057      : make_node (EXPR_PACK_EXPANSION);
3058   SET_PACK_EXPANSION_PATTERN (result, arg);
3059   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3060     {
3061       /* Propagate type and const-expression information.  */
3062       TREE_TYPE (result) = TREE_TYPE (arg);
3063       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3064     }
3065   else
3066     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3067        they will rarely be compared to anything.  */
3068     SET_TYPE_STRUCTURAL_EQUALITY (result);
3069
3070   /* Determine which parameter packs will be expanded.  */
3071   ppd.parameter_packs = &parameter_packs;
3072   ppd.visited = pointer_set_create ();
3073   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3074   pointer_set_destroy (ppd.visited);
3075
3076   /* Make sure we found some parameter packs.  */
3077   if (parameter_packs == NULL_TREE)
3078     {
3079       if (TYPE_P (arg))
3080         error ("expansion pattern %<%T%> contains no argument packs", arg);
3081       else
3082         error ("expansion pattern %<%E%> contains no argument packs", arg);
3083       return error_mark_node;
3084     }
3085   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3086
3087   return result;
3088 }
3089
3090 /* Checks T for any "bare" parameter packs, which have not yet been
3091    expanded, and issues an error if any are found. This operation can
3092    only be done on full expressions or types (e.g., an expression
3093    statement, "if" condition, etc.), because we could have expressions like:
3094
3095      foo(f(g(h(args)))...)
3096
3097    where "args" is a parameter pack. check_for_bare_parameter_packs
3098    should not be called for the subexpressions args, h(args),
3099    g(h(args)), or f(g(h(args))), because we would produce erroneous
3100    error messages. 
3101
3102    Returns TRUE and emits an error if there were bare parameter packs,
3103    returns FALSE otherwise.  */
3104 bool 
3105 check_for_bare_parameter_packs (tree t)
3106 {
3107   tree parameter_packs = NULL_TREE;
3108   struct find_parameter_pack_data ppd;
3109
3110   if (!processing_template_decl || !t || t == error_mark_node)
3111     return false;
3112
3113   if (TREE_CODE (t) == TYPE_DECL)
3114     t = TREE_TYPE (t);
3115
3116   ppd.parameter_packs = &parameter_packs;
3117   ppd.visited = pointer_set_create ();
3118   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3119   pointer_set_destroy (ppd.visited);
3120
3121   if (parameter_packs) 
3122     {
3123       error ("parameter packs not expanded with %<...%>:");
3124       while (parameter_packs)
3125         {
3126           tree pack = TREE_VALUE (parameter_packs);
3127           tree name = NULL_TREE;
3128
3129           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3130               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3131             name = TYPE_NAME (pack);
3132           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3133             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3134           else
3135             name = DECL_NAME (pack);
3136
3137           if (name)
3138             inform (input_location, "        %qD", name);
3139           else
3140             inform (input_location, "        <anonymous>");
3141
3142           parameter_packs = TREE_CHAIN (parameter_packs);
3143         }
3144
3145       return true;
3146     }
3147
3148   return false;
3149 }
3150
3151 /* Expand any parameter packs that occur in the template arguments in
3152    ARGS.  */
3153 tree
3154 expand_template_argument_pack (tree args)
3155 {
3156   tree result_args = NULL_TREE;
3157   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3158   int num_result_args = -1;
3159
3160   /* First, determine if we need to expand anything, and the number of
3161      slots we'll need.  */
3162   for (in_arg = 0; in_arg < nargs; ++in_arg)
3163     {
3164       tree arg = TREE_VEC_ELT (args, in_arg);
3165       if (arg == NULL_TREE)
3166         return args;
3167       if (ARGUMENT_PACK_P (arg))
3168         {
3169           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3170           if (num_result_args < 0)
3171             num_result_args = in_arg + num_packed;
3172           else
3173             num_result_args += num_packed;
3174         }
3175       else
3176         {
3177           if (num_result_args >= 0)
3178             num_result_args++;
3179         }
3180     }
3181
3182   /* If no expansion is necessary, we're done.  */
3183   if (num_result_args < 0)
3184     return args;
3185
3186   /* Expand arguments.  */
3187   result_args = make_tree_vec (num_result_args);
3188   for (in_arg = 0; in_arg < nargs; ++in_arg)
3189     {
3190       tree arg = TREE_VEC_ELT (args, in_arg);
3191       if (ARGUMENT_PACK_P (arg))
3192         {
3193           tree packed = ARGUMENT_PACK_ARGS (arg);
3194           int i, num_packed = TREE_VEC_LENGTH (packed);
3195           for (i = 0; i < num_packed; ++i, ++out_arg)
3196             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3197         }
3198       else
3199         {
3200           TREE_VEC_ELT (result_args, out_arg) = arg;
3201           ++out_arg;
3202         }
3203     }
3204
3205   return result_args;
3206 }
3207
3208 /* Checks if DECL shadows a template parameter.
3209
3210    [temp.local]: A template-parameter shall not be redeclared within its
3211    scope (including nested scopes).
3212
3213    Emits an error and returns TRUE if the DECL shadows a parameter,
3214    returns FALSE otherwise.  */
3215
3216 bool
3217 check_template_shadow (tree decl)
3218 {
3219   tree olddecl;
3220
3221   /* If we're not in a template, we can't possibly shadow a template
3222      parameter.  */
3223   if (!current_template_parms)
3224     return true;
3225
3226   /* Figure out what we're shadowing.  */
3227   if (TREE_CODE (decl) == OVERLOAD)
3228     decl = OVL_CURRENT (decl);
3229   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3230
3231   /* If there's no previous binding for this name, we're not shadowing
3232      anything, let alone a template parameter.  */
3233   if (!olddecl)
3234     return true;
3235
3236   /* If we're not shadowing a template parameter, we're done.  Note
3237      that OLDDECL might be an OVERLOAD (or perhaps even an
3238      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3239      node.  */
3240   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3241     return true;
3242
3243   /* We check for decl != olddecl to avoid bogus errors for using a
3244      name inside a class.  We check TPFI to avoid duplicate errors for
3245      inline member templates.  */
3246   if (decl == olddecl
3247       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3248     return true;
3249
3250   error ("declaration of %q+#D", decl);
3251   error (" shadows template parm %q+#D", olddecl);
3252   return false;
3253 }
3254
3255 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3256    ORIG_LEVEL, DECL, and TYPE.  */
3257
3258 static tree
3259 build_template_parm_index (int index,
3260                            int level,
3261                            int orig_level,
3262                            tree decl,
3263                            tree type)
3264 {
3265   tree t = make_node (TEMPLATE_PARM_INDEX);
3266   TEMPLATE_PARM_IDX (t) = index;
3267   TEMPLATE_PARM_LEVEL (t) = level;
3268   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3269   TEMPLATE_PARM_DECL (t) = decl;
3270   TREE_TYPE (t) = type;
3271   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3272   TREE_READONLY (t) = TREE_READONLY (decl);
3273
3274   return t;
3275 }
3276
3277 /* Find the canonical type parameter for the given template type
3278    parameter.  Returns the canonical type parameter, which may be TYPE
3279    if no such parameter existed.  */
3280 static tree
3281 canonical_type_parameter (tree type)
3282 {
3283   tree list;
3284   int idx = TEMPLATE_TYPE_IDX (type);
3285   if (!canonical_template_parms)
3286     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3287
3288   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3289     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3290
3291   list = VEC_index (tree, canonical_template_parms, idx);
3292   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3293     list = TREE_CHAIN (list);
3294
3295   if (list)
3296     return TREE_VALUE (list);
3297   else
3298     {
3299       VEC_replace(tree, canonical_template_parms, idx,
3300                   tree_cons (NULL_TREE, type, 
3301                              VEC_index (tree, canonical_template_parms, idx)));
3302       return type;
3303     }
3304 }
3305
3306 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3307    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3308    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3309    new one is created.  */
3310
3311 static tree
3312 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3313                             tsubst_flags_t complain)
3314 {
3315   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3316       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3317           != TEMPLATE_PARM_LEVEL (index) - levels))
3318     {
3319       tree orig_decl = TEMPLATE_PARM_DECL (index);
3320       tree decl, t;
3321
3322       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3323                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3324       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3325       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3326       DECL_ARTIFICIAL (decl) = 1;
3327       SET_DECL_TEMPLATE_PARM_P (decl);
3328
3329       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3330                                      TEMPLATE_PARM_LEVEL (index) - levels,
3331                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3332                                      decl, type);
3333       TEMPLATE_PARM_DESCENDANTS (index) = t;
3334       TEMPLATE_PARM_PARAMETER_PACK (t) 
3335         = TEMPLATE_PARM_PARAMETER_PACK (index);
3336
3337         /* Template template parameters need this.  */
3338       if (TREE_CODE (decl) == TEMPLATE_DECL)
3339         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3340           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3341            args, complain);
3342     }
3343
3344   return TEMPLATE_PARM_DESCENDANTS (index);
3345 }
3346
3347 /* Process information from new template parameter PARM and append it to the
3348    LIST being built.  This new parameter is a non-type parameter iff
3349    IS_NON_TYPE is true. This new parameter is a parameter
3350    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3351    PARM_LOC.  */
3352
3353 tree
3354 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3355                        bool is_parameter_pack)
3356 {
3357   tree decl = 0;
3358   tree defval;
3359   tree err_parm_list;
3360   int idx = 0;
3361
3362   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3363   defval = TREE_PURPOSE (parm);
3364
3365   if (list)
3366     {
3367       tree p = tree_last (list);
3368
3369       if (p && TREE_VALUE (p) != error_mark_node)
3370         {
3371           p = TREE_VALUE (p);
3372           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3373             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3374           else
3375             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3376         }
3377
3378       ++idx;
3379     }
3380   else
3381     idx = 0;
3382
3383   if (is_non_type)
3384     {
3385       parm = TREE_VALUE (parm);
3386
3387       SET_DECL_TEMPLATE_PARM_P (parm);
3388
3389       if (TREE_TYPE (parm) == error_mark_node)
3390         {
3391           err_parm_list = build_tree_list (defval, parm);
3392           TREE_VALUE (err_parm_list) = error_mark_node;
3393            return chainon (list, err_parm_list);
3394         }
3395       else
3396       {
3397         /* [temp.param]
3398
3399            The top-level cv-qualifiers on the template-parameter are
3400            ignored when determining its type.  */
3401         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3402         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3403           {
3404             err_parm_list = build_tree_list (defval, parm);
3405             TREE_VALUE (err_parm_list) = error_mark_node;
3406              return chainon (list, err_parm_list);
3407           }
3408
3409         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3410           {
3411             /* This template parameter is not a parameter pack, but it
3412                should be. Complain about "bare" parameter packs.  */
3413             check_for_bare_parameter_packs (TREE_TYPE (parm));
3414             
3415             /* Recover by calling this a parameter pack.  */
3416             is_parameter_pack = true;
3417           }
3418       }
3419
3420       /* A template parameter is not modifiable.  */
3421       TREE_CONSTANT (parm) = 1;
3422       TREE_READONLY (parm) = 1;
3423       decl = build_decl (parm_loc,
3424                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3425       TREE_CONSTANT (decl) = 1;
3426       TREE_READONLY (decl) = 1;
3427       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3428         = build_template_parm_index (idx, processing_template_decl,
3429                                      processing_template_decl,
3430                                      decl, TREE_TYPE (parm));
3431
3432       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3433         = is_parameter_pack;
3434     }
3435   else
3436     {
3437       tree t;
3438       parm = TREE_VALUE (TREE_VALUE (parm));
3439
3440       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3441         {
3442           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3443           /* This is for distinguishing between real templates and template
3444              template parameters */
3445           TREE_TYPE (parm) = t;
3446           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3447           decl = parm;
3448         }
3449       else
3450         {
3451           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3452           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3453           decl = build_decl (parm_loc,
3454                              TYPE_DECL, parm, t);
3455         }
3456
3457       TYPE_NAME (t) = decl;
3458       TYPE_STUB_DECL (t) = decl;
3459       parm = decl;
3460       TEMPLATE_TYPE_PARM_INDEX (t)
3461         = build_template_parm_index (idx, processing_template_decl,
3462                                      processing_template_decl,
3463                                      decl, TREE_TYPE (parm));
3464       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3465       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3466     }
3467   DECL_ARTIFICIAL (decl) = 1;
3468   SET_DECL_TEMPLATE_PARM_P (decl);
3469   pushdecl (decl);
3470   parm = build_tree_list (defval, parm);
3471   return chainon (list, parm);
3472 }
3473
3474 /* The end of a template parameter list has been reached.  Process the
3475    tree list into a parameter vector, converting each parameter into a more
3476    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3477    as PARM_DECLs.  */
3478
3479 tree
3480 end_template_parm_list (tree parms)
3481 {
3482   int nparms;
3483   tree parm, next;
3484   tree saved_parmlist = make_tree_vec (list_length (parms));
3485
3486   current_template_parms
3487     = tree_cons (size_int (processing_template_decl),
3488                  saved_parmlist, current_template_parms);
3489
3490   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3491     {
3492       next = TREE_CHAIN (parm);
3493       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3494       TREE_CHAIN (parm) = NULL_TREE;
3495     }
3496
3497   --processing_template_parmlist;
3498
3499   return saved_parmlist;
3500 }
3501
3502 /* end_template_decl is called after a template declaration is seen.  */
3503
3504 void
3505 end_template_decl (void)
3506 {
3507   reset_specialization ();
3508
3509   if (! processing_template_decl)
3510     return;
3511
3512   /* This matches the pushlevel in begin_template_parm_list.  */
3513   finish_scope ();
3514
3515   --processing_template_decl;
3516   current_template_parms = TREE_CHAIN (current_template_parms);
3517 }
3518
3519 /* Within the declaration of a template, return all levels of template
3520    parameters that apply.  The template parameters are represented as
3521    a TREE_VEC, in the form documented in cp-tree.h for template
3522    arguments.  */
3523
3524 static tree
3525 current_template_args (void)
3526 {
3527   tree header;
3528   tree args = NULL_TREE;
3529   int length = TMPL_PARMS_DEPTH (current_template_parms);
3530   int l = length;
3531
3532   /* If there is only one level of template parameters, we do not
3533      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3534      TREE_VEC containing the arguments.  */
3535   if (length > 1)
3536     args = make_tree_vec (length);
3537
3538   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3539     {
3540       tree a = copy_node (TREE_VALUE (header));
3541       int i;
3542
3543       TREE_TYPE (a) = NULL_TREE;
3544       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3545         {
3546           tree t = TREE_VEC_ELT (a, i);
3547
3548           /* T will be a list if we are called from within a
3549              begin/end_template_parm_list pair, but a vector directly
3550              if within a begin/end_member_template_processing pair.  */
3551           if (TREE_CODE (t) == TREE_LIST)
3552             {
3553               t = TREE_VALUE (t);
3554
3555               if (!error_operand_p (t))
3556                 {
3557                   if (TREE_CODE (t) == TYPE_DECL
3558                       || TREE_CODE (t) == TEMPLATE_DECL)
3559                     {
3560                       t = TREE_TYPE (t);
3561                       
3562                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3563                         {
3564                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3565                              with a single element, which expands T.  */
3566                           tree vec = make_tree_vec (1);
3567                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3568                           
3569                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3570                           SET_ARGUMENT_PACK_ARGS (t, vec);
3571                         }
3572                     }
3573                   else
3574                     {
3575                       t = DECL_INITIAL (t);
3576                       
3577                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3578                         {
3579                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3580                              with a single element, which expands T.  */
3581                           tree vec = make_tree_vec (1);
3582                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3583                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3584                           
3585                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3586                           SET_ARGUMENT_PACK_ARGS (t, vec);
3587                           TREE_TYPE (t) = type;
3588                         }
3589                     }
3590                   TREE_VEC_ELT (a, i) = t;
3591                 }
3592             }
3593         }
3594
3595       if (length > 1)
3596         TREE_VEC_ELT (args, --l) = a;
3597       else
3598         args = a;
3599     }
3600
3601   return args;
3602 }
3603
3604 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3605    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3606    a member template.  Used by push_template_decl below.  */
3607
3608 static tree
3609 build_template_decl (tree decl, tree parms, bool member_template_p)
3610 {
3611   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3612   DECL_TEMPLATE_PARMS (tmpl) = parms;
3613   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3614   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3615
3616   return tmpl;
3617 }
3618
3619 struct template_parm_data
3620 {
3621   /* The level of the template parameters we are currently
3622      processing.  */
3623   int level;
3624
3625   /* The index of the specialization argument we are currently
3626      processing.  */
3627   int current_arg;
3628
3629   /* An array whose size is the number of template parameters.  The
3630      elements are nonzero if the parameter has been used in any one
3631      of the arguments processed so far.  */
3632   int* parms;
3633
3634   /* An array whose size is the number of template arguments.  The
3635      elements are nonzero if the argument makes use of template
3636      parameters of this level.  */
3637   int* arg_uses_template_parms;
3638 };
3639
3640 /* Subroutine of push_template_decl used to see if each template
3641    parameter in a partial specialization is used in the explicit
3642    argument list.  If T is of the LEVEL given in DATA (which is
3643    treated as a template_parm_data*), then DATA->PARMS is marked
3644    appropriately.  */
3645
3646 static int
3647 mark_template_parm (tree t, void* data)
3648 {
3649   int level;
3650   int idx;
3651   struct template_parm_data* tpd = (struct template_parm_data*) data;
3652
3653   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3654     {
3655       level = TEMPLATE_PARM_LEVEL (t);
3656       idx = TEMPLATE_PARM_IDX (t);
3657     }
3658   else
3659     {
3660       level = TEMPLATE_TYPE_LEVEL (t);
3661       idx = TEMPLATE_TYPE_IDX (t);
3662     }
3663
3664   if (level == tpd->level)
3665     {
3666       tpd->parms[idx] = 1;
3667       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3668     }
3669
3670   /* Return zero so that for_each_template_parm will continue the
3671      traversal of the tree; we want to mark *every* template parm.  */
3672   return 0;
3673 }
3674
3675 /* Process the partial specialization DECL.  */
3676
3677 static tree
3678 process_partial_specialization (tree decl)
3679 {
3680   tree type = TREE_TYPE (decl);
3681   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3682   tree specargs = CLASSTYPE_TI_ARGS (type);
3683   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3684   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3685   tree inner_parms;
3686   int nargs = TREE_VEC_LENGTH (inner_args);
3687   int ntparms;
3688   int  i;
3689   int did_error_intro = 0;
3690   struct template_parm_data tpd;
3691   struct template_parm_data tpd2;
3692
3693   gcc_assert (current_template_parms);
3694
3695   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3696   ntparms = TREE_VEC_LENGTH (inner_parms);
3697
3698   /* We check that each of the template parameters given in the
3699      partial specialization is used in the argument list to the
3700      specialization.  For example:
3701
3702        template <class T> struct S;
3703        template <class T> struct S<T*>;
3704
3705      The second declaration is OK because `T*' uses the template
3706      parameter T, whereas
3707
3708        template <class T> struct S<int>;
3709
3710      is no good.  Even trickier is:
3711
3712        template <class T>
3713        struct S1
3714        {
3715           template <class U>
3716           struct S2;
3717           template <class U>
3718           struct S2<T>;
3719        };
3720
3721      The S2<T> declaration is actually invalid; it is a
3722      full-specialization.  Of course,
3723
3724           template <class U>
3725           struct S2<T (*)(U)>;
3726
3727      or some such would have been OK.  */
3728   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3729   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3730   memset (tpd.parms, 0, sizeof (int) * ntparms);
3731
3732   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3733   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3734   for (i = 0; i < nargs; ++i)
3735     {
3736       tpd.current_arg = i;
3737       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3738                               &mark_template_parm,
3739                               &tpd,
3740                               NULL,
3741                               /*include_nondeduced_p=*/false);
3742     }
3743   for (i = 0; i < ntparms; ++i)
3744     if (tpd.parms[i] == 0)
3745       {
3746         /* One of the template parms was not used in the
3747            specialization.  */
3748         if (!did_error_intro)
3749           {
3750             error ("template parameters not used in partial specialization:");
3751             did_error_intro = 1;
3752           }
3753
3754         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3755       }
3756
3757   /* [temp.class.spec]
3758
3759      The argument list of the specialization shall not be identical to
3760      the implicit argument list of the primary template.  */
3761   if (comp_template_args
3762       (inner_args,
3763        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3764                                                    (maintmpl)))))
3765     error ("partial specialization %qT does not specialize any template arguments", type);
3766
3767   /* [temp.class.spec]
3768
3769      A partially specialized non-type argument expression shall not
3770      involve template parameters of the partial specialization except
3771      when the argument expression is a simple identifier.
3772
3773      The type of a template parameter corresponding to a specialized
3774      non-type argument shall not be dependent on a parameter of the
3775      specialization. 
3776
3777      Also, we verify that pack expansions only occur at the
3778      end of the argument list.  */
3779   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3780   tpd2.parms = 0;
3781   for (i = 0; i < nargs; ++i)
3782     {
3783       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3784       tree arg = TREE_VEC_ELT (inner_args, i);
3785       tree packed_args = NULL_TREE;
3786       int j, len = 1;
3787
3788       if (ARGUMENT_PACK_P (arg))
3789         {
3790           /* Extract the arguments from the argument pack. We'll be
3791              iterating over these in the following loop.  */
3792           packed_args = ARGUMENT_PACK_ARGS (arg);
3793           len = TREE_VEC_LENGTH (packed_args);
3794         }
3795
3796       for (j = 0; j < len; j++)
3797         {
3798           if (packed_args)
3799             /* Get the Jth argument in the parameter pack.  */
3800             arg = TREE_VEC_ELT (packed_args, j);
3801
3802           if (PACK_EXPANSION_P (arg))
3803             {
3804               /* Pack expansions must come at the end of the
3805                  argument list.  */
3806               if ((packed_args && j < len - 1)
3807                   || (!packed_args && i < nargs - 1))
3808                 {
3809                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3810                     error ("parameter pack argument %qE must be at the "
3811                            "end of the template argument list", arg);
3812                   else
3813                     error ("parameter pack argument %qT must be at the "
3814                            "end of the template argument list", arg);
3815                 }
3816             }
3817
3818           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3819             /* We only care about the pattern.  */
3820             arg = PACK_EXPANSION_PATTERN (arg);
3821
3822           if (/* These first two lines are the `non-type' bit.  */
3823               !TYPE_P (arg)
3824               && TREE_CODE (arg) != TEMPLATE_DECL
3825               /* This next line is the `argument expression is not just a
3826                  simple identifier' condition and also the `specialized
3827                  non-type argument' bit.  */
3828               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3829             {
3830               if ((!packed_args && tpd.arg_uses_template_parms[i])
3831                   || (packed_args && uses_template_parms (arg)))
3832                 error ("template argument %qE involves template parameter(s)",
3833                        arg);
3834               else 
3835                 {
3836                   /* Look at the corresponding template parameter,
3837                      marking which template parameters its type depends
3838                      upon.  */
3839                   tree type = TREE_TYPE (parm);
3840
3841                   if (!tpd2.parms)
3842                     {
3843                       /* We haven't yet initialized TPD2.  Do so now.  */
3844                       tpd2.arg_uses_template_parms 
3845                         = (int *) alloca (sizeof (int) * nargs);
3846                       /* The number of parameters here is the number in the
3847                          main template, which, as checked in the assertion
3848                          above, is NARGS.  */
3849                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3850                       tpd2.level = 
3851                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3852                     }
3853
3854                   /* Mark the template parameters.  But this time, we're
3855                      looking for the template parameters of the main
3856                      template, not in the specialization.  */
3857                   tpd2.current_arg = i;
3858                   tpd2.arg_uses_template_parms[i] = 0;
3859                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3860                   for_each_template_parm (type,
3861                                           &mark_template_parm,
3862                                           &tpd2,
3863                                           NULL,
3864                                           /*include_nondeduced_p=*/false);
3865
3866                   if (tpd2.arg_uses_template_parms [i])
3867                     {
3868                       /* The type depended on some template parameters.
3869                          If they are fully specialized in the
3870                          specialization, that's OK.  */
3871                       int j;
3872                       for (j = 0; j < nargs; ++j)
3873                         if (tpd2.parms[j] != 0
3874                             && tpd.arg_uses_template_parms [j])
3875                           {
3876                             error ("type %qT of template argument %qE depends "
3877                                    "on template parameter(s)", 
3878                                    type,
3879                                    arg);
3880                             break;
3881                           }
3882                     }
3883                 }
3884             }
3885         }
3886     }
3887
3888   /* We should only get here once.  */
3889   gcc_assert (!COMPLETE_TYPE_P (type));
3890
3891   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3892     = tree_cons (specargs, inner_parms,
3893                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3894   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3895   return decl;
3896 }
3897
3898 /* Check that a template declaration's use of default arguments and
3899    parameter packs is not invalid.  Here, PARMS are the template
3900    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3901    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3902    specialization.
3903    
3904
3905    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3906    declaration (but not a definition); 1 indicates a declaration, 2
3907    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3908    emitted for extraneous default arguments.
3909
3910    Returns TRUE if there were no errors found, FALSE otherwise. */
3911
3912 bool
3913 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3914                          int is_partial, int is_friend_decl)
3915 {
3916   const char *msg;
3917   int last_level_to_check;
3918   tree parm_level;
3919   bool no_errors = true;
3920
3921   /* [temp.param]
3922
3923      A default template-argument shall not be specified in a
3924      function template declaration or a function template definition, nor
3925      in the template-parameter-list of the definition of a member of a
3926      class template.  */
3927
3928   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3929     /* You can't have a function template declaration in a local
3930        scope, nor you can you define a member of a class template in a
3931        local scope.  */
3932     return true;
3933
3934   if (current_class_type
3935       && !TYPE_BEING_DEFINED (current_class_type)
3936       && DECL_LANG_SPECIFIC (decl)
3937       && DECL_DECLARES_FUNCTION_P (decl)
3938       /* If this is either a friend defined in the scope of the class
3939          or a member function.  */
3940       && (DECL_FUNCTION_MEMBER_P (decl)
3941           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3942           : DECL_FRIEND_CONTEXT (decl)
3943           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3944           : false)
3945       /* And, if it was a member function, it really was defined in
3946          the scope of the class.  */
3947       && (!DECL_FUNCTION_MEMBER_P (decl)
3948           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3949     /* We already checked these parameters when the template was
3950        declared, so there's no need to do it again now.  This function
3951        was defined in class scope, but we're processing it's body now
3952        that the class is complete.  */
3953     return true;
3954
3955   /* Core issue 226 (C++0x only): the following only applies to class
3956      templates.  */
3957   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3958     {
3959       /* [temp.param]
3960
3961          If a template-parameter has a default template-argument, all
3962          subsequent template-parameters shall have a default
3963          template-argument supplied.  */
3964       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3965         {
3966           tree inner_parms = TREE_VALUE (parm_level);
3967           int ntparms = TREE_VEC_LENGTH (inner_parms);
3968           int seen_def_arg_p = 0;
3969           int i;
3970
3971           for (i = 0; i < ntparms; ++i)
3972             {
3973               tree parm = TREE_VEC_ELT (inner_parms, i);
3974
3975               if (parm == error_mark_node)
3976                 continue;
3977
3978               if (TREE_PURPOSE (parm))
3979                 seen_def_arg_p = 1;
3980               else if (seen_def_arg_p
3981                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3982                 {
3983                   error ("no default argument for %qD", TREE_VALUE (parm));
3984                   /* For better subsequent error-recovery, we indicate that
3985                      there should have been a default argument.  */
3986                   TREE_PURPOSE (parm) = error_mark_node;
3987                   no_errors = false;
3988                 }
3989               else if (is_primary
3990                        && !is_partial
3991                        && !is_friend_decl
3992                        /* Don't complain about an enclosing partial
3993                           specialization.  */
3994                        && parm_level == parms
3995                        && TREE_CODE (decl) == TYPE_DECL
3996                        && i < ntparms - 1
3997                        && template_parameter_pack_p (TREE_VALUE (parm)))
3998                 {
3999                   /* A primary class template can only have one
4000                      parameter pack, at the end of the template
4001                      parameter list.  */
4002
4003                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4004                     error ("parameter pack %qE must be at the end of the"
4005                            " template parameter list", TREE_VALUE (parm));
4006                   else
4007                     error ("parameter pack %qT must be at the end of the"
4008                            " template parameter list", 
4009                            TREE_TYPE (TREE_VALUE (parm)));
4010
4011                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4012                     = error_mark_node;
4013                   no_errors = false;
4014                 }
4015             }
4016         }
4017     }
4018
4019   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4020       || is_partial 
4021       || !is_primary
4022       || is_friend_decl)
4023     /* For an ordinary class template, default template arguments are
4024        allowed at the innermost level, e.g.:
4025          template <class T = int>
4026          struct S {};
4027        but, in a partial specialization, they're not allowed even
4028        there, as we have in [temp.class.spec]:
4029
4030          The template parameter list of a specialization shall not
4031          contain default template argument values.
4032
4033        So, for a partial specialization, or for a function template
4034        (in C++98/C++03), we look at all of them.  */
4035     ;
4036   else
4037     /* But, for a primary class template that is not a partial
4038        specialization we look at all template parameters except the
4039        innermost ones.  */
4040     parms = TREE_CHAIN (parms);
4041
4042   /* Figure out what error message to issue.  */
4043   if (is_friend_decl == 2)
4044     msg = "default template arguments may not be used in function template friend re-declaration";
4045   else if (is_friend_decl)
4046     msg = "default template arguments may not be used in function template friend declarations";
4047   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4048     msg = ("default template arguments may not be used in function templates "
4049            "without -std=c++0x or -std=gnu++0x");
4050   else if (is_partial)
4051     msg = "default template arguments may not be used in partial specializations";
4052   else
4053     msg = "default argument for template parameter for class enclosing %qD";
4054
4055   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4056     /* If we're inside a class definition, there's no need to
4057        examine the parameters to the class itself.  On the one
4058        hand, they will be checked when the class is defined, and,
4059        on the other, default arguments are valid in things like:
4060          template <class T = double>
4061          struct S { template <class U> void f(U); };
4062        Here the default argument for `S' has no bearing on the
4063        declaration of `f'.  */
4064     last_level_to_check = template_class_depth (current_class_type) + 1;
4065   else
4066     /* Check everything.  */
4067     last_level_to_check = 0;
4068
4069   for (parm_level = parms;
4070        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4071        parm_level = TREE_CHAIN (parm_level))
4072     {
4073       tree inner_parms = TREE_VALUE (parm_level);
4074       int i;
4075       int ntparms;
4076
4077       ntparms = TREE_VEC_LENGTH (inner_parms);
4078       for (i = 0; i < ntparms; ++i)
4079         {
4080           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4081             continue;
4082
4083           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4084             {
4085               if (msg)
4086                 {
4087                   no_errors = false;
4088                   if (is_friend_decl == 2)
4089                     return no_errors;
4090
4091                   error (msg, decl);
4092                   msg = 0;
4093                 }
4094
4095               /* Clear out the default argument so that we are not
4096                  confused later.  */
4097               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4098             }
4099         }
4100
4101       /* At this point, if we're still interested in issuing messages,
4102          they must apply to classes surrounding the object declared.  */
4103       if (msg)
4104         msg = "default argument for template parameter for class enclosing %qD";
4105     }
4106
4107   return no_errors;
4108 }
4109
4110 /* Worker for push_template_decl_real, called via
4111    for_each_template_parm.  DATA is really an int, indicating the
4112    level of the parameters we are interested in.  If T is a template
4113    parameter of that level, return nonzero.  */
4114
4115 static int
4116 template_parm_this_level_p (tree t, void* data)
4117 {
4118   int this_level = *(int *)data;
4119   int level;
4120
4121   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4122     level = TEMPLATE_PARM_LEVEL (t);
4123   else
4124     level = TEMPLATE_TYPE_LEVEL (t);
4125   return level == this_level;
4126 }
4127
4128 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4129    parameters given by current_template_args, or reuses a
4130    previously existing one, if appropriate.  Returns the DECL, or an
4131    equivalent one, if it is replaced via a call to duplicate_decls.
4132
4133    If IS_FRIEND is true, DECL is a friend declaration.  */
4134
4135 tree
4136 push_template_decl_real (tree decl, bool is_friend)
4137 {
4138   tree tmpl;
4139   tree args;
4140   tree info;
4141   tree ctx;
4142   int primary;
4143   int is_partial;
4144   int new_template_p = 0;
4145   /* True if the template is a member template, in the sense of
4146      [temp.mem].  */
4147   bool member_template_p = false;
4148
4149   if (decl == error_mark_node || !current_template_parms)
4150     return error_mark_node;
4151
4152   /* See if this is a partial specialization.  */
4153   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4154                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4155                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4156
4157   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4158     is_friend = true;
4159
4160   if (is_friend)
4161     /* For a friend, we want the context of the friend function, not
4162        the type of which it is a friend.  */
4163     ctx = DECL_CONTEXT (decl);
4164   else if (CP_DECL_CONTEXT (decl)
4165            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4166     /* In the case of a virtual function, we want the class in which
4167        it is defined.  */
4168     ctx = CP_DECL_CONTEXT (decl);
4169   else
4170     /* Otherwise, if we're currently defining some class, the DECL
4171        is assumed to be a member of the class.  */
4172     ctx = current_scope ();
4173
4174   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4175     ctx = NULL_TREE;
4176
4177   if (!DECL_CONTEXT (decl))
4178     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4179
4180   /* See if this is a primary template.  */
4181   if (is_friend && ctx)
4182     /* A friend template that specifies a class context, i.e.
4183          template <typename T> friend void A<T>::f();
4184        is not primary.  */
4185     primary = 0;
4186   else
4187     primary = template_parm_scope_p ();
4188
4189   if (primary)
4190     {
4191       if (DECL_CLASS_SCOPE_P (decl))
4192         member_template_p = true;
4193       if (TREE_CODE (decl) == TYPE_DECL
4194           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4195         {
4196           error ("template class without a name");
4197           return error_mark_node;
4198         }
4199       else if (TREE_CODE (decl) == FUNCTION_DECL)
4200         {
4201           if (DECL_DESTRUCTOR_P (decl))
4202             {
4203               /* [temp.mem]
4204
4205                  A destructor shall not be a member template.  */
4206               error ("destructor %qD declared as member template", decl);
4207               return error_mark_node;
4208             }
4209           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4210               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4211                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4212                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4213                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4214                       == void_list_node)))
4215             {
4216               /* [basic.stc.dynamic.allocation]
4217
4218                  An allocation function can be a function
4219                  template. ... Template allocation functions shall
4220                  have two or more parameters.  */
4221               error ("invalid template declaration of %qD", decl);
4222               return error_mark_node;
4223             }
4224         }
4225       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4226                && CLASS_TYPE_P (TREE_TYPE (decl)))
4227         /* OK */;
4228       else
4229         {
4230           error ("template declaration of %q#D", decl);
4231           return error_mark_node;
4232         }
4233     }
4234
4235   /* Check to see that the rules regarding the use of default
4236      arguments are not being violated.  */
4237   check_default_tmpl_args (decl, current_template_parms,
4238                            primary, is_partial, /*is_friend_decl=*/0);
4239
4240   /* Ensure that there are no parameter packs in the type of this
4241      declaration that have not been expanded.  */
4242   if (TREE_CODE (decl) == FUNCTION_DECL)
4243     {
4244       /* Check each of the arguments individually to see if there are
4245          any bare parameter packs.  */
4246       tree type = TREE_TYPE (decl);
4247       tree arg = DECL_ARGUMENTS (decl);
4248       tree argtype = TYPE_ARG_TYPES (type);
4249
4250       while (arg && argtype)
4251         {
4252           if (!FUNCTION_PARAMETER_PACK_P (arg)
4253               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4254             {
4255             /* This is a PARM_DECL that contains unexpanded parameter
4256                packs. We have already complained about this in the
4257                check_for_bare_parameter_packs call, so just replace
4258                these types with ERROR_MARK_NODE.  */
4259               TREE_TYPE (arg) = error_mark_node;
4260               TREE_VALUE (argtype) = error_mark_node;
4261             }
4262
4263           arg = TREE_CHAIN (arg);
4264           argtype = TREE_CHAIN (argtype);
4265         }
4266
4267       /* Check for bare parameter packs in the return type and the
4268          exception specifiers.  */
4269       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4270         /* Errors were already issued, set return type to int
4271            as the frontend doesn't expect error_mark_node as
4272            the return type.  */
4273         TREE_TYPE (type) = integer_type_node;
4274       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4275         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4276     }
4277   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4278     {
4279       TREE_TYPE (decl) = error_mark_node;
4280       return error_mark_node;
4281     }
4282
4283   if (is_partial)
4284     return process_partial_specialization (decl);
4285
4286   args = current_template_args ();
4287
4288   if (!ctx
4289       || TREE_CODE (ctx) == FUNCTION_DECL
4290       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4291       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4292     {
4293       if (DECL_LANG_SPECIFIC (decl)
4294           && DECL_TEMPLATE_INFO (decl)
4295           && DECL_TI_TEMPLATE (decl))
4296         tmpl = DECL_TI_TEMPLATE (decl);
4297       /* If DECL is a TYPE_DECL for a class-template, then there won't
4298          be DECL_LANG_SPECIFIC.  The information equivalent to
4299          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4300       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4301                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4302                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4303         {
4304           /* Since a template declaration already existed for this
4305              class-type, we must be redeclaring it here.  Make sure
4306              that the redeclaration is valid.  */
4307           redeclare_class_template (TREE_TYPE (decl),
4308                                     current_template_parms);
4309           /* We don't need to create a new TEMPLATE_DECL; just use the
4310              one we already had.  */
4311           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4312         }
4313       else
4314         {
4315           tmpl = build_template_decl (decl, current_template_parms,
4316                                       member_template_p);
4317           new_template_p = 1;
4318
4319           if (DECL_LANG_SPECIFIC (decl)
4320               && DECL_TEMPLATE_SPECIALIZATION (decl))
4321             {
4322               /* A specialization of a member template of a template
4323                  class.  */
4324               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4325               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4326               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4327             }
4328         }
4329     }
4330   else
4331     {
4332       tree a, t, current, parms;
4333       int i;
4334       tree tinfo = get_template_info (decl);
4335
4336       if (!tinfo)
4337         {
4338           error ("template definition of non-template %q#D", decl);
4339           return error_mark_node;
4340         }
4341
4342       tmpl = TI_TEMPLATE (tinfo);
4343
4344       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4345           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4346           && DECL_TEMPLATE_SPECIALIZATION (decl)
4347           && DECL_MEMBER_TEMPLATE_P (tmpl))
4348         {
4349           tree new_tmpl;
4350
4351           /* The declaration is a specialization of a member
4352              template, declared outside the class.  Therefore, the
4353              innermost template arguments will be NULL, so we
4354              replace them with the arguments determined by the
4355              earlier call to check_explicit_specialization.  */
4356           args = DECL_TI_ARGS (decl);
4357
4358           new_tmpl
4359             = build_template_decl (decl, current_template_parms,
4360                                    member_template_p);
4361           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4362           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4363           DECL_TI_TEMPLATE (decl) = new_tmpl;
4364           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4365           DECL_TEMPLATE_INFO (new_tmpl)
4366             = build_template_info (tmpl, args);
4367
4368           register_specialization (new_tmpl,
4369                                    most_general_template (tmpl),
4370                                    args,
4371                                    is_friend, 0);
4372           return decl;
4373         }
4374
4375       /* Make sure the template headers we got make sense.  */
4376
4377       parms = DECL_TEMPLATE_PARMS (tmpl);
4378       i = TMPL_PARMS_DEPTH (parms);
4379       if (TMPL_ARGS_DEPTH (args) != i)
4380         {
4381           error ("expected %d levels of template parms for %q#D, got %d",
4382                  i, decl, TMPL_ARGS_DEPTH (args));
4383         }
4384       else
4385         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4386           {
4387             a = TMPL_ARGS_LEVEL (args, i);
4388             t = INNERMOST_TEMPLATE_PARMS (parms);
4389
4390             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4391               {
4392                 if (current == decl)
4393                   error ("got %d template parameters for %q#D",
4394                          TREE_VEC_LENGTH (a), decl);
4395                 else
4396                   error ("got %d template parameters for %q#T",
4397                          TREE_VEC_LENGTH (a), current);
4398                 error ("  but %d required", TREE_VEC_LENGTH (t));
4399                 return error_mark_node;
4400               }
4401
4402             if (current == decl)
4403               current = ctx;
4404             else
4405               current = (TYPE_P (current)
4406                          ? TYPE_CONTEXT (current)
4407                          : DECL_CONTEXT (current));
4408           }
4409
4410       /* Check that the parms are used in the appropriate qualifying scopes
4411          in the declarator.  */
4412       if (!comp_template_args
4413           (TI_ARGS (tinfo),
4414            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4415         {
4416           error ("\
4417 template arguments to %qD do not match original template %qD",
4418                  decl, DECL_TEMPLATE_RESULT (tmpl));
4419           if (!uses_template_parms (TI_ARGS (tinfo)))
4420             inform (input_location, "use template<> for an explicit specialization");
4421           /* Avoid crash in import_export_decl.  */
4422           DECL_INTERFACE_KNOWN (decl) = 1;
4423           return error_mark_node;
4424         }
4425     }
4426
4427   DECL_TEMPLATE_RESULT (tmpl) = decl;
4428   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4429
4430   /* Push template declarations for global functions and types.  Note
4431      that we do not try to push a global template friend declared in a
4432      template class; such a thing may well depend on the template
4433      parameters of the class.  */
4434   if (new_template_p && !ctx
4435       && !(is_friend && template_class_depth (current_class_type) > 0))
4436     {
4437       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4438       if (tmpl == error_mark_node)
4439         return error_mark_node;
4440
4441       /* Hide template friend classes that haven't been declared yet.  */
4442       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4443         {
4444           DECL_ANTICIPATED (tmpl) = 1;
4445           DECL_FRIEND_P (tmpl) = 1;
4446         }
4447     }
4448
4449   if (primary)
4450     {
4451       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4452       int i;
4453
4454       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4455       if (DECL_CONV_FN_P (tmpl))
4456         {
4457           int depth = TMPL_PARMS_DEPTH (parms);
4458
4459           /* It is a conversion operator. See if the type converted to
4460              depends on innermost template operands.  */
4461
4462           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4463                                          depth))
4464             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4465         }
4466
4467       /* Give template template parms a DECL_CONTEXT of the template
4468          for which they are a parameter.  */
4469       parms = INNERMOST_TEMPLATE_PARMS (parms);
4470       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4471         {
4472           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4473           if (TREE_CODE (parm) == TEMPLATE_DECL)
4474             DECL_CONTEXT (parm) = tmpl;
4475         }
4476     }
4477
4478   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4479      back to its most general template.  If TMPL is a specialization,
4480      ARGS may only have the innermost set of arguments.  Add the missing
4481      argument levels if necessary.  */
4482   if (DECL_TEMPLATE_INFO (tmpl))
4483     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4484
4485   info = build_template_info (tmpl, args);
4486
4487   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4488     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4489   else if (DECL_LANG_SPECIFIC (decl))
4490     DECL_TEMPLATE_INFO (decl) = info;
4491
4492   return DECL_TEMPLATE_RESULT (tmpl);
4493 }
4494
4495 tree
4496 push_template_decl (tree decl)
4497 {
4498   return push_template_decl_real (decl, false);
4499 }
4500
4501 /* Called when a class template TYPE is redeclared with the indicated
4502    template PARMS, e.g.:
4503
4504      template <class T> struct S;
4505      template <class T> struct S {};  */
4506
4507 bool
4508 redeclare_class_template (tree type, tree parms)
4509 {
4510   tree tmpl;
4511   tree tmpl_parms;
4512   int i;
4513
4514   if (!TYPE_TEMPLATE_INFO (type))
4515     {
4516       error ("%qT is not a template type", type);
4517       return false;
4518     }
4519
4520   tmpl = TYPE_TI_TEMPLATE (type);
4521   if (!PRIMARY_TEMPLATE_P (tmpl))
4522     /* The type is nested in some template class.  Nothing to worry
4523        about here; there are no new template parameters for the nested
4524        type.  */
4525     return true;
4526
4527   if (!parms)
4528     {
4529       error ("template specifiers not specified in declaration of %qD",
4530              tmpl);
4531       return false;
4532     }
4533
4534   parms = INNERMOST_TEMPLATE_PARMS (parms);
4535   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4536
4537   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4538     {
4539       error ("redeclared with %d template parameter(s)", 
4540              TREE_VEC_LENGTH (parms));
4541       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4542              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4543       return false;
4544     }
4545
4546   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4547     {
4548       tree tmpl_parm;
4549       tree parm;
4550       tree tmpl_default;
4551       tree parm_default;
4552
4553       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4554           || TREE_VEC_ELT (parms, i) == error_mark_node)
4555         continue;
4556
4557       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4558       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4559       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4560       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4561
4562       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4563          TEMPLATE_DECL.  */
4564       if (tmpl_parm != error_mark_node
4565           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4566               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4567                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4568               || (TREE_CODE (tmpl_parm) != PARM_DECL
4569                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4570                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4571               || (TREE_CODE (tmpl_parm) == PARM_DECL
4572                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4573                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4574         {
4575           error ("template parameter %q+#D", tmpl_parm);
4576           error ("redeclared here as %q#D", parm);
4577           return false;
4578         }
4579
4580       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4581         {
4582           /* We have in [temp.param]:
4583
4584              A template-parameter may not be given default arguments
4585              by two different declarations in the same scope.  */
4586           error_at (input_location, "redefinition of default argument for %q#D", parm);
4587           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4588                   "original definition appeared here");
4589           return false;
4590         }
4591
4592       if (parm_default != NULL_TREE)
4593         /* Update the previous template parameters (which are the ones
4594            that will really count) with the new default value.  */
4595         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4596       else if (tmpl_default != NULL_TREE)
4597         /* Update the new parameters, too; they'll be used as the
4598            parameters for any members.  */
4599         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4600     }
4601
4602     return true;
4603 }
4604
4605 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4606    (possibly simplified) expression.  */
4607
4608 tree
4609 fold_non_dependent_expr (tree expr)
4610 {
4611   if (expr == NULL_TREE)
4612     return NULL_TREE;
4613
4614   /* If we're in a template, but EXPR isn't value dependent, simplify
4615      it.  We're supposed to treat:
4616
4617        template <typename T> void f(T[1 + 1]);
4618        template <typename T> void f(T[2]);
4619
4620      as two declarations of the same function, for example.  */
4621   if (processing_template_decl
4622       && !type_dependent_expression_p (expr)
4623       && !value_dependent_expression_p (expr))
4624     {
4625       HOST_WIDE_INT saved_processing_template_decl;
4626
4627       saved_processing_template_decl = processing_template_decl;
4628       processing_template_decl = 0;
4629       expr = tsubst_copy_and_build (expr,
4630                                     /*args=*/NULL_TREE,
4631                                     tf_error,
4632                                     /*in_decl=*/NULL_TREE,
4633                                     /*function_p=*/false,
4634                                     /*integral_constant_expression_p=*/true);
4635       processing_template_decl = saved_processing_template_decl;
4636     }
4637   return expr;
4638 }
4639
4640 /* EXPR is an expression which is used in a constant-expression context.
4641    For instance, it could be a VAR_DECL with a constant initializer.
4642    Extract the innermost constant expression.
4643
4644    This is basically a more powerful version of
4645    integral_constant_value, which can be used also in templates where
4646    initializers can maintain a syntactic rather than semantic form
4647    (even if they are non-dependent, for access-checking purposes).  */
4648
4649 static tree
4650 fold_decl_constant_value (tree expr)
4651 {
4652   tree const_expr = expr;
4653   do
4654     {
4655       expr = fold_non_dependent_expr (const_expr);
4656       const_expr = integral_constant_value (expr);
4657     }
4658   while (expr != const_expr);
4659
4660   return expr;
4661 }
4662
4663 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4664    must be a function or a pointer-to-function type, as specified
4665    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4666    and check that the resulting function has external linkage.  */
4667
4668 static tree
4669 convert_nontype_argument_function (tree type, tree expr)
4670 {
4671   tree fns = expr;
4672   tree fn, fn_no_ptr;
4673
4674   fn = instantiate_type (type, fns, tf_none);
4675   if (fn == error_mark_node)
4676     return error_mark_node;
4677
4678   fn_no_ptr = fn;
4679   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4680     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4681   if (TREE_CODE (fn_no_ptr) == BASELINK)
4682     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4683  
4684   /* [temp.arg.nontype]/1
4685
4686      A template-argument for a non-type, non-template template-parameter
4687      shall be one of:
4688      [...]
4689      -- the address of an object or function with external linkage.  */
4690   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4691     {
4692       error ("%qE is not a valid template argument for type %qT "
4693              "because function %qD has not external linkage",
4694              expr, type, fn_no_ptr);
4695       return NULL_TREE;
4696     }
4697
4698   return fn;
4699 }
4700
4701 /* Subroutine of convert_nontype_argument.
4702    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4703    Emit an error otherwise.  */
4704
4705 static bool
4706 check_valid_ptrmem_cst_expr (tree type, tree expr)
4707 {
4708   STRIP_NOPS (expr);
4709   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4710     return true;
4711   error ("%qE is not a valid template argument for type %qT",
4712          expr, type);
4713   error ("it must be a pointer-to-member of the form `&X::Y'");
4714   return false;
4715 }
4716
4717 /* Attempt to convert the non-type template parameter EXPR to the
4718    indicated TYPE.  If the conversion is successful, return the
4719    converted value.  If the conversion is unsuccessful, return
4720    NULL_TREE if we issued an error message, or error_mark_node if we
4721    did not.  We issue error messages for out-and-out bad template
4722    parameters, but not simply because the conversion failed, since we
4723    might be just trying to do argument deduction.  Both TYPE and EXPR
4724    must be non-dependent.
4725
4726    The conversion follows the special rules described in
4727    [temp.arg.nontype], and it is much more strict than an implicit
4728    conversion.
4729
4730    This function is called twice for each template argument (see
4731    lookup_template_class for a more accurate description of this
4732    problem). This means that we need to handle expressions which
4733    are not valid in a C++ source, but can be created from the
4734    first call (for instance, casts to perform conversions). These
4735    hacks can go away after we fix the double coercion problem.  */
4736
4737 static tree
4738 convert_nontype_argument (tree type, tree expr)
4739 {
4740   tree expr_type;
4741
4742   /* Detect immediately string literals as invalid non-type argument.
4743      This special-case is not needed for correctness (we would easily
4744      catch this later), but only to provide better diagnostic for this
4745      common user mistake. As suggested by DR 100, we do not mention
4746      linkage issues in the diagnostic as this is not the point.  */
4747   if (TREE_CODE (expr) == STRING_CST)
4748     {
4749       error ("%qE is not a valid template argument for type %qT "
4750              "because string literals can never be used in this context",
4751              expr, type);
4752       return NULL_TREE;
4753     }
4754
4755   /* If we are in a template, EXPR may be non-dependent, but still
4756      have a syntactic, rather than semantic, form.  For example, EXPR
4757      might be a SCOPE_REF, rather than the VAR_DECL to which the
4758      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4759      so that access checking can be performed when the template is
4760      instantiated -- but here we need the resolved form so that we can
4761      convert the argument.  */
4762   expr = fold_non_dependent_expr (expr);
4763   if (error_operand_p (expr))
4764     return error_mark_node;
4765   expr_type = TREE_TYPE (expr);
4766
4767   /* HACK: Due to double coercion, we can get a
4768      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4769      which is the tree that we built on the first call (see
4770      below when coercing to reference to object or to reference to
4771      function). We just strip everything and get to the arg.
4772      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4773      for examples.  */
4774   if (TREE_CODE (expr) == NOP_EXPR)
4775     {
4776       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4777         {
4778           /* ??? Maybe we could use convert_from_reference here, but we
4779              would need to relax its constraints because the NOP_EXPR
4780              could actually change the type to something more cv-qualified,
4781              and this is not folded by convert_from_reference.  */
4782           tree addr = TREE_OPERAND (expr, 0);
4783           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4784           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4785           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4786           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4787                       (TREE_TYPE (expr_type),
4788                        TREE_TYPE (TREE_TYPE (addr))));
4789
4790           expr = TREE_OPERAND (addr, 0);
4791           expr_type = TREE_TYPE (expr);
4792         }
4793
4794       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4795          parameter is a pointer to object, through decay and
4796          qualification conversion. Let's strip everything.  */
4797       else if (TYPE_PTROBV_P (type))
4798         {
4799           STRIP_NOPS (expr);
4800           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4801           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4802           /* Skip the ADDR_EXPR only if it is part of the decay for
4803              an array. Otherwise, it is part of the original argument
4804              in the source code.  */
4805           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4806             expr = TREE_OPERAND (expr, 0);
4807           expr_type = TREE_TYPE (expr);
4808         }
4809     }
4810
4811   /* [temp.arg.nontype]/5, bullet 1
4812
4813      For a non-type template-parameter of integral or enumeration type,
4814      integral promotions (_conv.prom_) and integral conversions
4815      (_conv.integral_) are applied.  */
4816   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4817     {
4818       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4819         return error_mark_node;
4820
4821       expr = fold_decl_constant_value (expr);
4822       /* Notice that there are constant expressions like '4 % 0' which
4823          do not fold into integer constants.  */
4824       if (TREE_CODE (expr) != INTEGER_CST)
4825         {
4826           error ("%qE is not a valid template argument for type %qT "
4827                  "because it is a non-constant expression", expr, type);
4828           return NULL_TREE;
4829         }
4830
4831       /* At this point, an implicit conversion does what we want,
4832          because we already know that the expression is of integral
4833          type.  */
4834       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4835       if (expr == error_mark_node)
4836         return error_mark_node;
4837
4838       /* Conversion was allowed: fold it to a bare integer constant.  */
4839       expr = fold (expr);
4840     }
4841   /* [temp.arg.nontype]/5, bullet 2
4842
4843      For a non-type template-parameter of type pointer to object,
4844      qualification conversions (_conv.qual_) and the array-to-pointer
4845      conversion (_conv.array_) are applied.  */
4846   else if (TYPE_PTROBV_P (type))
4847     {
4848       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4849
4850          A template-argument for a non-type, non-template template-parameter
4851          shall be one of: [...]
4852
4853          -- the name of a non-type template-parameter;
4854          -- the address of an object or function with external linkage, [...]
4855             expressed as "& id-expression" where the & is optional if the name
4856             refers to a function or array, or if the corresponding
4857             template-parameter is a reference.
4858
4859         Here, we do not care about functions, as they are invalid anyway
4860         for a parameter of type pointer-to-object.  */
4861
4862       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4863         /* Non-type template parameters are OK.  */
4864         ;
4865       else if (TREE_CODE (expr) != ADDR_EXPR
4866                && TREE_CODE (expr_type) != ARRAY_TYPE)
4867         {
4868           if (TREE_CODE (expr) == VAR_DECL)
4869             {
4870               error ("%qD is not a valid template argument "
4871                      "because %qD is a variable, not the address of "
4872                      "a variable",
4873                      expr, expr);
4874               return NULL_TREE;
4875             }
4876           /* Other values, like integer constants, might be valid
4877              non-type arguments of some other type.  */
4878           return error_mark_node;
4879         }
4880       else
4881         {
4882           tree decl;
4883
4884           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4885                   ? TREE_OPERAND (expr, 0) : expr);
4886           if (TREE_CODE (decl) != VAR_DECL)
4887             {
4888               error ("%qE is not a valid template argument of type %qT "
4889                      "because %qE is not a variable",
4890                      expr, type, decl);
4891               return NULL_TREE;
4892             }
4893           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4894             {
4895               error ("%qE is not a valid template argument of type %qT "
4896                      "because %qD does not have external linkage",
4897                      expr, type, decl);
4898               return NULL_TREE;
4899             }
4900         }
4901
4902       expr = decay_conversion (expr);
4903       if (expr == error_mark_node)
4904         return error_mark_node;
4905
4906       expr = perform_qualification_conversions (type, expr);
4907       if (expr == error_mark_node)
4908         return error_mark_node;
4909     }
4910   /* [temp.arg.nontype]/5, bullet 3
4911
4912      For a non-type template-parameter of type reference to object, no
4913      conversions apply. The type referred to by the reference may be more
4914      cv-qualified than the (otherwise identical) type of the
4915      template-argument. The template-parameter is bound directly to the
4916      template-argument, which must be an lvalue.  */
4917   else if (TYPE_REF_OBJ_P (type))
4918     {
4919       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4920                                                       expr_type))
4921         return error_mark_node;
4922
4923       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4924         {
4925           error ("%qE is not a valid template argument for type %qT "
4926                  "because of conflicts in cv-qualification", expr, type);
4927           return NULL_TREE;
4928         }
4929
4930       if (!real_lvalue_p (expr))
4931         {
4932           error ("%qE is not a valid template argument for type %qT "
4933                  "because it is not an lvalue", expr, type);
4934           return NULL_TREE;
4935         }
4936
4937       /* [temp.arg.nontype]/1
4938
4939          A template-argument for a non-type, non-template template-parameter
4940          shall be one of: [...]
4941
4942          -- the address of an object or function with external linkage.  */
4943       if (TREE_CODE (expr) == INDIRECT_REF
4944           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
4945         {
4946           expr = TREE_OPERAND (expr, 0);
4947           if (DECL_P (expr))
4948             {
4949               error ("%q#D is not a valid template argument for type %qT "
4950                      "because a reference variable does not have a constant "
4951                      "address", expr, type);
4952               return NULL_TREE;
4953             }
4954         }
4955
4956       if (!DECL_P (expr))
4957         {
4958           error ("%qE is not a valid template argument for type %qT "
4959                  "because it is not an object with external linkage",
4960                  expr, type);
4961           return NULL_TREE;
4962         }
4963
4964       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4965         {
4966           error ("%qE is not a valid template argument for type %qT "
4967                  "because object %qD has not external linkage",
4968                  expr, type, expr);
4969           return NULL_TREE;
4970         }
4971
4972       expr = build_nop (type, build_address (expr));
4973     }
4974   /* [temp.arg.nontype]/5, bullet 4
4975
4976      For a non-type template-parameter of type pointer to function, only
4977      the function-to-pointer conversion (_conv.func_) is applied. If the
4978      template-argument represents a set of overloaded functions (or a
4979      pointer to such), the matching function is selected from the set
4980      (_over.over_).  */
4981   else if (TYPE_PTRFN_P (type))
4982     {
4983       /* If the argument is a template-id, we might not have enough
4984          context information to decay the pointer.  */
4985       if (!type_unknown_p (expr_type))
4986         {
4987           expr = decay_conversion (expr);
4988           if (expr == error_mark_node)
4989             return error_mark_node;
4990         }
4991
4992       expr = convert_nontype_argument_function (type, expr);
4993       if (!expr || expr == error_mark_node)
4994         return expr;
4995
4996       if (TREE_CODE (expr) != ADDR_EXPR)
4997         {
4998           error ("%qE is not a valid template argument for type %qT", expr, type);
4999           error ("it must be the address of a function with external linkage");
5000           return NULL_TREE;
5001         }
5002     }
5003   /* [temp.arg.nontype]/5, bullet 5
5004
5005      For a non-type template-parameter of type reference to function, no
5006      conversions apply. If the template-argument represents a set of
5007      overloaded functions, the matching function is selected from the set
5008      (_over.over_).  */
5009   else if (TYPE_REFFN_P (type))
5010     {
5011       if (TREE_CODE (expr) == ADDR_EXPR)
5012         {
5013           error ("%qE is not a valid template argument for type %qT "
5014                  "because it is a pointer", expr, type);
5015           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5016           return NULL_TREE;
5017         }
5018
5019       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5020       if (!expr || expr == error_mark_node)
5021         return expr;
5022
5023       expr = build_nop (type, build_address (expr));
5024     }
5025   /* [temp.arg.nontype]/5, bullet 6
5026
5027      For a non-type template-parameter of type pointer to member function,
5028      no conversions apply. If the template-argument represents a set of
5029      overloaded member functions, the matching member function is selected
5030      from the set (_over.over_).  */
5031   else if (TYPE_PTRMEMFUNC_P (type))
5032     {
5033       expr = instantiate_type (type, expr, tf_none);
5034       if (expr == error_mark_node)
5035         return error_mark_node;
5036
5037       /* [temp.arg.nontype] bullet 1 says the pointer to member
5038          expression must be a pointer-to-member constant.  */
5039       if (!check_valid_ptrmem_cst_expr (type, expr))
5040         return error_mark_node;
5041
5042       /* There is no way to disable standard conversions in
5043          resolve_address_of_overloaded_function (called by
5044          instantiate_type). It is possible that the call succeeded by
5045          converting &B::I to &D::I (where B is a base of D), so we need
5046          to reject this conversion here.
5047
5048          Actually, even if there was a way to disable standard conversions,
5049          it would still be better to reject them here so that we can
5050          provide a superior diagnostic.  */
5051       if (!same_type_p (TREE_TYPE (expr), type))
5052         {
5053           /* Make sure we are just one standard conversion off.  */
5054           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5055           error ("%qE is not a valid template argument for type %qT "
5056                  "because it is of type %qT", expr, type,
5057                  TREE_TYPE (expr));
5058           inform (input_location, "standard conversions are not allowed in this context");
5059           return NULL_TREE;
5060         }
5061     }
5062   /* [temp.arg.nontype]/5, bullet 7
5063
5064      For a non-type template-parameter of type pointer to data member,
5065      qualification conversions (_conv.qual_) are applied.  */
5066   else if (TYPE_PTRMEM_P (type))
5067     {
5068       /* [temp.arg.nontype] bullet 1 says the pointer to member
5069          expression must be a pointer-to-member constant.  */
5070       if (!check_valid_ptrmem_cst_expr (type, expr))
5071         return error_mark_node;
5072
5073       expr = perform_qualification_conversions (type, expr);
5074       if (expr == error_mark_node)
5075         return expr;
5076     }
5077   /* A template non-type parameter must be one of the above.  */
5078   else
5079     gcc_unreachable ();
5080
5081   /* Sanity check: did we actually convert the argument to the
5082      right type?  */
5083   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5084   return expr;
5085 }
5086
5087 /* Subroutine of coerce_template_template_parms, which returns 1 if
5088    PARM_PARM and ARG_PARM match using the rule for the template
5089    parameters of template template parameters. Both PARM and ARG are
5090    template parameters; the rest of the arguments are the same as for
5091    coerce_template_template_parms.
5092  */
5093 static int
5094 coerce_template_template_parm (tree parm,
5095                               tree arg,
5096                               tsubst_flags_t complain,
5097                               tree in_decl,
5098                               tree outer_args)
5099 {
5100   if (arg == NULL_TREE || arg == error_mark_node
5101       || parm == NULL_TREE || parm == error_mark_node)
5102     return 0;
5103   
5104   if (TREE_CODE (arg) != TREE_CODE (parm))
5105     return 0;
5106   
5107   switch (TREE_CODE (parm))
5108     {
5109     case TEMPLATE_DECL:
5110       /* We encounter instantiations of templates like
5111          template <template <template <class> class> class TT>
5112          class C;  */
5113       {
5114         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5115         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5116         
5117         if (!coerce_template_template_parms
5118             (parmparm, argparm, complain, in_decl, outer_args))
5119           return 0;
5120       }
5121       /* Fall through.  */
5122       
5123     case TYPE_DECL:
5124       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5125           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5126         /* Argument is a parameter pack but parameter is not.  */
5127         return 0;
5128       break;
5129       
5130     case PARM_DECL:
5131       /* The tsubst call is used to handle cases such as
5132          
5133            template <int> class C {};
5134            template <class T, template <T> class TT> class D {};
5135            D<int, C> d;
5136
5137          i.e. the parameter list of TT depends on earlier parameters.  */
5138       if (!uses_template_parms (TREE_TYPE (arg))
5139           && !same_type_p
5140                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5141                  TREE_TYPE (arg)))
5142         return 0;
5143       
5144       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5145           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5146         /* Argument is a parameter pack but parameter is not.  */
5147         return 0;
5148       
5149       break;
5150
5151     default:
5152       gcc_unreachable ();
5153     }
5154
5155   return 1;
5156 }
5157
5158
5159 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5160    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5161    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5162    or PARM_DECL.
5163
5164    Consider the example:
5165      template <class T> class A;
5166      template<template <class U> class TT> class B;
5167
5168    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5169    the parameters to A, and OUTER_ARGS contains A.  */
5170
5171 static int
5172 coerce_template_template_parms (tree parm_parms,
5173                                 tree arg_parms,
5174                                 tsubst_flags_t complain,
5175                                 tree in_decl,
5176                                 tree outer_args)
5177 {
5178   int nparms, nargs, i;
5179   tree parm, arg;
5180   int variadic_p = 0;
5181
5182   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5183   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5184
5185   nparms = TREE_VEC_LENGTH (parm_parms);
5186   nargs = TREE_VEC_LENGTH (arg_parms);
5187
5188   /* Determine whether we have a parameter pack at the end of the
5189      template template parameter's template parameter list.  */
5190   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5191     {
5192       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5193       
5194       if (parm == error_mark_node)
5195         return 0;
5196
5197       switch (TREE_CODE (parm))
5198         {
5199         case TEMPLATE_DECL:
5200         case TYPE_DECL:
5201           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5202             variadic_p = 1;
5203           break;
5204           
5205         case PARM_DECL:
5206           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5207             variadic_p = 1;
5208           break;
5209           
5210         default:
5211           gcc_unreachable ();
5212         }
5213     }
5214  
5215   if (nargs != nparms
5216       && !(variadic_p && nargs >= nparms - 1))
5217     return 0;
5218
5219   /* Check all of the template parameters except the parameter pack at
5220      the end (if any).  */
5221   for (i = 0; i < nparms - variadic_p; ++i)
5222     {
5223       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5224           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5225         continue;
5226
5227       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5228       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5229
5230       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5231                                           outer_args))
5232         return 0;
5233
5234     }
5235
5236   if (variadic_p)
5237     {
5238       /* Check each of the template parameters in the template
5239          argument against the template parameter pack at the end of
5240          the template template parameter.  */
5241       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5242         return 0;
5243
5244       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5245
5246       for (; i < nargs; ++i)
5247         {
5248           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5249             continue;
5250  
5251           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5252  
5253           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5254                                               outer_args))
5255             return 0;
5256         }
5257     }
5258
5259   return 1;
5260 }
5261
5262 /* Verifies that the deduced template arguments (in TARGS) for the
5263    template template parameters (in TPARMS) represent valid bindings,
5264    by comparing the template parameter list of each template argument
5265    to the template parameter list of its corresponding template
5266    template parameter, in accordance with DR150. This
5267    routine can only be called after all template arguments have been
5268    deduced. It will return TRUE if all of the template template
5269    parameter bindings are okay, FALSE otherwise.  */
5270 bool 
5271 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5272 {
5273   int i, ntparms = TREE_VEC_LENGTH (tparms);
5274   bool ret = true;
5275
5276   /* We're dealing with template parms in this process.  */
5277   ++processing_template_decl;
5278
5279   targs = INNERMOST_TEMPLATE_ARGS (targs);
5280
5281   for (i = 0; i < ntparms; ++i)
5282     {
5283       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5284       tree targ = TREE_VEC_ELT (targs, i);
5285
5286       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5287         {
5288           tree packed_args = NULL_TREE;
5289           int idx, len = 1;
5290
5291           if (ARGUMENT_PACK_P (targ))
5292             {
5293               /* Look inside the argument pack.  */
5294               packed_args = ARGUMENT_PACK_ARGS (targ);
5295               len = TREE_VEC_LENGTH (packed_args);
5296             }
5297
5298           for (idx = 0; idx < len; ++idx)
5299             {
5300               tree targ_parms = NULL_TREE;
5301
5302               if (packed_args)
5303                 /* Extract the next argument from the argument
5304                    pack.  */
5305                 targ = TREE_VEC_ELT (packed_args, idx);
5306
5307               if (PACK_EXPANSION_P (targ))
5308                 /* Look at the pattern of the pack expansion.  */
5309                 targ = PACK_EXPANSION_PATTERN (targ);
5310
5311               /* Extract the template parameters from the template
5312                  argument.  */
5313               if (TREE_CODE (targ) == TEMPLATE_DECL)
5314                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5315               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5316                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5317
5318               /* Verify that we can coerce the template template
5319                  parameters from the template argument to the template
5320                  parameter.  This requires an exact match.  */
5321               if (targ_parms
5322                   && !coerce_template_template_parms
5323                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5324                         targ_parms,
5325                         tf_none,
5326                         tparm,
5327                         targs))
5328                 {
5329                   ret = false;
5330                   goto out;
5331                 }
5332             }
5333         }
5334     }
5335
5336  out:
5337
5338   --processing_template_decl;
5339   return ret;
5340 }
5341
5342 /* Convert the indicated template ARG as necessary to match the
5343    indicated template PARM.  Returns the converted ARG, or
5344    error_mark_node if the conversion was unsuccessful.  Error and
5345    warning messages are issued under control of COMPLAIN.  This
5346    conversion is for the Ith parameter in the parameter list.  ARGS is
5347    the full set of template arguments deduced so far.  */
5348
5349 static tree
5350 convert_template_argument (tree parm,
5351                            tree arg,
5352                            tree args,
5353                            tsubst_flags_t complain,
5354                            int i,
5355                            tree in_decl)
5356 {
5357   tree orig_arg;
5358   tree val;
5359   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5360
5361   if (TREE_CODE (arg) == TREE_LIST
5362       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5363     {
5364       /* The template argument was the name of some
5365          member function.  That's usually
5366          invalid, but static members are OK.  In any
5367          case, grab the underlying fields/functions
5368          and issue an error later if required.  */
5369       orig_arg = TREE_VALUE (arg);
5370       TREE_TYPE (arg) = unknown_type_node;
5371     }
5372
5373   orig_arg = arg;
5374
5375   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5376   requires_type = (TREE_CODE (parm) == TYPE_DECL
5377                    || requires_tmpl_type);
5378
5379   /* When determining whether an argument pack expansion is a template,
5380      look at the pattern.  */
5381   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5382     arg = PACK_EXPANSION_PATTERN (arg);
5383
5384   /* Deal with an injected-class-name used as a template template arg.  */
5385   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5386     {
5387       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5388       if (TREE_CODE (t) == TEMPLATE_DECL)
5389         {
5390           if (complain & tf_warning_or_error)
5391             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5392                      " used as template template argument", TYPE_NAME (arg));
5393           else if (flag_pedantic_errors)
5394             t = arg;
5395
5396           arg = t;
5397         }
5398     }
5399
5400   is_tmpl_type = 
5401     ((TREE_CODE (arg) == TEMPLATE_DECL
5402       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5403      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5404      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5405
5406   if (is_tmpl_type
5407       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5408           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5409     arg = TYPE_STUB_DECL (arg);
5410
5411   is_type = TYPE_P (arg) || is_tmpl_type;
5412
5413   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5414       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5415     {
5416       permerror (input_location, "to refer to a type member of a template parameter, "
5417                  "use %<typename %E%>", orig_arg);
5418
5419       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5420                                      TREE_OPERAND (arg, 1),
5421                                      typename_type,
5422                                      complain & tf_error);
5423       arg = orig_arg;
5424       is_type = 1;
5425     }
5426   if (is_type != requires_type)
5427     {
5428       if (in_decl)
5429         {
5430           if (complain & tf_error)
5431             {
5432               error ("type/value mismatch at argument %d in template "
5433                      "parameter list for %qD",
5434                      i + 1, in_decl);
5435               if (is_type)
5436                 error ("  expected a constant of type %qT, got %qT",
5437                        TREE_TYPE (parm),
5438                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5439               else if (requires_tmpl_type)
5440                 error ("  expected a class template, got %qE", orig_arg);
5441               else
5442                 error ("  expected a type, got %qE", orig_arg);
5443             }
5444         }
5445       return error_mark_node;
5446     }
5447   if (is_tmpl_type ^ requires_tmpl_type)
5448     {
5449       if (in_decl && (complain & tf_error))
5450         {
5451           error ("type/value mismatch at argument %d in template "
5452                  "parameter list for %qD",
5453                  i + 1, in_decl);
5454           if (is_tmpl_type)
5455             error ("  expected a type, got %qT", DECL_NAME (arg));
5456           else
5457             error ("  expected a class template, got %qT", orig_arg);
5458         }
5459       return error_mark_node;
5460     }
5461
5462   if (is_type)
5463     {
5464       if (requires_tmpl_type)
5465         {
5466           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5467             /* The number of argument required is not known yet.
5468                Just accept it for now.  */
5469             val = TREE_TYPE (arg);
5470           else
5471             {
5472               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5473               tree argparm;
5474
5475               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5476
5477               if (coerce_template_template_parms (parmparm, argparm,
5478                                                   complain, in_decl,
5479                                                   args))
5480                 {
5481                   val = arg;
5482
5483                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5484                      TEMPLATE_DECL.  */
5485                   if (val != error_mark_node)
5486                     {
5487                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5488                         val = TREE_TYPE (val);
5489                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5490                         val = make_pack_expansion (val);
5491                     }
5492                 }
5493               else
5494                 {
5495                   if (in_decl && (complain & tf_error))
5496                     {
5497                       error ("type/value mismatch at argument %d in "
5498                              "template parameter list for %qD",
5499                              i + 1, in_decl);
5500                       error ("  expected a template of type %qD, got %qT",
5501                              parm, orig_arg);
5502                     }
5503
5504                   val = error_mark_node;
5505                 }
5506             }
5507         }
5508       else
5509         val = orig_arg;
5510       /* We only form one instance of each template specialization.
5511          Therefore, if we use a non-canonical variant (i.e., a
5512          typedef), any future messages referring to the type will use
5513          the typedef, which is confusing if those future uses do not
5514          themselves also use the typedef.  */
5515       if (TYPE_P (val))
5516         val = strip_typedefs (val);
5517     }
5518   else
5519     {
5520       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5521
5522       if (invalid_nontype_parm_type_p (t, complain))
5523         return error_mark_node;
5524
5525       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5526         {
5527           if (same_type_p (t, TREE_TYPE (orig_arg)))
5528             val = orig_arg;
5529           else
5530             {
5531               /* Not sure if this is reachable, but it doesn't hurt
5532                  to be robust.  */
5533               error ("type mismatch in nontype parameter pack");
5534               val = error_mark_node;
5535             }
5536         }
5537       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5538         /* We used to call digest_init here.  However, digest_init
5539            will report errors, which we don't want when complain
5540            is zero.  More importantly, digest_init will try too
5541            hard to convert things: for example, `0' should not be
5542            converted to pointer type at this point according to
5543            the standard.  Accepting this is not merely an
5544            extension, since deciding whether or not these
5545            conversions can occur is part of determining which
5546            function template to call, or whether a given explicit
5547            argument specification is valid.  */
5548         val = convert_nontype_argument (t, orig_arg);
5549       else
5550         val = orig_arg;
5551
5552       if (val == NULL_TREE)
5553         val = error_mark_node;
5554       else if (val == error_mark_node && (complain & tf_error))
5555         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5556     }
5557
5558   return val;
5559 }
5560
5561 /* Coerces the remaining template arguments in INNER_ARGS (from
5562    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5563    Returns the coerced argument pack. PARM_IDX is the position of this
5564    parameter in the template parameter list. ARGS is the original
5565    template argument list.  */
5566 static tree
5567 coerce_template_parameter_pack (tree parms,
5568                                 int parm_idx,
5569                                 tree args,
5570                                 tree inner_args,
5571                                 int arg_idx,
5572                                 tree new_args,
5573                                 int* lost,
5574                                 tree in_decl,
5575                                 tsubst_flags_t complain)
5576 {
5577   tree parm = TREE_VEC_ELT (parms, parm_idx);
5578   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5579   tree packed_args;
5580   tree argument_pack;
5581   tree packed_types = NULL_TREE;
5582
5583   if (arg_idx > nargs)
5584     arg_idx = nargs;
5585
5586   packed_args = make_tree_vec (nargs - arg_idx);
5587
5588   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5589       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5590     {
5591       /* When the template parameter is a non-type template
5592          parameter pack whose type uses parameter packs, we need
5593          to look at each of the template arguments
5594          separately. Build a vector of the types for these
5595          non-type template parameters in PACKED_TYPES.  */
5596       tree expansion 
5597         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5598       packed_types = tsubst_pack_expansion (expansion, args,
5599                                             complain, in_decl);
5600
5601       if (packed_types == error_mark_node)
5602         return error_mark_node;
5603
5604       /* Check that we have the right number of arguments.  */
5605       if (arg_idx < nargs
5606           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5607           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5608         {
5609           int needed_parms 
5610             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5611           error ("wrong number of template arguments (%d, should be %d)",
5612                  nargs, needed_parms);
5613           return error_mark_node;
5614         }
5615
5616       /* If we aren't able to check the actual arguments now
5617          (because they haven't been expanded yet), we can at least
5618          verify that all of the types used for the non-type
5619          template parameter pack are, in fact, valid for non-type
5620          template parameters.  */
5621       if (arg_idx < nargs 
5622           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5623         {
5624           int j, len = TREE_VEC_LENGTH (packed_types);
5625           for (j = 0; j < len; ++j)
5626             {
5627               tree t = TREE_VEC_ELT (packed_types, j);
5628               if (invalid_nontype_parm_type_p (t, complain))
5629                 return error_mark_node;
5630             }
5631         }
5632     }
5633
5634   /* Convert the remaining arguments, which will be a part of the
5635      parameter pack "parm".  */
5636   for (; arg_idx < nargs; ++arg_idx)
5637     {
5638       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5639       tree actual_parm = TREE_VALUE (parm);
5640
5641       if (packed_types && !PACK_EXPANSION_P (arg))
5642         {
5643           /* When we have a vector of types (corresponding to the
5644              non-type template parameter pack that uses parameter
5645              packs in its type, as mention above), and the
5646              argument is not an expansion (which expands to a
5647              currently unknown number of arguments), clone the
5648              parm and give it the next type in PACKED_TYPES.  */
5649           actual_parm = copy_node (actual_parm);
5650           TREE_TYPE (actual_parm) = 
5651             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5652         }
5653
5654       if (arg != error_mark_node)
5655         arg = convert_template_argument (actual_parm, 
5656                                          arg, new_args, complain, parm_idx,
5657                                          in_decl);
5658       if (arg == error_mark_node)
5659         (*lost)++;
5660       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5661     }
5662
5663   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5664       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5665     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5666   else
5667     {
5668       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5669       TREE_TYPE (argument_pack) 
5670         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5671       TREE_CONSTANT (argument_pack) = 1;
5672     }
5673
5674   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5675   return argument_pack;
5676 }
5677
5678 /* Convert all template arguments to their appropriate types, and
5679    return a vector containing the innermost resulting template
5680    arguments.  If any error occurs, return error_mark_node. Error and
5681    warning messages are issued under control of COMPLAIN.
5682
5683    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5684    for arguments not specified in ARGS.  Otherwise, if
5685    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5686    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5687    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5688    ARGS.  */
5689
5690 static tree
5691 coerce_template_parms (tree parms,
5692                        tree args,
5693                        tree in_decl,
5694                        tsubst_flags_t complain,
5695                        bool require_all_args,
5696                        bool use_default_args)
5697 {
5698   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5699   tree inner_args;
5700   tree new_args;
5701   tree new_inner_args;
5702   int saved_unevaluated_operand;
5703   int saved_inhibit_evaluation_warnings;
5704
5705   /* When used as a boolean value, indicates whether this is a
5706      variadic template parameter list. Since it's an int, we can also
5707      subtract it from nparms to get the number of non-variadic
5708      parameters.  */
5709   int variadic_p = 0;
5710
5711   nparms = TREE_VEC_LENGTH (parms);
5712
5713   /* Determine if there are any parameter packs.  */
5714   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5715     {
5716       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5717       if (template_parameter_pack_p (tparm))
5718         ++variadic_p;
5719     }
5720
5721   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5722   /* If there are 0 or 1 parameter packs, we need to expand any argument
5723      packs so that we can deduce a parameter pack from some non-packed args
5724      followed by an argument pack, as in variadic85.C.  If there are more
5725      than that, we need to leave argument packs intact so the arguments are
5726      assigned to the right parameter packs.  This should only happen when
5727      dealing with a nested class inside a partial specialization of a class
5728      template, as in variadic92.C.  */
5729   if (variadic_p <= 1)
5730     inner_args = expand_template_argument_pack (inner_args);
5731
5732   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5733   if ((nargs > nparms && !variadic_p)
5734       || (nargs < nparms - variadic_p
5735           && require_all_args
5736           && (!use_default_args
5737               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5738                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5739     {
5740       if (complain & tf_error)
5741         {
5742           const char *or_more = "";
5743           if (variadic_p)
5744             {
5745               or_more = " or more";
5746               --nparms;
5747             }
5748
5749           error ("wrong number of template arguments (%d, should be %d%s)",
5750                  nargs, nparms, or_more);
5751
5752           if (in_decl)
5753             error ("provided for %q+D", in_decl);
5754         }
5755
5756       return error_mark_node;
5757     }
5758
5759   /* We need to evaluate the template arguments, even though this
5760      template-id may be nested within a "sizeof".  */
5761   saved_unevaluated_operand = cp_unevaluated_operand;
5762   cp_unevaluated_operand = 0;
5763   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5764   c_inhibit_evaluation_warnings = 0;
5765   new_inner_args = make_tree_vec (nparms);
5766   new_args = add_outermost_template_args (args, new_inner_args);
5767   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5768     {
5769       tree arg;
5770       tree parm;
5771
5772       /* Get the Ith template parameter.  */
5773       parm = TREE_VEC_ELT (parms, parm_idx);
5774  
5775       if (parm == error_mark_node)
5776       {
5777         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5778         continue;
5779       }
5780
5781       /* Calculate the next argument.  */
5782       if (arg_idx < nargs)
5783         arg = TREE_VEC_ELT (inner_args, arg_idx);
5784       else
5785         arg = NULL_TREE;
5786
5787       if (template_parameter_pack_p (TREE_VALUE (parm))
5788           && !(arg && ARGUMENT_PACK_P (arg)))
5789         {
5790           /* All remaining arguments will be placed in the
5791              template parameter pack PARM.  */
5792           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5793                                                 inner_args, arg_idx,
5794                                                 new_args, &lost,
5795                                                 in_decl, complain);
5796
5797           /* Store this argument.  */
5798           if (arg == error_mark_node)
5799             lost++;
5800           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5801
5802           /* We are done with all of the arguments.  */
5803           arg_idx = nargs;
5804           
5805           continue;
5806         }
5807       else if (arg)
5808         {
5809           if (PACK_EXPANSION_P (arg))
5810             {
5811               if (complain & tf_error)
5812                 {
5813                   /* FIXME this restriction was removed by N2555; see
5814                      bug 35722.  */
5815                   /* If ARG is a pack expansion, but PARM is not a
5816                      template parameter pack (if it were, we would have
5817                      handled it above), we're trying to expand into a
5818                      fixed-length argument list.  */
5819                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5820                     sorry ("cannot expand %<%E%> into a fixed-length "
5821                            "argument list", arg);
5822                   else
5823                     sorry ("cannot expand %<%T%> into a fixed-length "
5824                            "argument list", arg);
5825                 }
5826               return error_mark_node;
5827             }
5828         }
5829       else if (require_all_args)
5830         /* There must be a default arg in this case.  */
5831         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5832                                    complain, in_decl);
5833       else
5834         break;
5835
5836       if (arg == error_mark_node)
5837         {
5838           if (complain & tf_error)
5839             error ("template argument %d is invalid", arg_idx + 1);
5840         }
5841       else if (!arg)
5842         /* This only occurs if there was an error in the template
5843            parameter list itself (which we would already have
5844            reported) that we are trying to recover from, e.g., a class
5845            template with a parameter list such as
5846            template<typename..., typename>.  */
5847         return error_mark_node;
5848       else
5849         arg = convert_template_argument (TREE_VALUE (parm),
5850                                          arg, new_args, complain, 
5851                                          parm_idx, in_decl);
5852
5853       if (arg == error_mark_node)
5854         lost++;
5855       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5856     }
5857   cp_unevaluated_operand = saved_unevaluated_operand;
5858   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5859
5860   if (lost)
5861     return error_mark_node;
5862
5863   return new_inner_args;
5864 }
5865
5866 /* Returns 1 if template args OT and NT are equivalent.  */
5867
5868 static int
5869 template_args_equal (tree ot, tree nt)
5870 {
5871   if (nt == ot)
5872     return 1;
5873
5874   if (TREE_CODE (nt) == TREE_VEC)
5875     /* For member templates */
5876     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5877   else if (PACK_EXPANSION_P (ot))
5878     return PACK_EXPANSION_P (nt) 
5879       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5880                               PACK_EXPANSION_PATTERN (nt));
5881   else if (ARGUMENT_PACK_P (ot))
5882     {
5883       int i, len;
5884       tree opack, npack;
5885
5886       if (!ARGUMENT_PACK_P (nt))
5887         return 0;
5888
5889       opack = ARGUMENT_PACK_ARGS (ot);
5890       npack = ARGUMENT_PACK_ARGS (nt);
5891       len = TREE_VEC_LENGTH (opack);
5892       if (TREE_VEC_LENGTH (npack) != len)
5893         return 0;
5894       for (i = 0; i < len; ++i)
5895         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5896                                   TREE_VEC_ELT (npack, i)))
5897           return 0;
5898       return 1;
5899     }
5900   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5901     {
5902       /* We get here probably because we are in the middle of substituting
5903          into the pattern of a pack expansion. In that case the
5904          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5905          interested in. So we want to use the initial pack argument for
5906          the comparison.  */
5907       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5908       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5909         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5910       return template_args_equal (ot, nt);
5911     }
5912   else if (TYPE_P (nt))
5913     return TYPE_P (ot) && same_type_p (ot, nt);
5914   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5915     return 0;
5916   else
5917     return cp_tree_equal (ot, nt);
5918 }
5919
5920 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5921    of template arguments.  Returns 0 otherwise.  */
5922
5923 int
5924 comp_template_args (tree oldargs, tree newargs)
5925 {
5926   int i;
5927
5928   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5929     return 0;
5930
5931   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5932     {
5933       tree nt = TREE_VEC_ELT (newargs, i);
5934       tree ot = TREE_VEC_ELT (oldargs, i);
5935
5936       if (! template_args_equal (ot, nt))
5937         return 0;
5938     }
5939   return 1;
5940 }
5941
5942 static void
5943 add_pending_template (tree d)
5944 {
5945   tree ti = (TYPE_P (d)
5946              ? CLASSTYPE_TEMPLATE_INFO (d)
5947              : DECL_TEMPLATE_INFO (d));
5948   struct pending_template *pt;
5949   int level;
5950
5951   if (TI_PENDING_TEMPLATE_FLAG (ti))
5952     return;
5953
5954   /* We are called both from instantiate_decl, where we've already had a
5955      tinst_level pushed, and instantiate_template, where we haven't.
5956      Compensate.  */
5957   level = !current_tinst_level || current_tinst_level->decl != d;
5958
5959   if (level)
5960     push_tinst_level (d);
5961
5962   pt = GGC_NEW (struct pending_template);
5963   pt->next = NULL;
5964   pt->tinst = current_tinst_level;
5965   if (last_pending_template)
5966     last_pending_template->next = pt;
5967   else
5968     pending_templates = pt;
5969
5970   last_pending_template = pt;
5971
5972   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5973
5974   if (level)
5975     pop_tinst_level ();
5976 }
5977
5978
5979 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5980    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5981    documentation for TEMPLATE_ID_EXPR.  */
5982
5983 tree
5984 lookup_template_function (tree fns, tree arglist)
5985 {
5986   tree type;
5987
5988   if (fns == error_mark_node || arglist == error_mark_node)
5989     return error_mark_node;
5990
5991   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5992   gcc_assert (fns && (is_overloaded_fn (fns)
5993                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5994
5995   if (BASELINK_P (fns))
5996     {
5997       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5998                                          unknown_type_node,
5999                                          BASELINK_FUNCTIONS (fns),
6000                                          arglist);
6001       return fns;
6002     }
6003
6004   type = TREE_TYPE (fns);
6005   if (TREE_CODE (fns) == OVERLOAD || !type)
6006     type = unknown_type_node;
6007
6008   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6009 }
6010
6011 /* Within the scope of a template class S<T>, the name S gets bound
6012    (in build_self_reference) to a TYPE_DECL for the class, not a
6013    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6014    or one of its enclosing classes, and that type is a template,
6015    return the associated TEMPLATE_DECL.  Otherwise, the original
6016    DECL is returned.
6017
6018    Also handle the case when DECL is a TREE_LIST of ambiguous
6019    injected-class-names from different bases.  */
6020
6021 tree
6022 maybe_get_template_decl_from_type_decl (tree decl)
6023 {
6024   if (decl == NULL_TREE)
6025     return decl;
6026
6027   /* DR 176: A lookup that finds an injected-class-name (10.2
6028      [class.member.lookup]) can result in an ambiguity in certain cases
6029      (for example, if it is found in more than one base class). If all of
6030      the injected-class-names that are found refer to specializations of
6031      the same class template, and if the name is followed by a
6032      template-argument-list, the reference refers to the class template
6033      itself and not a specialization thereof, and is not ambiguous.  */
6034   if (TREE_CODE (decl) == TREE_LIST)
6035     {
6036       tree t, tmpl = NULL_TREE;
6037       for (t = decl; t; t = TREE_CHAIN (t))
6038         {
6039           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6040           if (!tmpl)
6041             tmpl = elt;
6042           else if (tmpl != elt)
6043             break;
6044         }
6045       if (tmpl && t == NULL_TREE)
6046         return tmpl;
6047       else
6048         return decl;
6049     }
6050
6051   return (decl != NULL_TREE
6052           && DECL_SELF_REFERENCE_P (decl)
6053           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6054     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6055 }
6056
6057 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6058    parameters, find the desired type.
6059
6060    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6061
6062    IN_DECL, if non-NULL, is the template declaration we are trying to
6063    instantiate.
6064
6065    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6066    the class we are looking up.
6067
6068    Issue error and warning messages under control of COMPLAIN.
6069
6070    If the template class is really a local class in a template
6071    function, then the FUNCTION_CONTEXT is the function in which it is
6072    being instantiated.
6073
6074    ??? Note that this function is currently called *twice* for each
6075    template-id: the first time from the parser, while creating the
6076    incomplete type (finish_template_type), and the second type during the
6077    real instantiation (instantiate_template_class). This is surely something
6078    that we want to avoid. It also causes some problems with argument
6079    coercion (see convert_nontype_argument for more information on this).  */
6080
6081 tree
6082 lookup_template_class (tree d1,
6083                        tree arglist,
6084                        tree in_decl,
6085                        tree context,
6086                        int entering_scope,
6087                        tsubst_flags_t complain)
6088 {
6089   tree templ = NULL_TREE, parmlist;
6090   tree t;
6091   spec_entry **slot;
6092   spec_entry *entry;
6093   spec_entry elt;
6094   hashval_t hash;
6095
6096   timevar_push (TV_NAME_LOOKUP);
6097
6098   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6099     {
6100       tree value = innermost_non_namespace_value (d1);
6101       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6102         templ = value;
6103       else
6104         {
6105           if (context)
6106             push_decl_namespace (context);
6107           templ = lookup_name (d1);
6108           templ = maybe_get_template_decl_from_type_decl (templ);
6109           if (context)
6110             pop_decl_namespace ();
6111         }
6112       if (templ)
6113         context = DECL_CONTEXT (templ);
6114     }
6115   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6116     {
6117       tree type = TREE_TYPE (d1);
6118
6119       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6120          an implicit typename for the second A.  Deal with it.  */
6121       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6122         type = TREE_TYPE (type);
6123
6124       if (CLASSTYPE_TEMPLATE_INFO (type))
6125         {
6126           templ = CLASSTYPE_TI_TEMPLATE (type);
6127           d1 = DECL_NAME (templ);
6128         }
6129     }
6130   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6131            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6132     {
6133       templ = TYPE_TI_TEMPLATE (d1);
6134       d1 = DECL_NAME (templ);
6135     }
6136   else if (TREE_CODE (d1) == TEMPLATE_DECL
6137            && DECL_TEMPLATE_RESULT (d1)
6138            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6139     {
6140       templ = d1;
6141       d1 = DECL_NAME (templ);
6142       context = DECL_CONTEXT (templ);
6143     }
6144
6145   /* Issue an error message if we didn't find a template.  */
6146   if (! templ)
6147     {
6148       if (complain & tf_error)
6149         error ("%qT is not a template", d1);
6150       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6151     }
6152
6153   if (TREE_CODE (templ) != TEMPLATE_DECL
6154          /* Make sure it's a user visible template, if it was named by
6155             the user.  */
6156       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6157           && !PRIMARY_TEMPLATE_P (templ)))
6158     {
6159       if (complain & tf_error)
6160         {
6161           error ("non-template type %qT used as a template", d1);
6162           if (in_decl)
6163             error ("for template declaration %q+D", in_decl);
6164         }
6165       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6166     }
6167
6168   complain &= ~tf_user;
6169
6170   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6171     {
6172       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6173          template arguments */
6174
6175       tree parm;
6176       tree arglist2;
6177       tree outer;
6178
6179       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6180
6181       /* Consider an example where a template template parameter declared as
6182
6183            template <class T, class U = std::allocator<T> > class TT
6184
6185          The template parameter level of T and U are one level larger than
6186          of TT.  To proper process the default argument of U, say when an
6187          instantiation `TT<int>' is seen, we need to build the full
6188          arguments containing {int} as the innermost level.  Outer levels,
6189          available when not appearing as default template argument, can be
6190          obtained from the arguments of the enclosing template.
6191
6192          Suppose that TT is later substituted with std::vector.  The above
6193          instantiation is `TT<int, std::allocator<T> >' with TT at
6194          level 1, and T at level 2, while the template arguments at level 1
6195          becomes {std::vector} and the inner level 2 is {int}.  */
6196
6197       outer = DECL_CONTEXT (templ);
6198       if (outer)
6199         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6200       else if (current_template_parms)
6201         /* This is an argument of the current template, so we haven't set
6202            DECL_CONTEXT yet.  */
6203         outer = current_template_args ();
6204
6205       if (outer)
6206         arglist = add_to_template_args (outer, arglist);
6207
6208       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6209                                         complain,
6210                                         /*require_all_args=*/true,
6211                                         /*use_default_args=*/true);
6212       if (arglist2 == error_mark_node
6213           || (!uses_template_parms (arglist2)
6214               && check_instantiated_args (templ, arglist2, complain)))
6215         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6216
6217       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6218       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6219     }
6220   else
6221     {
6222       tree template_type = TREE_TYPE (templ);
6223       tree gen_tmpl;
6224       tree type_decl;
6225       tree found = NULL_TREE;
6226       int arg_depth;
6227       int parm_depth;
6228       int is_partial_instantiation;
6229
6230       gen_tmpl = most_general_template (templ);
6231       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6232       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6233       arg_depth = TMPL_ARGS_DEPTH (arglist);
6234
6235       if (arg_depth == 1 && parm_depth > 1)
6236         {
6237           /* We've been given an incomplete set of template arguments.
6238              For example, given:
6239
6240                template <class T> struct S1 {
6241                  template <class U> struct S2 {};
6242                  template <class U> struct S2<U*> {};
6243                 };
6244
6245              we will be called with an ARGLIST of `U*', but the
6246              TEMPLATE will be `template <class T> template
6247              <class U> struct S1<T>::S2'.  We must fill in the missing
6248              arguments.  */
6249           arglist
6250             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6251                                            arglist);
6252           arg_depth = TMPL_ARGS_DEPTH (arglist);
6253         }
6254
6255       /* Now we should have enough arguments.  */
6256       gcc_assert (parm_depth == arg_depth);
6257
6258       /* From here on, we're only interested in the most general
6259          template.  */
6260
6261       /* Calculate the BOUND_ARGS.  These will be the args that are
6262          actually tsubst'd into the definition to create the
6263          instantiation.  */
6264       if (parm_depth > 1)
6265         {
6266           /* We have multiple levels of arguments to coerce, at once.  */
6267           int i;
6268           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6269
6270           tree bound_args = make_tree_vec (parm_depth);
6271
6272           for (i = saved_depth,
6273                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6274                i > 0 && t != NULL_TREE;
6275                --i, t = TREE_CHAIN (t))
6276             {
6277               tree a = coerce_template_parms (TREE_VALUE (t),
6278                                               arglist, gen_tmpl,
6279                                               complain,
6280                                               /*require_all_args=*/true,
6281                                               /*use_default_args=*/true);
6282
6283               /* Don't process further if one of the levels fails.  */
6284               if (a == error_mark_node)
6285                 {
6286                   /* Restore the ARGLIST to its full size.  */
6287                   TREE_VEC_LENGTH (arglist) = saved_depth;
6288                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6289                 }
6290
6291               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6292
6293               /* We temporarily reduce the length of the ARGLIST so
6294                  that coerce_template_parms will see only the arguments
6295                  corresponding to the template parameters it is
6296                  examining.  */
6297               TREE_VEC_LENGTH (arglist)--;
6298             }
6299
6300           /* Restore the ARGLIST to its full size.  */
6301           TREE_VEC_LENGTH (arglist) = saved_depth;
6302
6303           arglist = bound_args;
6304         }
6305       else
6306         arglist
6307           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6308                                    INNERMOST_TEMPLATE_ARGS (arglist),
6309                                    gen_tmpl,
6310                                    complain,
6311                                    /*require_all_args=*/true,
6312                                    /*use_default_args=*/true);
6313
6314       if (arglist == error_mark_node)
6315         /* We were unable to bind the arguments.  */
6316         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6317
6318       /* In the scope of a template class, explicit references to the
6319          template class refer to the type of the template, not any
6320          instantiation of it.  For example, in:
6321
6322            template <class T> class C { void f(C<T>); }
6323
6324          the `C<T>' is just the same as `C'.  Outside of the
6325          class, however, such a reference is an instantiation.  */
6326       if ((entering_scope
6327            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6328            || currently_open_class (template_type))
6329           /* comp_template_args is expensive, check it last.  */
6330           && comp_template_args (TYPE_TI_ARGS (template_type),
6331                                  arglist))
6332         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6333
6334       /* If we already have this specialization, return it.  */
6335       elt.tmpl = gen_tmpl;
6336       elt.args = arglist;
6337       hash = hash_specialization (&elt);
6338       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6339                                                   &elt, hash);
6340
6341       if (entry)
6342         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6343
6344       /* This type is a "partial instantiation" if any of the template
6345          arguments still involve template parameters.  Note that we set
6346          IS_PARTIAL_INSTANTIATION for partial specializations as
6347          well.  */
6348       is_partial_instantiation = uses_template_parms (arglist);
6349
6350       /* If the deduced arguments are invalid, then the binding
6351          failed.  */
6352       if (!is_partial_instantiation
6353           && check_instantiated_args (gen_tmpl,
6354                                       INNERMOST_TEMPLATE_ARGS (arglist),
6355                                       complain))
6356         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6357
6358       if (!is_partial_instantiation
6359           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6360           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6361           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6362         {
6363           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6364                                       DECL_NAME (gen_tmpl),
6365                                       /*tag_scope=*/ts_global);
6366           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6367         }
6368
6369       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6370                         complain, in_decl);
6371       if (!context)
6372         context = global_namespace;
6373
6374       /* Create the type.  */
6375       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6376         {
6377           if (!is_partial_instantiation)
6378             {
6379               set_current_access_from_decl (TYPE_NAME (template_type));
6380               t = start_enum (TYPE_IDENTIFIER (template_type),
6381                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6382                                       arglist, complain, in_decl),
6383                               SCOPED_ENUM_P (template_type));
6384             }
6385           else
6386             {
6387               /* We don't want to call start_enum for this type, since
6388                  the values for the enumeration constants may involve
6389                  template parameters.  And, no one should be interested
6390                  in the enumeration constants for such a type.  */
6391               t = cxx_make_type (ENUMERAL_TYPE);
6392               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6393             }
6394         }
6395       else
6396         {
6397           t = make_class_type (TREE_CODE (template_type));
6398           CLASSTYPE_DECLARED_CLASS (t)
6399             = CLASSTYPE_DECLARED_CLASS (template_type);
6400           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6401           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6402
6403           /* A local class.  Make sure the decl gets registered properly.  */
6404           if (context == current_function_decl)
6405             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6406
6407           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6408             /* This instantiation is another name for the primary
6409                template type. Set the TYPE_CANONICAL field
6410                appropriately. */
6411             TYPE_CANONICAL (t) = template_type;
6412           else if (any_template_arguments_need_structural_equality_p (arglist))
6413             /* Some of the template arguments require structural
6414                equality testing, so this template class requires
6415                structural equality testing. */
6416             SET_TYPE_STRUCTURAL_EQUALITY (t);
6417         }
6418
6419       /* If we called start_enum or pushtag above, this information
6420          will already be set up.  */
6421       if (!TYPE_NAME (t))
6422         {
6423           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6424
6425           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6426           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6427           DECL_SOURCE_LOCATION (type_decl)
6428             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6429         }
6430       else
6431         type_decl = TYPE_NAME (t);
6432
6433       TREE_PRIVATE (type_decl)
6434         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6435       TREE_PROTECTED (type_decl)
6436         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6437       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6438         {
6439           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6440           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6441         }
6442
6443       /* Set up the template information.  We have to figure out which
6444          template is the immediate parent if this is a full
6445          instantiation.  */
6446       if (parm_depth == 1 || is_partial_instantiation
6447           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6448         /* This case is easy; there are no member templates involved.  */
6449         found = gen_tmpl;
6450       else
6451         {
6452           /* This is a full instantiation of a member template.  Find
6453              the partial instantiation of which this is an instance.  */
6454
6455           /* Temporarily reduce by one the number of levels in the ARGLIST
6456              so as to avoid comparing the last set of arguments.  */
6457           TREE_VEC_LENGTH (arglist)--;
6458           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6459           TREE_VEC_LENGTH (arglist)++;
6460           found = CLASSTYPE_TI_TEMPLATE (found);
6461         }
6462
6463       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6464
6465       elt.spec = t;
6466       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6467                                                        &elt, hash, INSERT);
6468       *slot = GGC_NEW (spec_entry);
6469       **slot = elt;
6470
6471       /* Note this use of the partial instantiation so we can check it
6472          later in maybe_process_partial_specialization.  */
6473       DECL_TEMPLATE_INSTANTIATIONS (templ)
6474         = tree_cons (arglist, t,
6475                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6476
6477       if (TREE_CODE (t) == ENUMERAL_TYPE
6478           && !is_partial_instantiation)
6479         /* Now that the type has been registered on the instantiations
6480            list, we set up the enumerators.  Because the enumeration
6481            constants may involve the enumeration type itself, we make
6482            sure to register the type first, and then create the
6483            constants.  That way, doing tsubst_expr for the enumeration
6484            constants won't result in recursive calls here; we'll find
6485            the instantiation and exit above.  */
6486         tsubst_enum (template_type, t, arglist);
6487
6488       if (is_partial_instantiation)
6489         /* If the type makes use of template parameters, the
6490            code that generates debugging information will crash.  */
6491         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6492
6493       /* Possibly limit visibility based on template args.  */
6494       TREE_PUBLIC (type_decl) = 1;
6495       determine_visibility (type_decl);
6496
6497       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6498     }
6499   timevar_pop (TV_NAME_LOOKUP);
6500 }
6501 \f
6502 struct pair_fn_data
6503 {
6504   tree_fn_t fn;
6505   void *data;
6506   /* True when we should also visit template parameters that occur in
6507      non-deduced contexts.  */
6508   bool include_nondeduced_p;
6509   struct pointer_set_t *visited;
6510 };
6511
6512 /* Called from for_each_template_parm via walk_tree.  */
6513
6514 static tree
6515 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6516 {
6517   tree t = *tp;
6518   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6519   tree_fn_t fn = pfd->fn;
6520   void *data = pfd->data;
6521
6522   if (TYPE_P (t)
6523       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6524       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6525                                  pfd->include_nondeduced_p))
6526     return error_mark_node;
6527
6528   switch (TREE_CODE (t))
6529     {
6530     case RECORD_TYPE:
6531       if (TYPE_PTRMEMFUNC_P (t))
6532         break;
6533       /* Fall through.  */
6534
6535     case UNION_TYPE:
6536     case ENUMERAL_TYPE:
6537       if (!TYPE_TEMPLATE_INFO (t))
6538         *walk_subtrees = 0;
6539       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6540                                        fn, data, pfd->visited, 
6541                                        pfd->include_nondeduced_p))
6542         return error_mark_node;
6543       break;
6544
6545     case INTEGER_TYPE:
6546       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6547                                   fn, data, pfd->visited, 
6548                                   pfd->include_nondeduced_p)
6549           || for_each_template_parm (TYPE_MAX_VALUE (t),
6550                                      fn, data, pfd->visited,
6551                                      pfd->include_nondeduced_p))
6552         return error_mark_node;
6553       break;
6554
6555     case METHOD_TYPE:
6556       /* Since we're not going to walk subtrees, we have to do this
6557          explicitly here.  */
6558       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6559                                   pfd->visited, pfd->include_nondeduced_p))
6560         return error_mark_node;
6561       /* Fall through.  */
6562
6563     case FUNCTION_TYPE:
6564       /* Check the return type.  */
6565       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6566                                   pfd->include_nondeduced_p))
6567         return error_mark_node;
6568
6569       /* Check the parameter types.  Since default arguments are not
6570          instantiated until they are needed, the TYPE_ARG_TYPES may
6571          contain expressions that involve template parameters.  But,
6572          no-one should be looking at them yet.  And, once they're
6573          instantiated, they don't contain template parameters, so
6574          there's no point in looking at them then, either.  */
6575       {
6576         tree parm;
6577
6578         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6579           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6580                                       pfd->visited, pfd->include_nondeduced_p))
6581             return error_mark_node;
6582
6583         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6584            want walk_tree walking into them itself.  */
6585         *walk_subtrees = 0;
6586       }
6587       break;
6588
6589     case TYPEOF_TYPE:
6590       if (pfd->include_nondeduced_p
6591           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6592                                      pfd->visited, 
6593                                      pfd->include_nondeduced_p))
6594         return error_mark_node;
6595       break;
6596
6597     case FUNCTION_DECL:
6598     case VAR_DECL:
6599       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6600           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6601                                      pfd->visited, pfd->include_nondeduced_p))
6602         return error_mark_node;
6603       /* Fall through.  */
6604
6605     case PARM_DECL:
6606     case CONST_DECL:
6607       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6608           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6609                                      pfd->visited, pfd->include_nondeduced_p))
6610         return error_mark_node;
6611       if (DECL_CONTEXT (t)
6612           && pfd->include_nondeduced_p
6613           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6614                                      pfd->visited, pfd->include_nondeduced_p))
6615         return error_mark_node;
6616       break;
6617
6618     case BOUND_TEMPLATE_TEMPLATE_PARM:
6619       /* Record template parameters such as `T' inside `TT<T>'.  */
6620       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6621                                   pfd->include_nondeduced_p))
6622         return error_mark_node;
6623       /* Fall through.  */
6624
6625     case TEMPLATE_TEMPLATE_PARM:
6626     case TEMPLATE_TYPE_PARM:
6627     case TEMPLATE_PARM_INDEX:
6628       if (fn && (*fn)(t, data))
6629         return error_mark_node;
6630       else if (!fn)
6631         return error_mark_node;
6632       break;
6633
6634     case TEMPLATE_DECL:
6635       /* A template template parameter is encountered.  */
6636       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6637           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6638                                      pfd->include_nondeduced_p))
6639         return error_mark_node;
6640
6641       /* Already substituted template template parameter */
6642       *walk_subtrees = 0;
6643       break;
6644
6645     case TYPENAME_TYPE:
6646       if (!fn
6647           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6648                                      data, pfd->visited, 
6649                                      pfd->include_nondeduced_p))
6650         return error_mark_node;
6651       break;
6652
6653     case CONSTRUCTOR:
6654       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6655           && pfd->include_nondeduced_p
6656           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6657                                      (TREE_TYPE (t)), fn, data,
6658                                      pfd->visited, pfd->include_nondeduced_p))
6659         return error_mark_node;
6660       break;
6661
6662     case INDIRECT_REF:
6663     case COMPONENT_REF:
6664       /* If there's no type, then this thing must be some expression
6665          involving template parameters.  */
6666       if (!fn && !TREE_TYPE (t))
6667         return error_mark_node;
6668       break;
6669
6670     case MODOP_EXPR:
6671     case CAST_EXPR:
6672     case REINTERPRET_CAST_EXPR:
6673     case CONST_CAST_EXPR:
6674     case STATIC_CAST_EXPR:
6675     case DYNAMIC_CAST_EXPR:
6676     case ARROW_EXPR:
6677     case DOTSTAR_EXPR:
6678     case TYPEID_EXPR:
6679     case PSEUDO_DTOR_EXPR:
6680       if (!fn)
6681         return error_mark_node;
6682       break;
6683
6684     default:
6685       break;
6686     }
6687
6688   /* We didn't find any template parameters we liked.  */
6689   return NULL_TREE;
6690 }
6691
6692 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6693    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6694    call FN with the parameter and the DATA.
6695    If FN returns nonzero, the iteration is terminated, and
6696    for_each_template_parm returns 1.  Otherwise, the iteration
6697    continues.  If FN never returns a nonzero value, the value
6698    returned by for_each_template_parm is 0.  If FN is NULL, it is
6699    considered to be the function which always returns 1.
6700
6701    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6702    parameters that occur in non-deduced contexts.  When false, only
6703    visits those template parameters that can be deduced.  */
6704
6705 static int
6706 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6707                         struct pointer_set_t *visited,
6708                         bool include_nondeduced_p)
6709 {
6710   struct pair_fn_data pfd;
6711   int result;
6712
6713   /* Set up.  */
6714   pfd.fn = fn;
6715   pfd.data = data;
6716   pfd.include_nondeduced_p = include_nondeduced_p;
6717
6718   /* Walk the tree.  (Conceptually, we would like to walk without
6719      duplicates, but for_each_template_parm_r recursively calls
6720      for_each_template_parm, so we would need to reorganize a fair
6721      bit to use walk_tree_without_duplicates, so we keep our own
6722      visited list.)  */
6723   if (visited)
6724     pfd.visited = visited;
6725   else
6726     pfd.visited = pointer_set_create ();
6727   result = cp_walk_tree (&t,
6728                          for_each_template_parm_r,
6729                          &pfd,
6730                          pfd.visited) != NULL_TREE;
6731
6732   /* Clean up.  */
6733   if (!visited)
6734     {
6735       pointer_set_destroy (pfd.visited);
6736       pfd.visited = 0;
6737     }
6738
6739   return result;
6740 }
6741
6742 /* Returns true if T depends on any template parameter.  */
6743
6744 int
6745 uses_template_parms (tree t)
6746 {
6747   bool dependent_p;
6748   int saved_processing_template_decl;
6749
6750   saved_processing_template_decl = processing_template_decl;
6751   if (!saved_processing_template_decl)
6752     processing_template_decl = 1;
6753   if (TYPE_P (t))
6754     dependent_p = dependent_type_p (t);
6755   else if (TREE_CODE (t) == TREE_VEC)
6756     dependent_p = any_dependent_template_arguments_p (t);
6757   else if (TREE_CODE (t) == TREE_LIST)
6758     dependent_p = (uses_template_parms (TREE_VALUE (t))
6759                    || uses_template_parms (TREE_CHAIN (t)));
6760   else if (TREE_CODE (t) == TYPE_DECL)
6761     dependent_p = dependent_type_p (TREE_TYPE (t));
6762   else if (DECL_P (t)
6763            || EXPR_P (t)
6764            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6765            || TREE_CODE (t) == OVERLOAD
6766            || TREE_CODE (t) == BASELINK
6767            || TREE_CODE (t) == IDENTIFIER_NODE
6768            || TREE_CODE (t) == TRAIT_EXPR
6769            || TREE_CODE (t) == CONSTRUCTOR
6770            || CONSTANT_CLASS_P (t))
6771     dependent_p = (type_dependent_expression_p (t)
6772                    || value_dependent_expression_p (t));
6773   else
6774     {
6775       gcc_assert (t == error_mark_node);
6776       dependent_p = false;
6777     }
6778
6779   processing_template_decl = saved_processing_template_decl;
6780
6781   return dependent_p;
6782 }
6783
6784 /* Returns true if T depends on any template parameter with level LEVEL.  */
6785
6786 int
6787 uses_template_parms_level (tree t, int level)
6788 {
6789   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6790                                  /*include_nondeduced_p=*/true);
6791 }
6792
6793 static int tinst_depth;
6794 extern int max_tinst_depth;
6795 #ifdef GATHER_STATISTICS
6796 int depth_reached;
6797 #endif
6798 static int tinst_level_tick;
6799 static int last_template_error_tick;
6800
6801 /* We're starting to instantiate D; record the template instantiation context
6802    for diagnostics and to restore it later.  */
6803
6804 static int
6805 push_tinst_level (tree d)
6806 {
6807   struct tinst_level *new_level;
6808
6809   if (tinst_depth >= max_tinst_depth)
6810     {
6811       /* If the instantiation in question still has unbound template parms,
6812          we don't really care if we can't instantiate it, so just return.
6813          This happens with base instantiation for implicit `typename'.  */
6814       if (uses_template_parms (d))
6815         return 0;
6816
6817       last_template_error_tick = tinst_level_tick;
6818       error ("template instantiation depth exceeds maximum of %d (use "
6819              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6820              max_tinst_depth, d);
6821
6822       print_instantiation_context ();
6823
6824       return 0;
6825     }
6826
6827   new_level = GGC_NEW (struct tinst_level);
6828   new_level->decl = d;
6829   new_level->locus = input_location;
6830   new_level->in_system_header_p = in_system_header;
6831   new_level->next = current_tinst_level;
6832   current_tinst_level = new_level;
6833
6834   ++tinst_depth;
6835 #ifdef GATHER_STATISTICS
6836   if (tinst_depth > depth_reached)
6837     depth_reached = tinst_depth;
6838 #endif
6839
6840   ++tinst_level_tick;
6841   return 1;
6842 }
6843
6844 /* We're done instantiating this template; return to the instantiation
6845    context.  */
6846
6847 static void
6848 pop_tinst_level (void)
6849 {
6850   /* Restore the filename and line number stashed away when we started
6851      this instantiation.  */
6852   input_location = current_tinst_level->locus;
6853   current_tinst_level = current_tinst_level->next;
6854   --tinst_depth;
6855   ++tinst_level_tick;
6856 }
6857
6858 /* We're instantiating a deferred template; restore the template
6859    instantiation context in which the instantiation was requested, which
6860    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6861
6862 static tree
6863 reopen_tinst_level (struct tinst_level *level)
6864 {
6865   struct tinst_level *t;
6866
6867   tinst_depth = 0;
6868   for (t = level; t; t = t->next)
6869     ++tinst_depth;
6870
6871   current_tinst_level = level;
6872   pop_tinst_level ();
6873   return level->decl;
6874 }
6875
6876 /* Returns the TINST_LEVEL which gives the original instantiation
6877    context.  */
6878
6879 struct tinst_level *
6880 outermost_tinst_level (void)
6881 {
6882   struct tinst_level *level = current_tinst_level;
6883   if (level)
6884     while (level->next)
6885       level = level->next;
6886   return level;
6887 }
6888
6889 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6890
6891 bool
6892 parameter_of_template_p (tree parm, tree templ)
6893 {
6894   tree parms;
6895   int i;
6896
6897   if (!parm || !templ)
6898     return false;
6899
6900   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6901   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6902
6903   parms = DECL_TEMPLATE_PARMS (templ);
6904   parms = INNERMOST_TEMPLATE_PARMS (parms);
6905
6906   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6907     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6908       return true;
6909
6910   return false;
6911 }
6912
6913 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6914    vector of template arguments, as for tsubst.
6915
6916    Returns an appropriate tsubst'd friend declaration.  */
6917
6918 static tree
6919 tsubst_friend_function (tree decl, tree args)
6920 {
6921   tree new_friend;
6922
6923   if (TREE_CODE (decl) == FUNCTION_DECL
6924       && DECL_TEMPLATE_INSTANTIATION (decl)
6925       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6926     /* This was a friend declared with an explicit template
6927        argument list, e.g.:
6928
6929        friend void f<>(T);
6930
6931        to indicate that f was a template instantiation, not a new
6932        function declaration.  Now, we have to figure out what
6933        instantiation of what template.  */
6934     {
6935       tree template_id, arglist, fns;
6936       tree new_args;
6937       tree tmpl;
6938       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6939
6940       /* Friend functions are looked up in the containing namespace scope.
6941          We must enter that scope, to avoid finding member functions of the
6942          current class with same name.  */
6943       push_nested_namespace (ns);
6944       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6945                          tf_warning_or_error, NULL_TREE,
6946                          /*integral_constant_expression_p=*/false);
6947       pop_nested_namespace (ns);
6948       arglist = tsubst (DECL_TI_ARGS (decl), args,
6949                         tf_warning_or_error, NULL_TREE);
6950       template_id = lookup_template_function (fns, arglist);
6951
6952       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6953       tmpl = determine_specialization (template_id, new_friend,
6954                                        &new_args,
6955                                        /*need_member_template=*/0,
6956                                        TREE_VEC_LENGTH (args),
6957                                        tsk_none);
6958       return instantiate_template (tmpl, new_args, tf_error);
6959     }
6960
6961   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6962
6963   /* The NEW_FRIEND will look like an instantiation, to the
6964      compiler, but is not an instantiation from the point of view of
6965      the language.  For example, we might have had:
6966
6967      template <class T> struct S {
6968        template <class U> friend void f(T, U);
6969      };
6970
6971      Then, in S<int>, template <class U> void f(int, U) is not an
6972      instantiation of anything.  */
6973   if (new_friend == error_mark_node)
6974     return error_mark_node;
6975
6976   DECL_USE_TEMPLATE (new_friend) = 0;
6977   if (TREE_CODE (decl) == TEMPLATE_DECL)
6978     {
6979       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6980       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6981         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6982     }
6983
6984   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6985      is not a template instantiation and should not be mangled like
6986      one.  Therefore, we forget the mangling here; we'll recompute it
6987      later if we need it.  */
6988   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6989     {
6990       SET_DECL_RTL (new_friend, NULL_RTX);
6991       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6992     }
6993
6994   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6995     {
6996       tree old_decl;
6997       tree new_friend_template_info;
6998       tree new_friend_result_template_info;
6999       tree ns;
7000       int  new_friend_is_defn;
7001
7002       /* We must save some information from NEW_FRIEND before calling
7003          duplicate decls since that function will free NEW_FRIEND if
7004          possible.  */
7005       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7006       new_friend_is_defn =
7007             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7008                            (template_for_substitution (new_friend)))
7009              != NULL_TREE);
7010       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7011         {
7012           /* This declaration is a `primary' template.  */
7013           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7014
7015           new_friend_result_template_info
7016             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7017         }
7018       else
7019         new_friend_result_template_info = NULL_TREE;
7020
7021       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7022       if (new_friend_is_defn)
7023         DECL_INITIAL (new_friend) = error_mark_node;
7024
7025       /* Inside pushdecl_namespace_level, we will push into the
7026          current namespace. However, the friend function should go
7027          into the namespace of the template.  */
7028       ns = decl_namespace_context (new_friend);
7029       push_nested_namespace (ns);
7030       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7031       pop_nested_namespace (ns);
7032
7033       if (old_decl == error_mark_node)
7034         return error_mark_node;
7035
7036       if (old_decl != new_friend)
7037         {
7038           /* This new friend declaration matched an existing
7039              declaration.  For example, given:
7040
7041                template <class T> void f(T);
7042                template <class U> class C {
7043                  template <class T> friend void f(T) {}
7044                };
7045
7046              the friend declaration actually provides the definition
7047              of `f', once C has been instantiated for some type.  So,
7048              old_decl will be the out-of-class template declaration,
7049              while new_friend is the in-class definition.
7050
7051              But, if `f' was called before this point, the
7052              instantiation of `f' will have DECL_TI_ARGS corresponding
7053              to `T' but not to `U', references to which might appear
7054              in the definition of `f'.  Previously, the most general
7055              template for an instantiation of `f' was the out-of-class
7056              version; now it is the in-class version.  Therefore, we
7057              run through all specialization of `f', adding to their
7058              DECL_TI_ARGS appropriately.  In particular, they need a
7059              new set of outer arguments, corresponding to the
7060              arguments for this class instantiation.
7061
7062              The same situation can arise with something like this:
7063
7064                friend void f(int);
7065                template <class T> class C {
7066                  friend void f(T) {}
7067                };
7068
7069              when `C<int>' is instantiated.  Now, `f(int)' is defined
7070              in the class.  */
7071
7072           if (!new_friend_is_defn)
7073             /* On the other hand, if the in-class declaration does
7074                *not* provide a definition, then we don't want to alter
7075                existing definitions.  We can just leave everything
7076                alone.  */
7077             ;
7078           else
7079             {
7080               tree new_template = TI_TEMPLATE (new_friend_template_info);
7081               tree new_args = TI_ARGS (new_friend_template_info);
7082
7083               /* Overwrite whatever template info was there before, if
7084                  any, with the new template information pertaining to
7085                  the declaration.  */
7086               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7087
7088               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7089                 /* We should have called reregister_specialization in
7090                    duplicate_decls.  */
7091                 gcc_assert (retrieve_specialization (new_template,
7092                                                      new_args, 0)
7093                             == old_decl);
7094               else
7095                 {
7096                   tree t;
7097
7098                   /* Indicate that the old function template is a partial
7099                      instantiation.  */
7100                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7101                     = new_friend_result_template_info;
7102
7103                   gcc_assert (new_template
7104                               == most_general_template (new_template));
7105                   gcc_assert (new_template != old_decl);
7106
7107                   /* Reassign any specializations already in the hash table
7108                      to the new more general template, and add the
7109                      additional template args.  */
7110                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7111                        t != NULL_TREE;
7112                        t = TREE_CHAIN (t))
7113                     {
7114                       tree spec = TREE_VALUE (t);
7115                       spec_entry elt;
7116
7117                       elt.tmpl = old_decl;
7118                       elt.args = DECL_TI_ARGS (spec);
7119                       elt.spec = NULL_TREE;
7120
7121                       htab_remove_elt (decl_specializations, &elt);
7122
7123                       DECL_TI_ARGS (spec)
7124                         = add_outermost_template_args (new_args,
7125                                                        DECL_TI_ARGS (spec));
7126
7127                       register_specialization
7128                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7129
7130                     }
7131                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7132                 }
7133             }
7134
7135           /* The information from NEW_FRIEND has been merged into OLD_DECL
7136              by duplicate_decls.  */
7137           new_friend = old_decl;
7138         }
7139     }
7140   else
7141     {
7142       tree context = DECL_CONTEXT (new_friend);
7143       bool dependent_p;
7144
7145       /* In the code
7146            template <class T> class C {
7147              template <class U> friend void C1<U>::f (); // case 1
7148              friend void C2<T>::f ();                    // case 2
7149            };
7150          we only need to make sure CONTEXT is a complete type for
7151          case 2.  To distinguish between the two cases, we note that
7152          CONTEXT of case 1 remains dependent type after tsubst while
7153          this isn't true for case 2.  */
7154       ++processing_template_decl;
7155       dependent_p = dependent_type_p (context);
7156       --processing_template_decl;
7157
7158       if (!dependent_p
7159           && !complete_type_or_else (context, NULL_TREE))
7160         return error_mark_node;
7161
7162       if (COMPLETE_TYPE_P (context))
7163         {
7164           /* Check to see that the declaration is really present, and,
7165              possibly obtain an improved declaration.  */
7166           tree fn = check_classfn (context,
7167                                    new_friend, NULL_TREE);
7168
7169           if (fn)
7170             new_friend = fn;
7171         }
7172     }
7173
7174   return new_friend;
7175 }
7176
7177 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7178    template arguments, as for tsubst.
7179
7180    Returns an appropriate tsubst'd friend type or error_mark_node on
7181    failure.  */
7182
7183 static tree
7184 tsubst_friend_class (tree friend_tmpl, tree args)
7185 {
7186   tree friend_type;
7187   tree tmpl;
7188   tree context;
7189
7190   context = DECL_CONTEXT (friend_tmpl);
7191
7192   if (context)
7193     {
7194       if (TREE_CODE (context) == NAMESPACE_DECL)
7195         push_nested_namespace (context);
7196       else
7197         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7198     }
7199
7200   /* Look for a class template declaration.  We look for hidden names
7201      because two friend declarations of the same template are the
7202      same.  For example, in:
7203
7204        struct A { 
7205          template <typename> friend class F;
7206        };
7207        template <typename> struct B { 
7208          template <typename> friend class F;
7209        };
7210
7211      both F templates are the same.  */
7212   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7213                            /*block_p=*/true, 0, 
7214                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7215
7216   /* But, if we don't find one, it might be because we're in a
7217      situation like this:
7218
7219        template <class T>
7220        struct S {
7221          template <class U>
7222          friend struct S;
7223        };
7224
7225      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7226      for `S<int>', not the TEMPLATE_DECL.  */
7227   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7228     {
7229       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7230       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7231     }
7232
7233   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7234     {
7235       /* The friend template has already been declared.  Just
7236          check to see that the declarations match, and install any new
7237          default parameters.  We must tsubst the default parameters,
7238          of course.  We only need the innermost template parameters
7239          because that is all that redeclare_class_template will look
7240          at.  */
7241       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7242           > TMPL_ARGS_DEPTH (args))
7243         {
7244           tree parms;
7245           location_t saved_input_location;
7246           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7247                                          args, tf_warning_or_error);
7248
7249           saved_input_location = input_location;
7250           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7251           redeclare_class_template (TREE_TYPE (tmpl), parms);
7252           input_location = saved_input_location;
7253           
7254         }
7255
7256       friend_type = TREE_TYPE (tmpl);
7257     }
7258   else
7259     {
7260       /* The friend template has not already been declared.  In this
7261          case, the instantiation of the template class will cause the
7262          injection of this template into the global scope.  */
7263       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7264       if (tmpl == error_mark_node)
7265         return error_mark_node;
7266
7267       /* The new TMPL is not an instantiation of anything, so we
7268          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7269          the new type because that is supposed to be the corresponding
7270          template decl, i.e., TMPL.  */
7271       DECL_USE_TEMPLATE (tmpl) = 0;
7272       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7273       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7274       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7275         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7276
7277       /* Inject this template into the global scope.  */
7278       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7279     }
7280
7281   if (context)
7282     {
7283       if (TREE_CODE (context) == NAMESPACE_DECL)
7284         pop_nested_namespace (context);
7285       else
7286         pop_nested_class ();
7287     }
7288
7289   return friend_type;
7290 }
7291
7292 /* Returns zero if TYPE cannot be completed later due to circularity.
7293    Otherwise returns one.  */
7294
7295 static int
7296 can_complete_type_without_circularity (tree type)
7297 {
7298   if (type == NULL_TREE || type == error_mark_node)
7299     return 0;
7300   else if (COMPLETE_TYPE_P (type))
7301     return 1;
7302   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7303     return can_complete_type_without_circularity (TREE_TYPE (type));
7304   else if (CLASS_TYPE_P (type)
7305            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7306     return 0;
7307   else
7308     return 1;
7309 }
7310
7311 /* Apply any attributes which had to be deferred until instantiation
7312    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7313    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7314
7315 static void
7316 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7317                                 tree args, tsubst_flags_t complain, tree in_decl)
7318 {
7319   tree last_dep = NULL_TREE;
7320   tree t;
7321   tree *p;
7322
7323   for (t = attributes; t; t = TREE_CHAIN (t))
7324     if (ATTR_IS_DEPENDENT (t))
7325       {
7326         last_dep = t;
7327         attributes = copy_list (attributes);
7328         break;
7329       }
7330
7331   if (DECL_P (*decl_p))
7332     {
7333       if (TREE_TYPE (*decl_p) == error_mark_node)
7334         return;
7335       p = &DECL_ATTRIBUTES (*decl_p);
7336     }
7337   else
7338     p = &TYPE_ATTRIBUTES (*decl_p);
7339
7340   if (last_dep)
7341     {
7342       tree late_attrs = NULL_TREE;
7343       tree *q = &late_attrs;
7344
7345       for (*p = attributes; *p; )
7346         {
7347           t = *p;
7348           if (ATTR_IS_DEPENDENT (t))
7349             {
7350               *p = TREE_CHAIN (t);
7351               TREE_CHAIN (t) = NULL_TREE;
7352               /* If the first attribute argument is an identifier, don't
7353                  pass it through tsubst.  Attributes like mode, format,
7354                  cleanup and several target specific attributes expect it
7355                  unmodified.  */
7356               if (TREE_VALUE (t)
7357                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7358                   && TREE_VALUE (TREE_VALUE (t))
7359                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7360                       == IDENTIFIER_NODE))
7361                 {
7362                   tree chain
7363                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7364                                    in_decl,
7365                                    /*integral_constant_expression_p=*/false);
7366                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7367                     TREE_VALUE (t)
7368                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7369                                    chain);
7370                 }
7371               else
7372                 TREE_VALUE (t)
7373                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7374                                  /*integral_constant_expression_p=*/false);
7375               *q = t;
7376               q = &TREE_CHAIN (t);
7377             }
7378           else
7379             p = &TREE_CHAIN (t);
7380         }
7381
7382       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7383     }
7384 }
7385
7386 /* Perform (or defer) access check for typedefs that were referenced
7387    from within the template TMPL code.
7388    This is a subroutine of instantiate_template and instantiate_class_template.
7389    TMPL is the template to consider and TARGS is the list of arguments of
7390    that template.  */
7391
7392 static void
7393 perform_typedefs_access_check (tree tmpl, tree targs)
7394 {
7395   location_t saved_location;
7396   int i;
7397   qualified_typedef_usage_t *iter;
7398
7399   if (!tmpl
7400       || (!CLASS_TYPE_P (tmpl)
7401           && TREE_CODE (tmpl) != FUNCTION_DECL))
7402     return;
7403
7404   saved_location = input_location;
7405   for (i = 0;
7406        VEC_iterate (qualified_typedef_usage_t,
7407                     get_types_needing_access_check (tmpl),
7408                     i, iter);
7409         ++i)
7410     {
7411       tree type_decl = iter->typedef_decl;
7412       tree type_scope = iter->context;
7413
7414       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7415         continue;
7416
7417       if (uses_template_parms (type_decl))
7418         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7419       if (uses_template_parms (type_scope))
7420         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7421
7422       /* Make access check error messages point to the location
7423          of the use of the typedef.  */
7424       input_location = iter->locus;
7425       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7426                                      type_decl, type_decl);
7427     }
7428     input_location = saved_location;
7429 }
7430
7431 tree
7432 instantiate_class_template (tree type)
7433 {
7434   tree templ, args, pattern, t, member;
7435   tree typedecl;
7436   tree pbinfo;
7437   tree base_list;
7438   unsigned int saved_maximum_field_alignment;
7439
7440   if (type == error_mark_node)
7441     return error_mark_node;
7442
7443   if (TYPE_BEING_DEFINED (type)
7444       || COMPLETE_TYPE_P (type)
7445       || uses_template_parms (type))
7446     return type;
7447
7448   /* Figure out which template is being instantiated.  */
7449   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7450   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7451
7452   /* Determine what specialization of the original template to
7453      instantiate.  */
7454   t = most_specialized_class (type, templ);
7455   if (t == error_mark_node)
7456     {
7457       TYPE_BEING_DEFINED (type) = 1;
7458       return error_mark_node;
7459     }
7460   else if (t)
7461     {
7462       /* This TYPE is actually an instantiation of a partial
7463          specialization.  We replace the innermost set of ARGS with
7464          the arguments appropriate for substitution.  For example,
7465          given:
7466
7467            template <class T> struct S {};
7468            template <class T> struct S<T*> {};
7469
7470          and supposing that we are instantiating S<int*>, ARGS will
7471          presently be {int*} -- but we need {int}.  */
7472       pattern = TREE_TYPE (t);
7473       args = TREE_PURPOSE (t);
7474     }
7475   else
7476     {
7477       pattern = TREE_TYPE (templ);
7478       args = CLASSTYPE_TI_ARGS (type);
7479     }
7480
7481   /* If the template we're instantiating is incomplete, then clearly
7482      there's nothing we can do.  */
7483   if (!COMPLETE_TYPE_P (pattern))
7484     return type;
7485
7486   /* If we've recursively instantiated too many templates, stop.  */
7487   if (! push_tinst_level (type))
7488     return type;
7489
7490   /* Now we're really doing the instantiation.  Mark the type as in
7491      the process of being defined.  */
7492   TYPE_BEING_DEFINED (type) = 1;
7493
7494   /* We may be in the middle of deferred access check.  Disable
7495      it now.  */
7496   push_deferring_access_checks (dk_no_deferred);
7497
7498   push_to_top_level ();
7499   /* Use #pragma pack from the template context.  */
7500   saved_maximum_field_alignment = maximum_field_alignment;
7501   maximum_field_alignment = TYPE_PRECISION (pattern);
7502
7503   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7504
7505   /* Set the input location to the most specialized template definition.
7506      This is needed if tsubsting causes an error.  */
7507   typedecl = TYPE_MAIN_DECL (pattern);
7508   input_location = DECL_SOURCE_LOCATION (typedecl);
7509
7510   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7511   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7512   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7513   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7514   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7515   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7516   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7517   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7518   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7519   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7520   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7521   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7522   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7523   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7524   if (ANON_AGGR_TYPE_P (pattern))
7525     SET_ANON_AGGR_TYPE_P (type);
7526   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7527     {
7528       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7529       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7530     }
7531
7532   pbinfo = TYPE_BINFO (pattern);
7533
7534   /* We should never instantiate a nested class before its enclosing
7535      class; we need to look up the nested class by name before we can
7536      instantiate it, and that lookup should instantiate the enclosing
7537      class.  */
7538   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7539               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7540               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7541
7542   base_list = NULL_TREE;
7543   if (BINFO_N_BASE_BINFOS (pbinfo))
7544     {
7545       tree pbase_binfo;
7546       tree context = TYPE_CONTEXT (type);
7547       tree pushed_scope;
7548       int i;
7549
7550       /* We must enter the scope containing the type, as that is where
7551          the accessibility of types named in dependent bases are
7552          looked up from.  */
7553       pushed_scope = push_scope (context ? context : global_namespace);
7554
7555       /* Substitute into each of the bases to determine the actual
7556          basetypes.  */
7557       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7558         {
7559           tree base;
7560           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7561           tree expanded_bases = NULL_TREE;
7562           int idx, len = 1;
7563
7564           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7565             {
7566               expanded_bases = 
7567                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7568                                        args, tf_error, NULL_TREE);
7569               if (expanded_bases == error_mark_node)
7570                 continue;
7571
7572               len = TREE_VEC_LENGTH (expanded_bases);
7573             }
7574
7575           for (idx = 0; idx < len; idx++)
7576             {
7577               if (expanded_bases)
7578                 /* Extract the already-expanded base class.  */
7579                 base = TREE_VEC_ELT (expanded_bases, idx);
7580               else
7581                 /* Substitute to figure out the base class.  */
7582                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7583                                NULL_TREE);
7584
7585               if (base == error_mark_node)
7586                 continue;
7587
7588               base_list = tree_cons (access, base, base_list);
7589               if (BINFO_VIRTUAL_P (pbase_binfo))
7590                 TREE_TYPE (base_list) = integer_type_node;
7591             }
7592         }
7593
7594       /* The list is now in reverse order; correct that.  */
7595       base_list = nreverse (base_list);
7596
7597       if (pushed_scope)
7598         pop_scope (pushed_scope);
7599     }
7600   /* Now call xref_basetypes to set up all the base-class
7601      information.  */
7602   xref_basetypes (type, base_list);
7603
7604   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7605                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7606                                   args, tf_error, NULL_TREE);
7607
7608   /* Now that our base classes are set up, enter the scope of the
7609      class, so that name lookups into base classes, etc. will work
7610      correctly.  This is precisely analogous to what we do in
7611      begin_class_definition when defining an ordinary non-template
7612      class, except we also need to push the enclosing classes.  */
7613   push_nested_class (type);
7614
7615   /* Now members are processed in the order of declaration.  */
7616   for (member = CLASSTYPE_DECL_LIST (pattern);
7617        member; member = TREE_CHAIN (member))
7618     {
7619       tree t = TREE_VALUE (member);
7620
7621       if (TREE_PURPOSE (member))
7622         {
7623           if (TYPE_P (t))
7624             {
7625               /* Build new CLASSTYPE_NESTED_UTDS.  */
7626
7627               tree newtag;
7628               bool class_template_p;
7629
7630               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7631                                   && TYPE_LANG_SPECIFIC (t)
7632                                   && CLASSTYPE_IS_TEMPLATE (t));
7633               /* If the member is a class template, then -- even after
7634                  substitution -- there may be dependent types in the
7635                  template argument list for the class.  We increment
7636                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7637                  that function will assume that no types are dependent
7638                  when outside of a template.  */
7639               if (class_template_p)
7640                 ++processing_template_decl;
7641               newtag = tsubst (t, args, tf_error, NULL_TREE);
7642               if (class_template_p)
7643                 --processing_template_decl;
7644               if (newtag == error_mark_node)
7645                 continue;
7646
7647               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7648                 {
7649                   tree name = TYPE_IDENTIFIER (t);
7650
7651                   if (class_template_p)
7652                     /* Unfortunately, lookup_template_class sets
7653                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7654                        instantiation (i.e., for the type of a member
7655                        template class nested within a template class.)
7656                        This behavior is required for
7657                        maybe_process_partial_specialization to work
7658                        correctly, but is not accurate in this case;
7659                        the TAG is not an instantiation of anything.
7660                        (The corresponding TEMPLATE_DECL is an
7661                        instantiation, but the TYPE is not.) */
7662                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7663
7664                   /* Now, we call pushtag to put this NEWTAG into the scope of
7665                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7666                      pushtag calling push_template_decl.  We don't have to do
7667                      this for enums because it will already have been done in
7668                      tsubst_enum.  */
7669                   if (name)
7670                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7671                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7672                 }
7673             }
7674           else if (TREE_CODE (t) == FUNCTION_DECL
7675                    || DECL_FUNCTION_TEMPLATE_P (t))
7676             {
7677               /* Build new TYPE_METHODS.  */
7678               tree r;
7679
7680               if (TREE_CODE (t) == TEMPLATE_DECL)
7681                 ++processing_template_decl;
7682               r = tsubst (t, args, tf_error, NULL_TREE);
7683               if (TREE_CODE (t) == TEMPLATE_DECL)
7684                 --processing_template_decl;
7685               set_current_access_from_decl (r);
7686               finish_member_declaration (r);
7687             }
7688           else
7689             {
7690               /* Build new TYPE_FIELDS.  */
7691               if (TREE_CODE (t) == STATIC_ASSERT)
7692                 {
7693                   tree condition = 
7694                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7695                                  tf_warning_or_error, NULL_TREE,
7696                                  /*integral_constant_expression_p=*/true);
7697                   finish_static_assert (condition,
7698                                         STATIC_ASSERT_MESSAGE (t), 
7699                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7700                                         /*member_p=*/true);
7701                 }
7702               else if (TREE_CODE (t) != CONST_DECL)
7703                 {
7704                   tree r;
7705
7706                   /* The file and line for this declaration, to
7707                      assist in error message reporting.  Since we
7708                      called push_tinst_level above, we don't need to
7709                      restore these.  */
7710                   input_location = DECL_SOURCE_LOCATION (t);
7711
7712                   if (TREE_CODE (t) == TEMPLATE_DECL)
7713                     ++processing_template_decl;
7714                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7715                   if (TREE_CODE (t) == TEMPLATE_DECL)
7716                     --processing_template_decl;
7717                   if (TREE_CODE (r) == VAR_DECL)
7718                     {
7719                       /* In [temp.inst]:
7720
7721                            [t]he initialization (and any associated
7722                            side-effects) of a static data member does
7723                            not occur unless the static data member is
7724                            itself used in a way that requires the
7725                            definition of the static data member to
7726                            exist.
7727
7728                          Therefore, we do not substitute into the
7729                          initialized for the static data member here.  */
7730                       finish_static_data_member_decl
7731                         (r,
7732                          /*init=*/NULL_TREE,
7733                          /*init_const_expr_p=*/false,
7734                          /*asmspec_tree=*/NULL_TREE,
7735                          /*flags=*/0);
7736                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7737                         check_static_variable_definition (r, TREE_TYPE (r));
7738                     }
7739                   else if (TREE_CODE (r) == FIELD_DECL)
7740                     {
7741                       /* Determine whether R has a valid type and can be
7742                          completed later.  If R is invalid, then it is
7743                          replaced by error_mark_node so that it will not be
7744                          added to TYPE_FIELDS.  */
7745                       tree rtype = TREE_TYPE (r);
7746                       if (can_complete_type_without_circularity (rtype))
7747                         complete_type (rtype);
7748
7749                       if (!COMPLETE_TYPE_P (rtype))
7750                         {
7751                           cxx_incomplete_type_error (r, rtype);
7752                           r = error_mark_node;
7753                         }
7754                     }
7755
7756                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7757                      such a thing will already have been added to the field
7758                      list by tsubst_enum in finish_member_declaration in the
7759                      CLASSTYPE_NESTED_UTDS case above.  */
7760                   if (!(TREE_CODE (r) == TYPE_DECL
7761                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7762                         && DECL_ARTIFICIAL (r)))
7763                     {
7764                       set_current_access_from_decl (r);
7765                       finish_member_declaration (r);
7766                     }
7767                 }
7768             }
7769         }
7770       else
7771         {
7772           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7773             {
7774               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7775
7776               tree friend_type = t;
7777               bool adjust_processing_template_decl = false;
7778
7779               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7780                 {
7781                   /* template <class T> friend class C;  */
7782                   friend_type = tsubst_friend_class (friend_type, args);
7783                   adjust_processing_template_decl = true;
7784                 }
7785               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7786                 {
7787                   /* template <class T> friend class C::D;  */
7788                   friend_type = tsubst (friend_type, args,
7789                                         tf_warning_or_error, NULL_TREE);
7790                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7791                     friend_type = TREE_TYPE (friend_type);
7792                   adjust_processing_template_decl = true;
7793                 }
7794               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7795                 {
7796                   /* This could be either
7797
7798                        friend class T::C;
7799
7800                      when dependent_type_p is false or
7801
7802                        template <class U> friend class T::C;
7803
7804                      otherwise.  */
7805                   friend_type = tsubst (friend_type, args,
7806                                         tf_warning_or_error, NULL_TREE);
7807                   /* Bump processing_template_decl for correct
7808                      dependent_type_p calculation.  */
7809                   ++processing_template_decl;
7810                   if (dependent_type_p (friend_type))
7811                     adjust_processing_template_decl = true;
7812                   --processing_template_decl;
7813                 }
7814               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7815                        && hidden_name_p (TYPE_NAME (friend_type)))
7816                 {
7817                   /* friend class C;
7818
7819                      where C hasn't been declared yet.  Let's lookup name
7820                      from namespace scope directly, bypassing any name that
7821                      come from dependent base class.  */
7822                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7823
7824                   /* The call to xref_tag_from_type does injection for friend
7825                      classes.  */
7826                   push_nested_namespace (ns);
7827                   friend_type =
7828                     xref_tag_from_type (friend_type, NULL_TREE,
7829                                         /*tag_scope=*/ts_current);
7830                   pop_nested_namespace (ns);
7831                 }
7832               else if (uses_template_parms (friend_type))
7833                 /* friend class C<T>;  */
7834                 friend_type = tsubst (friend_type, args,
7835                                       tf_warning_or_error, NULL_TREE);
7836               /* Otherwise it's
7837
7838                    friend class C;
7839
7840                  where C is already declared or
7841
7842                    friend class C<int>;
7843
7844                  We don't have to do anything in these cases.  */
7845
7846               if (adjust_processing_template_decl)
7847                 /* Trick make_friend_class into realizing that the friend
7848                    we're adding is a template, not an ordinary class.  It's
7849                    important that we use make_friend_class since it will
7850                    perform some error-checking and output cross-reference
7851                    information.  */
7852                 ++processing_template_decl;
7853
7854               if (friend_type != error_mark_node)
7855                 make_friend_class (type, friend_type, /*complain=*/false);
7856
7857               if (adjust_processing_template_decl)
7858                 --processing_template_decl;
7859             }
7860           else
7861             {
7862               /* Build new DECL_FRIENDLIST.  */
7863               tree r;
7864
7865               /* The file and line for this declaration, to
7866                  assist in error message reporting.  Since we
7867                  called push_tinst_level above, we don't need to
7868                  restore these.  */
7869               input_location = DECL_SOURCE_LOCATION (t);
7870
7871               if (TREE_CODE (t) == TEMPLATE_DECL)
7872                 {
7873                   ++processing_template_decl;
7874                   push_deferring_access_checks (dk_no_check);
7875                 }
7876
7877               r = tsubst_friend_function (t, args);
7878               add_friend (type, r, /*complain=*/false);
7879               if (TREE_CODE (t) == TEMPLATE_DECL)
7880                 {
7881                   pop_deferring_access_checks ();
7882                   --processing_template_decl;
7883                 }
7884             }
7885         }
7886     }
7887
7888   /* Set the file and line number information to whatever is given for
7889      the class itself.  This puts error messages involving generated
7890      implicit functions at a predictable point, and the same point
7891      that would be used for non-template classes.  */
7892   input_location = DECL_SOURCE_LOCATION (typedecl);
7893
7894   unreverse_member_declarations (type);
7895   finish_struct_1 (type);
7896   TYPE_BEING_DEFINED (type) = 0;
7897
7898   /* Now that the class is complete, instantiate default arguments for
7899      any member functions.  We don't do this earlier because the
7900      default arguments may reference members of the class.  */
7901   if (!PRIMARY_TEMPLATE_P (templ))
7902     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7903       if (TREE_CODE (t) == FUNCTION_DECL
7904           /* Implicitly generated member functions will not have template
7905              information; they are not instantiations, but instead are
7906              created "fresh" for each instantiation.  */
7907           && DECL_TEMPLATE_INFO (t))
7908         tsubst_default_arguments (t);
7909
7910   /* Some typedefs referenced from within the template code need to be access
7911      checked at template instantiation time, i.e now. These types were
7912      added to the template at parsing time. Let's get those and perform
7913      the access checks then.  */
7914   perform_typedefs_access_check (pattern, args);
7915   perform_deferred_access_checks ();
7916   pop_nested_class ();
7917   maximum_field_alignment = saved_maximum_field_alignment;
7918   pop_from_top_level ();
7919   pop_deferring_access_checks ();
7920   pop_tinst_level ();
7921
7922   /* The vtable for a template class can be emitted in any translation
7923      unit in which the class is instantiated.  When there is no key
7924      method, however, finish_struct_1 will already have added TYPE to
7925      the keyed_classes list.  */
7926   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7927     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7928
7929   return type;
7930 }
7931
7932 static tree
7933 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7934 {
7935   tree r;
7936
7937   if (!t)
7938     r = t;
7939   else if (TYPE_P (t))
7940     r = tsubst (t, args, complain, in_decl);
7941   else
7942     {
7943       r = tsubst_expr (t, args, complain, in_decl,
7944                        /*integral_constant_expression_p=*/true);
7945       r = fold_non_dependent_expr (r);
7946     }
7947   return r;
7948 }
7949
7950 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7951    NONTYPE_ARGUMENT_PACK.  */
7952
7953 static tree
7954 make_fnparm_pack (tree spec_parm)
7955 {
7956   /* Collect all of the extra "packed" parameters into an
7957      argument pack.  */
7958   tree parmvec;
7959   tree parmtypevec;
7960   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7961   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7962   int i, len = list_length (spec_parm);
7963
7964   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7965   parmvec = make_tree_vec (len);
7966   parmtypevec = make_tree_vec (len);
7967   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7968     {
7969       TREE_VEC_ELT (parmvec, i) = spec_parm;
7970       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7971     }
7972
7973   /* Build the argument packs.  */
7974   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7975   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7976   TREE_TYPE (argpack) = argtypepack;
7977
7978   return argpack;
7979 }        
7980
7981 /* Substitute ARGS into T, which is an pack expansion
7982    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7983    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7984    (if only a partial substitution could be performed) or
7985    ERROR_MARK_NODE if there was an error.  */
7986 tree
7987 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7988                        tree in_decl)
7989 {
7990   tree pattern;
7991   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7992   tree first_arg_pack; int i, len = -1;
7993   tree result;
7994   int incomplete = 0;
7995   bool very_local_specializations = false;
7996
7997   gcc_assert (PACK_EXPANSION_P (t));
7998   pattern = PACK_EXPANSION_PATTERN (t);
7999
8000   /* Determine the argument packs that will instantiate the parameter
8001      packs used in the expansion expression. While we're at it,
8002      compute the number of arguments to be expanded and make sure it
8003      is consistent.  */
8004   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8005        pack = TREE_CHAIN (pack))
8006     {
8007       tree parm_pack = TREE_VALUE (pack);
8008       tree arg_pack = NULL_TREE;
8009       tree orig_arg = NULL_TREE;
8010
8011       if (TREE_CODE (parm_pack) == PARM_DECL)
8012         {
8013           arg_pack = retrieve_local_specialization (parm_pack);
8014           if (arg_pack == NULL_TREE)
8015             {
8016               /* This can happen for a parameter name used later in a function
8017                  declaration (such as in a late-specified return type).  Just
8018                  make a dummy decl, since it's only used for its type.  */
8019               gcc_assert (cp_unevaluated_operand != 0);
8020               arg_pack = tsubst_decl (parm_pack, args, complain);
8021               arg_pack = make_fnparm_pack (arg_pack);
8022             }
8023         }
8024       else
8025         {
8026           int level, idx, levels;
8027           template_parm_level_and_index (parm_pack, &level, &idx);
8028
8029           levels = TMPL_ARGS_DEPTH (args);
8030           if (level <= levels)
8031             arg_pack = TMPL_ARG (args, level, idx);
8032         }
8033
8034       orig_arg = arg_pack;
8035       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8036         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8037       
8038       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8039         /* This can only happen if we forget to expand an argument
8040            pack somewhere else. Just return an error, silently.  */
8041         {
8042           result = make_tree_vec (1);
8043           TREE_VEC_ELT (result, 0) = error_mark_node;
8044           return result;
8045         }
8046
8047       if (arg_pack
8048           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8049           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8050         {
8051           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8052           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8053           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8054               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8055             /* The argument pack that the parameter maps to is just an
8056                expansion of the parameter itself, such as one would
8057                find in the implicit typedef of a class inside the
8058                class itself.  Consider this parameter "unsubstituted",
8059                so that we will maintain the outer pack expansion.  */
8060             arg_pack = NULL_TREE;
8061         }
8062           
8063       if (arg_pack)
8064         {
8065           int my_len = 
8066             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8067
8068           /* It's all-or-nothing with incomplete argument packs.  */
8069           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8070             return error_mark_node;
8071           
8072           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8073             incomplete = 1;
8074
8075           if (len < 0)
8076             {
8077               len = my_len;
8078               first_arg_pack = arg_pack;
8079             }
8080           else if (len != my_len)
8081             {
8082               if (incomplete)
8083                 /* We got explicit args for some packs but not others;
8084                    do nothing now and try again after deduction.  */
8085                 return t;
8086               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8087                 error ("mismatched argument pack lengths while expanding "
8088                        "%<%T%>",
8089                        pattern);
8090               else
8091                 error ("mismatched argument pack lengths while expanding "
8092                        "%<%E%>",
8093                        pattern);
8094               return error_mark_node;
8095             }
8096
8097           /* Keep track of the parameter packs and their corresponding
8098              argument packs.  */
8099           packs = tree_cons (parm_pack, arg_pack, packs);
8100           TREE_TYPE (packs) = orig_arg;
8101         }
8102       else
8103         /* We can't substitute for this parameter pack.  */
8104         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8105                                          TREE_VALUE (pack),
8106                                          unsubstituted_packs);
8107     }
8108
8109   /* We cannot expand this expansion expression, because we don't have
8110      all of the argument packs we need. Substitute into the pattern
8111      and return a PACK_EXPANSION_*. The caller will need to deal with
8112      that.  */
8113   if (unsubstituted_packs)
8114     {
8115       tree new_pat;
8116       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8117         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8118                                /*integral_constant_expression_p=*/false);
8119       else
8120         new_pat = tsubst (pattern, args, complain, in_decl);
8121       return make_pack_expansion (new_pat);
8122     }
8123
8124   /* We could not find any argument packs that work.  */
8125   if (len < 0)
8126     return error_mark_node;
8127
8128   if (!local_specializations)
8129     {
8130       /* We're in a late-specified return type, so we don't have a local
8131          specializations table.  Create one for doing this expansion.  */
8132       very_local_specializations = true;
8133       local_specializations = htab_create (37,
8134                                            hash_local_specialization,
8135                                            eq_local_specializations,
8136                                            NULL);
8137     }
8138
8139   /* For each argument in each argument pack, substitute into the
8140      pattern.  */
8141   result = make_tree_vec (len + incomplete);
8142   for (i = 0; i < len + incomplete; ++i)
8143     {
8144       /* For parameter pack, change the substitution of the parameter
8145          pack to the ith argument in its argument pack, then expand
8146          the pattern.  */
8147       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8148         {
8149           tree parm = TREE_PURPOSE (pack);
8150
8151           if (TREE_CODE (parm) == PARM_DECL)
8152             {
8153               /* Select the Ith argument from the pack.  */
8154               tree arg = make_node (ARGUMENT_PACK_SELECT);
8155               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8156               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8157               mark_used (parm);
8158               register_local_specialization (arg, parm);
8159             }
8160           else
8161             {
8162               tree value = parm;
8163               int idx, level;
8164               template_parm_level_and_index (parm, &level, &idx);
8165               
8166               if (i < len) 
8167                 {
8168                   /* Select the Ith argument from the pack. */
8169                   value = make_node (ARGUMENT_PACK_SELECT);
8170                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8171                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8172                 }
8173
8174               /* Update the corresponding argument.  */
8175               TMPL_ARG (args, level, idx) = value;
8176             }
8177         }
8178
8179       /* Substitute into the PATTERN with the altered arguments.  */
8180       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8181         TREE_VEC_ELT (result, i) = 
8182           tsubst_expr (pattern, args, complain, in_decl,
8183                        /*integral_constant_expression_p=*/false);
8184       else
8185         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8186
8187       if (i == len)
8188         /* When we have incomplete argument packs, the last "expanded"
8189            result is itself a pack expansion, which allows us
8190            to deduce more arguments.  */
8191         TREE_VEC_ELT (result, i) = 
8192           make_pack_expansion (TREE_VEC_ELT (result, i));
8193
8194       if (TREE_VEC_ELT (result, i) == error_mark_node)
8195         {
8196           result = error_mark_node;
8197           break;
8198         }
8199     }
8200
8201   /* Update ARGS to restore the substitution from parameter packs to
8202      their argument packs.  */
8203   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8204     {
8205       tree parm = TREE_PURPOSE (pack);
8206
8207       if (TREE_CODE (parm) == PARM_DECL)
8208         register_local_specialization (TREE_TYPE (pack), parm);
8209       else
8210         {
8211           int idx, level;
8212           template_parm_level_and_index (parm, &level, &idx);
8213           
8214           /* Update the corresponding argument.  */
8215           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8216             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8217               TREE_TYPE (pack);
8218           else
8219             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8220         }
8221     }
8222
8223   if (very_local_specializations)
8224     {
8225       htab_delete (local_specializations);
8226       local_specializations = NULL;
8227     }
8228   
8229   return result;
8230 }
8231
8232 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8233    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8234    parameter packs; all parms generated from a function parameter pack will
8235    have the same DECL_PARM_INDEX.  */
8236
8237 tree
8238 get_pattern_parm (tree parm, tree tmpl)
8239 {
8240   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8241   tree patparm;
8242
8243   if (DECL_ARTIFICIAL (parm))
8244     {
8245       for (patparm = DECL_ARGUMENTS (pattern);
8246            patparm; patparm = TREE_CHAIN (patparm))
8247         if (DECL_ARTIFICIAL (patparm)
8248             && DECL_NAME (parm) == DECL_NAME (patparm))
8249           break;
8250     }
8251   else
8252     {
8253       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8254       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8255       gcc_assert (DECL_PARM_INDEX (patparm)
8256                   == DECL_PARM_INDEX (parm));
8257     }
8258
8259   return patparm;
8260 }
8261
8262 /* Substitute ARGS into the vector or list of template arguments T.  */
8263
8264 static tree
8265 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8266 {
8267   tree orig_t = t;
8268   int len = TREE_VEC_LENGTH (t);
8269   int need_new = 0, i, expanded_len_adjust = 0, out;
8270   tree *elts = (tree *) alloca (len * sizeof (tree));
8271
8272   for (i = 0; i < len; i++)
8273     {
8274       tree orig_arg = TREE_VEC_ELT (t, i);
8275       tree new_arg;
8276
8277       if (TREE_CODE (orig_arg) == TREE_VEC)
8278         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8279       else if (PACK_EXPANSION_P (orig_arg))
8280         {
8281           /* Substitute into an expansion expression.  */
8282           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8283
8284           if (TREE_CODE (new_arg) == TREE_VEC)
8285             /* Add to the expanded length adjustment the number of
8286                expanded arguments. We subtract one from this
8287                measurement, because the argument pack expression
8288                itself is already counted as 1 in
8289                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8290                the argument pack is empty.  */
8291             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8292         }
8293       else if (ARGUMENT_PACK_P (orig_arg))
8294         {
8295           /* Substitute into each of the arguments.  */
8296           new_arg = TYPE_P (orig_arg)
8297             ? cxx_make_type (TREE_CODE (orig_arg))
8298             : make_node (TREE_CODE (orig_arg));
8299           
8300           SET_ARGUMENT_PACK_ARGS (
8301             new_arg,
8302             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8303                                   args, complain, in_decl));
8304
8305           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8306             new_arg = error_mark_node;
8307
8308           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8309             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8310                                           complain, in_decl);
8311             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8312
8313             if (TREE_TYPE (new_arg) == error_mark_node)
8314               new_arg = error_mark_node;
8315           }
8316         }
8317       else
8318         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8319
8320       if (new_arg == error_mark_node)
8321         return error_mark_node;
8322
8323       elts[i] = new_arg;
8324       if (new_arg != orig_arg)
8325         need_new = 1;
8326     }
8327
8328   if (!need_new)
8329     return t;
8330
8331   /* Make space for the expanded arguments coming from template
8332      argument packs.  */
8333   t = make_tree_vec (len + expanded_len_adjust);
8334   for (i = 0, out = 0; i < len; i++)
8335     {
8336       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8337            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8338           && TREE_CODE (elts[i]) == TREE_VEC)
8339         {
8340           int idx;
8341
8342           /* Now expand the template argument pack "in place".  */
8343           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8344             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8345         }
8346       else
8347         {
8348           TREE_VEC_ELT (t, out) = elts[i];
8349           out++;
8350         }
8351     }
8352
8353   return t;
8354 }
8355
8356 /* Return the result of substituting ARGS into the template parameters
8357    given by PARMS.  If there are m levels of ARGS and m + n levels of
8358    PARMS, then the result will contain n levels of PARMS.  For
8359    example, if PARMS is `template <class T> template <class U>
8360    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8361    result will be `template <int*, double, class V>'.  */
8362
8363 static tree
8364 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8365 {
8366   tree r = NULL_TREE;
8367   tree* new_parms;
8368
8369   /* When substituting into a template, we must set
8370      PROCESSING_TEMPLATE_DECL as the template parameters may be
8371      dependent if they are based on one-another, and the dependency
8372      predicates are short-circuit outside of templates.  */
8373   ++processing_template_decl;
8374
8375   for (new_parms = &r;
8376        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8377        new_parms = &(TREE_CHAIN (*new_parms)),
8378          parms = TREE_CHAIN (parms))
8379     {
8380       tree new_vec =
8381         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8382       int i;
8383
8384       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8385         {
8386           tree tuple;
8387           tree default_value;
8388           tree parm_decl;
8389
8390           if (parms == error_mark_node)
8391             continue;
8392
8393           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8394
8395           if (tuple == error_mark_node)
8396             continue;
8397
8398           default_value = TREE_PURPOSE (tuple);
8399           parm_decl = TREE_VALUE (tuple);
8400
8401           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8402           if (TREE_CODE (parm_decl) == PARM_DECL
8403               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8404             parm_decl = error_mark_node;
8405           default_value = tsubst_template_arg (default_value, args,
8406                                                complain, NULL_TREE);
8407
8408           tuple = build_tree_list (default_value, parm_decl);
8409           TREE_VEC_ELT (new_vec, i) = tuple;
8410         }
8411
8412       *new_parms =
8413         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8414                              - TMPL_ARGS_DEPTH (args)),
8415                    new_vec, NULL_TREE);
8416     }
8417
8418   --processing_template_decl;
8419
8420   return r;
8421 }
8422
8423 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8424    type T.  If T is not an aggregate or enumeration type, it is
8425    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8426    ENTERING_SCOPE is nonzero, T is the context for a template which
8427    we are presently tsubst'ing.  Return the substituted value.  */
8428
8429 static tree
8430 tsubst_aggr_type (tree t,
8431                   tree args,
8432                   tsubst_flags_t complain,
8433                   tree in_decl,
8434                   int entering_scope)
8435 {
8436   if (t == NULL_TREE)
8437     return NULL_TREE;
8438
8439   switch (TREE_CODE (t))
8440     {
8441     case RECORD_TYPE:
8442       if (TYPE_PTRMEMFUNC_P (t))
8443         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8444
8445       /* Else fall through.  */
8446     case ENUMERAL_TYPE:
8447     case UNION_TYPE:
8448       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8449         {
8450           tree argvec;
8451           tree context;
8452           tree r;
8453           int saved_unevaluated_operand;
8454           int saved_inhibit_evaluation_warnings;
8455
8456           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8457           saved_unevaluated_operand = cp_unevaluated_operand;
8458           cp_unevaluated_operand = 0;
8459           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8460           c_inhibit_evaluation_warnings = 0;
8461
8462           /* First, determine the context for the type we are looking
8463              up.  */
8464           context = TYPE_CONTEXT (t);
8465           if (context)
8466             {
8467               context = tsubst_aggr_type (context, args, complain,
8468                                           in_decl, /*entering_scope=*/1);
8469               /* If context is a nested class inside a class template,
8470                  it may still need to be instantiated (c++/33959).  */
8471               if (TYPE_P (context))
8472                 context = complete_type (context);
8473             }
8474
8475           /* Then, figure out what arguments are appropriate for the
8476              type we are trying to find.  For example, given:
8477
8478                template <class T> struct S;
8479                template <class T, class U> void f(T, U) { S<U> su; }
8480
8481              and supposing that we are instantiating f<int, double>,
8482              then our ARGS will be {int, double}, but, when looking up
8483              S we only want {double}.  */
8484           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8485                                          complain, in_decl);
8486           if (argvec == error_mark_node)
8487             r = error_mark_node;
8488           else
8489             {
8490               r = lookup_template_class (t, argvec, in_decl, context,
8491                                          entering_scope, complain);
8492               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8493             }
8494
8495           cp_unevaluated_operand = saved_unevaluated_operand;
8496           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8497
8498           return r;
8499         }
8500       else
8501         /* This is not a template type, so there's nothing to do.  */
8502         return t;
8503
8504     default:
8505       return tsubst (t, args, complain, in_decl);
8506     }
8507 }
8508
8509 /* Substitute into the default argument ARG (a default argument for
8510    FN), which has the indicated TYPE.  */
8511
8512 tree
8513 tsubst_default_argument (tree fn, tree type, tree arg)
8514 {
8515   tree saved_class_ptr = NULL_TREE;
8516   tree saved_class_ref = NULL_TREE;
8517
8518   /* This default argument came from a template.  Instantiate the
8519      default argument here, not in tsubst.  In the case of
8520      something like:
8521
8522        template <class T>
8523        struct S {
8524          static T t();
8525          void f(T = t());
8526        };
8527
8528      we must be careful to do name lookup in the scope of S<T>,
8529      rather than in the current class.  */
8530   push_access_scope (fn);
8531   /* The "this" pointer is not valid in a default argument.  */
8532   if (cfun)
8533     {
8534       saved_class_ptr = current_class_ptr;
8535       cp_function_chain->x_current_class_ptr = NULL_TREE;
8536       saved_class_ref = current_class_ref;
8537       cp_function_chain->x_current_class_ref = NULL_TREE;
8538     }
8539
8540   push_deferring_access_checks(dk_no_deferred);
8541   /* The default argument expression may cause implicitly defined
8542      member functions to be synthesized, which will result in garbage
8543      collection.  We must treat this situation as if we were within
8544      the body of function so as to avoid collecting live data on the
8545      stack.  */
8546   ++function_depth;
8547   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8548                      tf_warning_or_error, NULL_TREE,
8549                      /*integral_constant_expression_p=*/false);
8550   --function_depth;
8551   pop_deferring_access_checks();
8552
8553   /* Restore the "this" pointer.  */
8554   if (cfun)
8555     {
8556       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8557       cp_function_chain->x_current_class_ref = saved_class_ref;
8558     }
8559
8560   /* Make sure the default argument is reasonable.  */
8561   arg = check_default_argument (type, arg);
8562
8563   pop_access_scope (fn);
8564
8565   return arg;
8566 }
8567
8568 /* Substitute into all the default arguments for FN.  */
8569
8570 static void
8571 tsubst_default_arguments (tree fn)
8572 {
8573   tree arg;
8574   tree tmpl_args;
8575
8576   tmpl_args = DECL_TI_ARGS (fn);
8577
8578   /* If this function is not yet instantiated, we certainly don't need
8579      its default arguments.  */
8580   if (uses_template_parms (tmpl_args))
8581     return;
8582
8583   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8584        arg;
8585        arg = TREE_CHAIN (arg))
8586     if (TREE_PURPOSE (arg))
8587       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8588                                                     TREE_VALUE (arg),
8589                                                     TREE_PURPOSE (arg));
8590 }
8591
8592 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8593    result of the substitution.  Issue error and warning messages under
8594    control of COMPLAIN.  */
8595
8596 static tree
8597 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8598 {
8599 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8600   location_t saved_loc;
8601   tree r = NULL_TREE;
8602   tree in_decl = t;
8603   hashval_t hash = 0;
8604
8605   /* Set the filename and linenumber to improve error-reporting.  */
8606   saved_loc = input_location;
8607   input_location = DECL_SOURCE_LOCATION (t);
8608
8609   switch (TREE_CODE (t))
8610     {
8611     case TEMPLATE_DECL:
8612       {
8613         /* We can get here when processing a member function template,
8614            member class template, or template template parameter.  */
8615         tree decl = DECL_TEMPLATE_RESULT (t);
8616         tree spec;
8617         tree tmpl_args;
8618         tree full_args;
8619
8620         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8621           {
8622             /* Template template parameter is treated here.  */
8623             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8624             if (new_type == error_mark_node)
8625               RETURN (error_mark_node);
8626
8627             r = copy_decl (t);
8628             TREE_CHAIN (r) = NULL_TREE;
8629             TREE_TYPE (r) = new_type;
8630             DECL_TEMPLATE_RESULT (r)
8631               = build_decl (DECL_SOURCE_LOCATION (decl),
8632                             TYPE_DECL, DECL_NAME (decl), new_type);
8633             DECL_TEMPLATE_PARMS (r)
8634               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8635                                        complain);
8636             TYPE_NAME (new_type) = r;
8637             break;
8638           }
8639
8640         /* We might already have an instance of this template.
8641            The ARGS are for the surrounding class type, so the
8642            full args contain the tsubst'd args for the context,
8643            plus the innermost args from the template decl.  */
8644         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8645           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8646           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8647         /* Because this is a template, the arguments will still be
8648            dependent, even after substitution.  If
8649            PROCESSING_TEMPLATE_DECL is not set, the dependency
8650            predicates will short-circuit.  */
8651         ++processing_template_decl;
8652         full_args = tsubst_template_args (tmpl_args, args,
8653                                           complain, in_decl);
8654         --processing_template_decl;
8655         if (full_args == error_mark_node)
8656           RETURN (error_mark_node);
8657
8658         /* If this is a default template template argument,
8659            tsubst might not have changed anything.  */
8660         if (full_args == tmpl_args)
8661           RETURN (t);
8662
8663         hash = hash_tmpl_and_args (t, full_args);
8664         spec = retrieve_specialization (t, full_args, hash);
8665         if (spec != NULL_TREE)
8666           {
8667             r = spec;
8668             break;
8669           }
8670
8671         /* Make a new template decl.  It will be similar to the
8672            original, but will record the current template arguments.
8673            We also create a new function declaration, which is just
8674            like the old one, but points to this new template, rather
8675            than the old one.  */
8676         r = copy_decl (t);
8677         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8678         TREE_CHAIN (r) = NULL_TREE;
8679
8680         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8681
8682         if (TREE_CODE (decl) == TYPE_DECL)
8683           {
8684             tree new_type;
8685             ++processing_template_decl;
8686             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8687             --processing_template_decl;
8688             if (new_type == error_mark_node)
8689               RETURN (error_mark_node);
8690
8691             TREE_TYPE (r) = new_type;
8692             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8693             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8694             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8695             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8696           }
8697         else
8698           {
8699             tree new_decl;
8700             ++processing_template_decl;
8701             new_decl = tsubst (decl, args, complain, in_decl);
8702             --processing_template_decl;
8703             if (new_decl == error_mark_node)
8704               RETURN (error_mark_node);
8705
8706             DECL_TEMPLATE_RESULT (r) = new_decl;
8707             DECL_TI_TEMPLATE (new_decl) = r;
8708             TREE_TYPE (r) = TREE_TYPE (new_decl);
8709             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8710             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8711           }
8712
8713         SET_DECL_IMPLICIT_INSTANTIATION (r);
8714         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8715         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8716
8717         /* The template parameters for this new template are all the
8718            template parameters for the old template, except the
8719            outermost level of parameters.  */
8720         DECL_TEMPLATE_PARMS (r)
8721           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8722                                    complain);
8723
8724         if (PRIMARY_TEMPLATE_P (t))
8725           DECL_PRIMARY_TEMPLATE (r) = r;
8726
8727         if (TREE_CODE (decl) != TYPE_DECL)
8728           /* Record this non-type partial instantiation.  */
8729           register_specialization (r, t,
8730                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8731                                    false, hash);
8732       }
8733       break;
8734
8735     case FUNCTION_DECL:
8736       {
8737         tree ctx;
8738         tree argvec = NULL_TREE;
8739         tree *friends;
8740         tree gen_tmpl;
8741         tree type;
8742         int member;
8743         int args_depth;
8744         int parms_depth;
8745
8746         /* Nobody should be tsubst'ing into non-template functions.  */
8747         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8748
8749         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8750           {
8751             tree spec;
8752             bool dependent_p;
8753
8754             /* If T is not dependent, just return it.  We have to
8755                increment PROCESSING_TEMPLATE_DECL because
8756                value_dependent_expression_p assumes that nothing is
8757                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8758             ++processing_template_decl;
8759             dependent_p = value_dependent_expression_p (t);
8760             --processing_template_decl;
8761             if (!dependent_p)
8762               RETURN (t);
8763
8764             /* Calculate the most general template of which R is a
8765                specialization, and the complete set of arguments used to
8766                specialize R.  */
8767             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8768             argvec = tsubst_template_args (DECL_TI_ARGS
8769                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8770                                            args, complain, in_decl);
8771
8772             /* Check to see if we already have this specialization.  */
8773             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8774             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8775
8776             if (spec)
8777               {
8778                 r = spec;
8779                 break;
8780               }
8781
8782             /* We can see more levels of arguments than parameters if
8783                there was a specialization of a member template, like
8784                this:
8785
8786                  template <class T> struct S { template <class U> void f(); }
8787                  template <> template <class U> void S<int>::f(U);
8788
8789                Here, we'll be substituting into the specialization,
8790                because that's where we can find the code we actually
8791                want to generate, but we'll have enough arguments for
8792                the most general template.
8793
8794                We also deal with the peculiar case:
8795
8796                  template <class T> struct S {
8797                    template <class U> friend void f();
8798                  };
8799                  template <class U> void f() {}
8800                  template S<int>;
8801                  template void f<double>();
8802
8803                Here, the ARGS for the instantiation of will be {int,
8804                double}.  But, we only need as many ARGS as there are
8805                levels of template parameters in CODE_PATTERN.  We are
8806                careful not to get fooled into reducing the ARGS in
8807                situations like:
8808
8809                  template <class T> struct S { template <class U> void f(U); }
8810                  template <class T> template <> void S<T>::f(int) {}
8811
8812                which we can spot because the pattern will be a
8813                specialization in this case.  */
8814             args_depth = TMPL_ARGS_DEPTH (args);
8815             parms_depth =
8816               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8817             if (args_depth > parms_depth
8818                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8819               args = get_innermost_template_args (args, parms_depth);
8820           }
8821         else
8822           {
8823             /* This special case arises when we have something like this:
8824
8825                  template <class T> struct S {
8826                    friend void f<int>(int, double);
8827                  };
8828
8829                Here, the DECL_TI_TEMPLATE for the friend declaration
8830                will be an IDENTIFIER_NODE.  We are being called from
8831                tsubst_friend_function, and we want only to create a
8832                new decl (R) with appropriate types so that we can call
8833                determine_specialization.  */
8834             gen_tmpl = NULL_TREE;
8835           }
8836
8837         if (DECL_CLASS_SCOPE_P (t))
8838           {
8839             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8840               member = 2;
8841             else
8842               member = 1;
8843             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8844                                     complain, t, /*entering_scope=*/1);
8845           }
8846         else
8847           {
8848             member = 0;
8849             ctx = DECL_CONTEXT (t);
8850           }
8851         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8852         if (type == error_mark_node)
8853           RETURN (error_mark_node);
8854
8855         /* We do NOT check for matching decls pushed separately at this
8856            point, as they may not represent instantiations of this
8857            template, and in any case are considered separate under the
8858            discrete model.  */
8859         r = copy_decl (t);
8860         DECL_USE_TEMPLATE (r) = 0;
8861         TREE_TYPE (r) = type;
8862         /* Clear out the mangled name and RTL for the instantiation.  */
8863         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8864         SET_DECL_RTL (r, NULL_RTX);
8865         /* Leave DECL_INITIAL set on deleted instantiations.  */
8866         if (!DECL_DELETED_FN (r))
8867           DECL_INITIAL (r) = NULL_TREE;
8868         DECL_CONTEXT (r) = ctx;
8869
8870         if (member && DECL_CONV_FN_P (r))
8871           /* Type-conversion operator.  Reconstruct the name, in
8872              case it's the name of one of the template's parameters.  */
8873           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8874
8875         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8876                                      complain, t);
8877         DECL_RESULT (r) = NULL_TREE;
8878
8879         TREE_STATIC (r) = 0;
8880         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8881         DECL_EXTERNAL (r) = 1;
8882         /* If this is an instantiation of a function with internal
8883            linkage, we already know what object file linkage will be
8884            assigned to the instantiation.  */
8885         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8886         DECL_DEFER_OUTPUT (r) = 0;
8887         TREE_CHAIN (r) = NULL_TREE;
8888         DECL_PENDING_INLINE_INFO (r) = 0;
8889         DECL_PENDING_INLINE_P (r) = 0;
8890         DECL_SAVED_TREE (r) = NULL_TREE;
8891         DECL_STRUCT_FUNCTION (r) = NULL;
8892         TREE_USED (r) = 0;
8893         /* We'll re-clone as appropriate in instantiate_template.  */
8894         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8895
8896         /* If we aren't complaining now, return on error before we register
8897            the specialization so that we'll complain eventually.  */
8898         if ((complain & tf_error) == 0
8899             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8900             && !grok_op_properties (r, /*complain=*/false))
8901           RETURN (error_mark_node);
8902
8903         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8904            this in the special friend case mentioned above where
8905            GEN_TMPL is NULL.  */
8906         if (gen_tmpl)
8907           {
8908             DECL_TEMPLATE_INFO (r)
8909               = build_template_info (gen_tmpl, argvec);
8910             SET_DECL_IMPLICIT_INSTANTIATION (r);
8911             register_specialization (r, gen_tmpl, argvec, false, hash);
8912
8913             /* We're not supposed to instantiate default arguments
8914                until they are called, for a template.  But, for a
8915                declaration like:
8916
8917                  template <class T> void f ()
8918                  { extern void g(int i = T()); }
8919
8920                we should do the substitution when the template is
8921                instantiated.  We handle the member function case in
8922                instantiate_class_template since the default arguments
8923                might refer to other members of the class.  */
8924             if (!member
8925                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8926                 && !uses_template_parms (argvec))
8927               tsubst_default_arguments (r);
8928           }
8929         else
8930           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8931
8932         /* Copy the list of befriending classes.  */
8933         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8934              *friends;
8935              friends = &TREE_CHAIN (*friends))
8936           {
8937             *friends = copy_node (*friends);
8938             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8939                                             args, complain,
8940                                             in_decl);
8941           }
8942
8943         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8944           {
8945             maybe_retrofit_in_chrg (r);
8946             if (DECL_CONSTRUCTOR_P (r))
8947               grok_ctor_properties (ctx, r);
8948             /* If this is an instantiation of a member template, clone it.
8949                If it isn't, that'll be handled by
8950                clone_constructors_and_destructors.  */
8951             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8952               clone_function_decl (r, /*update_method_vec_p=*/0);
8953           }
8954         else if ((complain & tf_error) != 0
8955                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8956                  && !grok_op_properties (r, /*complain=*/true))
8957           RETURN (error_mark_node);
8958
8959         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8960           SET_DECL_FRIEND_CONTEXT (r,
8961                                    tsubst (DECL_FRIEND_CONTEXT (t),
8962                                             args, complain, in_decl));
8963
8964         /* Possibly limit visibility based on template args.  */
8965         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8966         if (DECL_VISIBILITY_SPECIFIED (t))
8967           {
8968             DECL_VISIBILITY_SPECIFIED (r) = 0;
8969             DECL_ATTRIBUTES (r)
8970               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8971           }
8972         determine_visibility (r);
8973         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
8974             && !processing_template_decl)
8975           defaulted_late_check (r);
8976
8977         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8978                                         args, complain, in_decl);
8979       }
8980       break;
8981
8982     case PARM_DECL:
8983       {
8984         tree type = NULL_TREE;
8985         int i, len = 1;
8986         tree expanded_types = NULL_TREE;
8987         tree prev_r = NULL_TREE;
8988         tree first_r = NULL_TREE;
8989
8990         if (FUNCTION_PARAMETER_PACK_P (t))
8991           {
8992             /* If there is a local specialization that isn't a
8993                parameter pack, it means that we're doing a "simple"
8994                substitution from inside tsubst_pack_expansion. Just
8995                return the local specialization (which will be a single
8996                parm).  */
8997             tree spec = retrieve_local_specialization (t);
8998             if (spec 
8999                 && TREE_CODE (spec) == PARM_DECL
9000                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9001               RETURN (spec);
9002
9003             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9004                the parameters in this function parameter pack.  */
9005             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9006                                                     complain, in_decl);
9007             if (TREE_CODE (expanded_types) == TREE_VEC)
9008               {
9009                 len = TREE_VEC_LENGTH (expanded_types);
9010
9011                 /* Zero-length parameter packs are boring. Just substitute
9012                    into the chain.  */
9013                 if (len == 0)
9014                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9015                                   TREE_CHAIN (t)));
9016               }
9017             else
9018               {
9019                 /* All we did was update the type. Make a note of that.  */
9020                 type = expanded_types;
9021                 expanded_types = NULL_TREE;
9022               }
9023           }
9024
9025         /* Loop through all of the parameter's we'll build. When T is
9026            a function parameter pack, LEN is the number of expanded
9027            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9028         r = NULL_TREE;
9029         for (i = 0; i < len; ++i)
9030           {
9031             prev_r = r;
9032             r = copy_node (t);
9033             if (DECL_TEMPLATE_PARM_P (t))
9034               SET_DECL_TEMPLATE_PARM_P (r);
9035
9036             /* An argument of a function parameter pack is not a parameter
9037                pack.  */
9038             FUNCTION_PARAMETER_PACK_P (r) = false;
9039
9040             if (expanded_types)
9041               /* We're on the Ith parameter of the function parameter
9042                  pack.  */
9043               {
9044                 /* Get the Ith type.  */
9045                 type = TREE_VEC_ELT (expanded_types, i);
9046
9047                 if (DECL_NAME (r))
9048                   /* Rename the parameter to include the index.  */
9049                   DECL_NAME (r) =
9050                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9051               }
9052             else if (!type)
9053               /* We're dealing with a normal parameter.  */
9054               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9055
9056             type = type_decays_to (type);
9057             TREE_TYPE (r) = type;
9058             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9059
9060             if (DECL_INITIAL (r))
9061               {
9062                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9063                   DECL_INITIAL (r) = TREE_TYPE (r);
9064                 else
9065                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9066                                              complain, in_decl);
9067               }
9068
9069             DECL_CONTEXT (r) = NULL_TREE;
9070
9071             if (!DECL_TEMPLATE_PARM_P (r))
9072               DECL_ARG_TYPE (r) = type_passed_as (type);
9073
9074             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9075                                             args, complain, in_decl);
9076
9077             /* Keep track of the first new parameter we
9078                generate. That's what will be returned to the
9079                caller.  */
9080             if (!first_r)
9081               first_r = r;
9082
9083             /* Build a proper chain of parameters when substituting
9084                into a function parameter pack.  */
9085             if (prev_r)
9086               TREE_CHAIN (prev_r) = r;
9087           }
9088
9089         if (TREE_CHAIN (t))
9090           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9091                                    complain, TREE_CHAIN (t));
9092
9093         /* FIRST_R contains the start of the chain we've built.  */
9094         r = first_r;
9095       }
9096       break;
9097
9098     case FIELD_DECL:
9099       {
9100         tree type;
9101
9102         r = copy_decl (t);
9103         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9104         if (type == error_mark_node)
9105           RETURN (error_mark_node);
9106         TREE_TYPE (r) = type;
9107         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9108
9109         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9110         DECL_INITIAL (r)
9111           = tsubst_expr (DECL_INITIAL (t), args,
9112                          complain, in_decl,
9113                          /*integral_constant_expression_p=*/true);
9114         /* We don't have to set DECL_CONTEXT here; it is set by
9115            finish_member_declaration.  */
9116         TREE_CHAIN (r) = NULL_TREE;
9117         if (VOID_TYPE_P (type))
9118           error ("instantiation of %q+D as type %qT", r, type);
9119
9120         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9121                                         args, complain, in_decl);
9122       }
9123       break;
9124
9125     case USING_DECL:
9126       /* We reach here only for member using decls.  */
9127       if (DECL_DEPENDENT_P (t))
9128         {
9129           r = do_class_using_decl
9130             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9131              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9132           if (!r)
9133             r = error_mark_node;
9134           else
9135             {
9136               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9137               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9138             }
9139         }
9140       else
9141         {
9142           r = copy_node (t);
9143           TREE_CHAIN (r) = NULL_TREE;
9144         }
9145       break;
9146
9147     case TYPE_DECL:
9148     case VAR_DECL:
9149       {
9150         tree argvec = NULL_TREE;
9151         tree gen_tmpl = NULL_TREE;
9152         tree spec;
9153         tree tmpl = NULL_TREE;
9154         tree ctx;
9155         tree type = NULL_TREE;
9156         bool local_p;
9157
9158         if (TREE_CODE (t) == TYPE_DECL
9159             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9160           {
9161             /* If this is the canonical decl, we don't have to
9162                mess with instantiations, and often we can't (for
9163                typename, template type parms and such).  Note that
9164                TYPE_NAME is not correct for the above test if
9165                we've copied the type for a typedef.  */
9166             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9167             if (type == error_mark_node)
9168               RETURN (error_mark_node);
9169             r = TYPE_NAME (type);
9170             break;
9171           }
9172
9173         /* Check to see if we already have the specialization we
9174            need.  */
9175         spec = NULL_TREE;
9176         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9177           {
9178             /* T is a static data member or namespace-scope entity.
9179                We have to substitute into namespace-scope variables
9180                (even though such entities are never templates) because
9181                of cases like:
9182                
9183                  template <class T> void f() { extern T t; }
9184
9185                where the entity referenced is not known until
9186                instantiation time.  */
9187             local_p = false;
9188             ctx = DECL_CONTEXT (t);
9189             if (DECL_CLASS_SCOPE_P (t))
9190               {
9191                 ctx = tsubst_aggr_type (ctx, args,
9192                                         complain,
9193                                         in_decl, /*entering_scope=*/1);
9194                 /* If CTX is unchanged, then T is in fact the
9195                    specialization we want.  That situation occurs when
9196                    referencing a static data member within in its own
9197                    class.  We can use pointer equality, rather than
9198                    same_type_p, because DECL_CONTEXT is always
9199                    canonical.  */
9200                 if (ctx == DECL_CONTEXT (t))
9201                   spec = t;
9202               }
9203
9204             if (!spec)
9205               {
9206                 tmpl = DECL_TI_TEMPLATE (t);
9207                 gen_tmpl = most_general_template (tmpl);
9208                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9209                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9210                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9211               }
9212           }
9213         else
9214           {
9215             /* A local variable.  */
9216             local_p = true;
9217             /* Subsequent calls to pushdecl will fill this in.  */
9218             ctx = NULL_TREE;
9219             spec = retrieve_local_specialization (t);
9220           }
9221         /* If we already have the specialization we need, there is
9222            nothing more to do.  */ 
9223         if (spec)
9224           {
9225             r = spec;
9226             break;
9227           }
9228
9229         /* Create a new node for the specialization we need.  */
9230         r = copy_decl (t);
9231         if (type == NULL_TREE)
9232           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9233         if (TREE_CODE (r) == VAR_DECL)
9234           {
9235             /* Even if the original location is out of scope, the
9236                newly substituted one is not.  */
9237             DECL_DEAD_FOR_LOCAL (r) = 0;
9238             DECL_INITIALIZED_P (r) = 0;
9239             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9240             if (type == error_mark_node)
9241               RETURN (error_mark_node);
9242             if (TREE_CODE (type) == FUNCTION_TYPE)
9243               {
9244                 /* It may seem that this case cannot occur, since:
9245
9246                      typedef void f();
9247                      void g() { f x; }
9248
9249                    declares a function, not a variable.  However:
9250       
9251                      typedef void f();
9252                      template <typename T> void g() { T t; }
9253                      template void g<f>();
9254
9255                    is an attempt to declare a variable with function
9256                    type.  */
9257                 error ("variable %qD has function type",
9258                        /* R is not yet sufficiently initialized, so we
9259                           just use its name.  */
9260                        DECL_NAME (r));
9261                 RETURN (error_mark_node);
9262               }
9263             type = complete_type (type);
9264             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9265               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9266             type = check_var_type (DECL_NAME (r), type);
9267
9268             if (DECL_HAS_VALUE_EXPR_P (t))
9269               {
9270                 tree ve = DECL_VALUE_EXPR (t);
9271                 ve = tsubst_expr (ve, args, complain, in_decl,
9272                                   /*constant_expression_p=*/false);
9273                 SET_DECL_VALUE_EXPR (r, ve);
9274               }
9275           }
9276         else if (DECL_SELF_REFERENCE_P (t))
9277           SET_DECL_SELF_REFERENCE_P (r);
9278         TREE_TYPE (r) = type;
9279         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9280         DECL_CONTEXT (r) = ctx;
9281         /* Clear out the mangled name and RTL for the instantiation.  */
9282         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9283         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9284           SET_DECL_RTL (r, NULL_RTX);
9285         /* The initializer must not be expanded until it is required;
9286            see [temp.inst].  */
9287         DECL_INITIAL (r) = NULL_TREE;
9288         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9289           SET_DECL_RTL (r, NULL_RTX);
9290         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9291         if (TREE_CODE (r) == VAR_DECL)
9292           {
9293             /* Possibly limit visibility based on template args.  */
9294             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9295             if (DECL_VISIBILITY_SPECIFIED (t))
9296               {
9297                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9298                 DECL_ATTRIBUTES (r)
9299                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9300               }
9301             determine_visibility (r);
9302           }
9303         /* Preserve a typedef that names a type.  */
9304         else if (TREE_CODE (r) == TYPE_DECL
9305                  && DECL_ORIGINAL_TYPE (t)
9306                  && type != error_mark_node)
9307           {
9308             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9309                                              args, complain, in_decl);
9310             TREE_TYPE (r) = type = build_variant_type_copy (type);
9311             TYPE_NAME (type) = r;
9312           }
9313
9314         if (!local_p)
9315           {
9316             /* A static data member declaration is always marked
9317                external when it is declared in-class, even if an
9318                initializer is present.  We mimic the non-template
9319                processing here.  */
9320             DECL_EXTERNAL (r) = 1;
9321
9322             register_specialization (r, gen_tmpl, argvec, false, hash);
9323             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9324             SET_DECL_IMPLICIT_INSTANTIATION (r);
9325           }
9326         else if (cp_unevaluated_operand)
9327           {
9328             /* We're substituting this var in a decltype outside of its
9329                scope, such as for a lambda return type.  Don't add it to
9330                local_specializations, do perform auto deduction.  */
9331             tree auto_node = type_uses_auto (type);
9332             tree init
9333               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9334                              /*constant_expression_p=*/false);
9335
9336             if (auto_node && init && describable_type (init))
9337               {
9338                 type = do_auto_deduction (type, init, auto_node);
9339                 TREE_TYPE (r) = type;
9340               }
9341           }
9342         else
9343           register_local_specialization (r, t);
9344
9345         TREE_CHAIN (r) = NULL_TREE;
9346
9347         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9348                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9349                                         args, complain, in_decl);
9350         layout_decl (r, 0);
9351       }
9352       break;
9353
9354     default:
9355       gcc_unreachable ();
9356     }
9357 #undef RETURN
9358
9359  out:
9360   /* Restore the file and line information.  */
9361   input_location = saved_loc;
9362
9363   return r;
9364 }
9365
9366 /* Substitute into the ARG_TYPES of a function type.  */
9367
9368 static tree
9369 tsubst_arg_types (tree arg_types,
9370                   tree args,
9371                   tsubst_flags_t complain,
9372                   tree in_decl)
9373 {
9374   tree remaining_arg_types;
9375   tree type = NULL_TREE;
9376   int i = 1;
9377   tree expanded_args = NULL_TREE;
9378   tree default_arg;
9379
9380   if (!arg_types || arg_types == void_list_node)
9381     return arg_types;
9382
9383   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9384                                           args, complain, in_decl);
9385   if (remaining_arg_types == error_mark_node)
9386     return error_mark_node;
9387
9388   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9389     {
9390       /* For a pack expansion, perform substitution on the
9391          entire expression. Later on, we'll handle the arguments
9392          one-by-one.  */
9393       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9394                                             args, complain, in_decl);
9395
9396       if (TREE_CODE (expanded_args) == TREE_VEC)
9397         /* So that we'll spin through the parameters, one by one.  */
9398         i = TREE_VEC_LENGTH (expanded_args);
9399       else
9400         {
9401           /* We only partially substituted into the parameter
9402              pack. Our type is TYPE_PACK_EXPANSION.  */
9403           type = expanded_args;
9404           expanded_args = NULL_TREE;
9405         }
9406     }
9407
9408   while (i > 0) {
9409     --i;
9410     
9411     if (expanded_args)
9412       type = TREE_VEC_ELT (expanded_args, i);
9413     else if (!type)
9414       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9415
9416     if (type == error_mark_node)
9417       return error_mark_node;
9418     if (VOID_TYPE_P (type))
9419       {
9420         if (complain & tf_error)
9421           {
9422             error ("invalid parameter type %qT", type);
9423             if (in_decl)
9424               error ("in declaration %q+D", in_decl);
9425           }
9426         return error_mark_node;
9427     }
9428     
9429     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9430        top-level qualifiers as required.  */
9431     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9432
9433     /* We do not substitute into default arguments here.  The standard
9434        mandates that they be instantiated only when needed, which is
9435        done in build_over_call.  */
9436     default_arg = TREE_PURPOSE (arg_types);
9437
9438     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9439       {
9440         /* We've instantiated a template before its default arguments
9441            have been parsed.  This can happen for a nested template
9442            class, and is not an error unless we require the default
9443            argument in a call of this function.  */
9444         remaining_arg_types = 
9445           tree_cons (default_arg, type, remaining_arg_types);
9446         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9447                        remaining_arg_types);
9448       }
9449     else
9450       remaining_arg_types = 
9451         hash_tree_cons (default_arg, type, remaining_arg_types);
9452   }
9453         
9454   return remaining_arg_types;
9455 }
9456
9457 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9458    *not* handle the exception-specification for FNTYPE, because the
9459    initial substitution of explicitly provided template parameters
9460    during argument deduction forbids substitution into the
9461    exception-specification:
9462
9463      [temp.deduct]
9464
9465      All references in the function type of the function template to  the
9466      corresponding template parameters are replaced by the specified tem-
9467      plate argument values.  If a substitution in a template parameter or
9468      in  the function type of the function template results in an invalid
9469      type, type deduction fails.  [Note: The equivalent  substitution  in
9470      exception specifications is done only when the function is instanti-
9471      ated, at which point a program is  ill-formed  if  the  substitution
9472      results in an invalid type.]  */
9473
9474 static tree
9475 tsubst_function_type (tree t,
9476                       tree args,
9477                       tsubst_flags_t complain,
9478                       tree in_decl)
9479 {
9480   tree return_type;
9481   tree arg_types;
9482   tree fntype;
9483
9484   /* The TYPE_CONTEXT is not used for function/method types.  */
9485   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9486
9487   /* Substitute the return type.  */
9488   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9489   if (return_type == error_mark_node)
9490     return error_mark_node;
9491   /* The standard does not presently indicate that creation of a
9492      function type with an invalid return type is a deduction failure.
9493      However, that is clearly analogous to creating an array of "void"
9494      or a reference to a reference.  This is core issue #486.  */
9495   if (TREE_CODE (return_type) == ARRAY_TYPE
9496       || TREE_CODE (return_type) == FUNCTION_TYPE)
9497     {
9498       if (complain & tf_error)
9499         {
9500           if (TREE_CODE (return_type) == ARRAY_TYPE)
9501             error ("function returning an array");
9502           else
9503             error ("function returning a function");
9504         }
9505       return error_mark_node;
9506     }
9507
9508   /* Substitute the argument types.  */
9509   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9510                                 complain, in_decl);
9511   if (arg_types == error_mark_node)
9512     return error_mark_node;
9513
9514   /* Construct a new type node and return it.  */
9515   if (TREE_CODE (t) == FUNCTION_TYPE)
9516     fntype = build_function_type (return_type, arg_types);
9517   else
9518     {
9519       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9520       if (! MAYBE_CLASS_TYPE_P (r))
9521         {
9522           /* [temp.deduct]
9523
9524              Type deduction may fail for any of the following
9525              reasons:
9526
9527              -- Attempting to create "pointer to member of T" when T
9528              is not a class type.  */
9529           if (complain & tf_error)
9530             error ("creating pointer to member function of non-class type %qT",
9531                       r);
9532           return error_mark_node;
9533         }
9534
9535       fntype = build_method_type_directly (r, return_type,
9536                                            TREE_CHAIN (arg_types));
9537     }
9538   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9539   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9540
9541   return fntype;
9542 }
9543
9544 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9545    ARGS into that specification, and return the substituted
9546    specification.  If there is no specification, return NULL_TREE.  */
9547
9548 static tree
9549 tsubst_exception_specification (tree fntype,
9550                                 tree args,
9551                                 tsubst_flags_t complain,
9552                                 tree in_decl)
9553 {
9554   tree specs;
9555   tree new_specs;
9556
9557   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9558   new_specs = NULL_TREE;
9559   if (specs)
9560     {
9561       if (! TREE_VALUE (specs))
9562         new_specs = specs;
9563       else
9564         while (specs)
9565           {
9566             tree spec;
9567             int i, len = 1;
9568             tree expanded_specs = NULL_TREE;
9569
9570             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9571               {
9572                 /* Expand the pack expansion type.  */
9573                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9574                                                        args, complain,
9575                                                        in_decl);
9576
9577                 if (expanded_specs == error_mark_node)
9578                   return error_mark_node;
9579                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9580                   len = TREE_VEC_LENGTH (expanded_specs);
9581                 else
9582                   {
9583                     /* We're substituting into a member template, so
9584                        we got a TYPE_PACK_EXPANSION back.  Add that
9585                        expansion and move on.  */
9586                     gcc_assert (TREE_CODE (expanded_specs) 
9587                                 == TYPE_PACK_EXPANSION);
9588                     new_specs = add_exception_specifier (new_specs,
9589                                                          expanded_specs,
9590                                                          complain);
9591                     specs = TREE_CHAIN (specs);
9592                     continue;
9593                   }
9594               }
9595
9596             for (i = 0; i < len; ++i)
9597               {
9598                 if (expanded_specs)
9599                   spec = TREE_VEC_ELT (expanded_specs, i);
9600                 else
9601                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9602                 if (spec == error_mark_node)
9603                   return spec;
9604                 new_specs = add_exception_specifier (new_specs, spec, 
9605                                                      complain);
9606               }
9607
9608             specs = TREE_CHAIN (specs);
9609           }
9610     }
9611   return new_specs;
9612 }
9613
9614 /* Take the tree structure T and replace template parameters used
9615    therein with the argument vector ARGS.  IN_DECL is an associated
9616    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9617    Issue error and warning messages under control of COMPLAIN.  Note
9618    that we must be relatively non-tolerant of extensions here, in
9619    order to preserve conformance; if we allow substitutions that
9620    should not be allowed, we may allow argument deductions that should
9621    not succeed, and therefore report ambiguous overload situations
9622    where there are none.  In theory, we could allow the substitution,
9623    but indicate that it should have failed, and allow our caller to
9624    make sure that the right thing happens, but we don't try to do this
9625    yet.
9626
9627    This function is used for dealing with types, decls and the like;
9628    for expressions, use tsubst_expr or tsubst_copy.  */
9629
9630 tree
9631 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9632 {
9633   tree type, r;
9634
9635   if (t == NULL_TREE || t == error_mark_node
9636       || t == integer_type_node
9637       || t == void_type_node
9638       || t == char_type_node
9639       || t == unknown_type_node
9640       || TREE_CODE (t) == NAMESPACE_DECL)
9641     return t;
9642
9643   if (DECL_P (t))
9644     return tsubst_decl (t, args, complain);
9645
9646   if (args == NULL_TREE)
9647     return t;
9648
9649   if (TREE_CODE (t) == IDENTIFIER_NODE)
9650     type = IDENTIFIER_TYPE_VALUE (t);
9651   else
9652     type = TREE_TYPE (t);
9653
9654   gcc_assert (type != unknown_type_node);
9655
9656   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9657      such as attribute aligned.  */
9658   if (TYPE_P (t)
9659       && TYPE_NAME (t)
9660       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9661     {
9662       tree decl = TYPE_NAME (t);
9663       
9664       if (DECL_CLASS_SCOPE_P (decl)
9665           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9666           && uses_template_parms (DECL_CONTEXT (decl)))
9667         {
9668           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9669           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9670           r = retrieve_specialization (tmpl, gen_args, 0);
9671         }
9672       else if (DECL_FUNCTION_SCOPE_P (decl)
9673                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9674                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9675         r = retrieve_local_specialization (decl);
9676       else
9677         /* The typedef is from a non-template context.  */
9678         return t;
9679
9680       if (r)
9681         {
9682           r = TREE_TYPE (r);
9683           r = cp_build_qualified_type_real
9684             (r, cp_type_quals (t) | cp_type_quals (r),
9685              complain | tf_ignore_bad_quals);
9686           return r;
9687         }
9688       /* Else we must be instantiating the typedef, so fall through.  */
9689     }
9690
9691   if (type
9692       && TREE_CODE (t) != TYPENAME_TYPE
9693       && TREE_CODE (t) != IDENTIFIER_NODE
9694       && TREE_CODE (t) != FUNCTION_TYPE
9695       && TREE_CODE (t) != METHOD_TYPE)
9696     type = tsubst (type, args, complain, in_decl);
9697   if (type == error_mark_node)
9698     return error_mark_node;
9699
9700   switch (TREE_CODE (t))
9701     {
9702     case RECORD_TYPE:
9703     case UNION_TYPE:
9704     case ENUMERAL_TYPE:
9705       return tsubst_aggr_type (t, args, complain, in_decl,
9706                                /*entering_scope=*/0);
9707
9708     case ERROR_MARK:
9709     case IDENTIFIER_NODE:
9710     case VOID_TYPE:
9711     case REAL_TYPE:
9712     case COMPLEX_TYPE:
9713     case VECTOR_TYPE:
9714     case BOOLEAN_TYPE:
9715     case INTEGER_CST:
9716     case REAL_CST:
9717     case STRING_CST:
9718       return t;
9719
9720     case INTEGER_TYPE:
9721       if (t == integer_type_node)
9722         return t;
9723
9724       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9725           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9726         return t;
9727
9728       {
9729         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9730
9731         max = tsubst_expr (omax, args, complain, in_decl,
9732                            /*integral_constant_expression_p=*/false);
9733
9734         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9735            needed.  */
9736         if (TREE_CODE (max) == NOP_EXPR
9737             && TREE_SIDE_EFFECTS (omax)
9738             && !TREE_TYPE (max))
9739           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9740
9741         max = fold_decl_constant_value (max);
9742
9743         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9744            with TREE_SIDE_EFFECTS that indicates this is not an integral
9745            constant expression.  */
9746         if (processing_template_decl
9747             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9748           {
9749             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9750             TREE_SIDE_EFFECTS (max) = 1;
9751           }
9752
9753         if (TREE_CODE (max) != INTEGER_CST
9754             && !at_function_scope_p ()
9755             && !TREE_SIDE_EFFECTS (max)
9756             && !value_dependent_expression_p (max))
9757           {
9758             if (complain & tf_error)
9759               error ("array bound is not an integer constant");
9760             return error_mark_node;
9761           }
9762
9763         /* [temp.deduct]
9764
9765            Type deduction may fail for any of the following
9766            reasons:
9767
9768              Attempting to create an array with a size that is
9769              zero or negative.  */
9770         if (integer_zerop (max) && !(complain & tf_error))
9771           /* We must fail if performing argument deduction (as
9772              indicated by the state of complain), so that
9773              another substitution can be found.  */
9774           return error_mark_node;
9775         else if (TREE_CODE (max) == INTEGER_CST
9776                  && INT_CST_LT (max, integer_zero_node))
9777           {
9778             if (complain & tf_error)
9779               error ("creating array with negative size (%qE)", max);
9780
9781             return error_mark_node;
9782           }
9783
9784         return compute_array_index_type (NULL_TREE, max);
9785       }
9786
9787     case TEMPLATE_TYPE_PARM:
9788     case TEMPLATE_TEMPLATE_PARM:
9789     case BOUND_TEMPLATE_TEMPLATE_PARM:
9790     case TEMPLATE_PARM_INDEX:
9791       {
9792         int idx;
9793         int level;
9794         int levels;
9795         tree arg = NULL_TREE;
9796
9797         r = NULL_TREE;
9798
9799         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9800         template_parm_level_and_index (t, &level, &idx); 
9801
9802         levels = TMPL_ARGS_DEPTH (args);
9803         if (level <= levels)
9804           {
9805             arg = TMPL_ARG (args, level, idx);
9806
9807             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9808               /* See through ARGUMENT_PACK_SELECT arguments. */
9809               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9810           }
9811
9812         if (arg == error_mark_node)
9813           return error_mark_node;
9814         else if (arg != NULL_TREE)
9815           {
9816             if (ARGUMENT_PACK_P (arg))
9817               /* If ARG is an argument pack, we don't actually want to
9818                  perform a substitution here, because substitutions
9819                  for argument packs are only done
9820                  element-by-element. We can get to this point when
9821                  substituting the type of a non-type template
9822                  parameter pack, when that type actually contains
9823                  template parameter packs from an outer template, e.g.,
9824
9825                  template<typename... Types> struct A {
9826                    template<Types... Values> struct B { };
9827                  };  */
9828               return t;
9829
9830             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9831               {
9832                 int quals;
9833                 gcc_assert (TYPE_P (arg));
9834
9835                 /* cv-quals from the template are discarded when
9836                    substituting in a function or reference type.  */
9837                 if (TREE_CODE (arg) == FUNCTION_TYPE
9838                     || TREE_CODE (arg) == METHOD_TYPE
9839                     || TREE_CODE (arg) == REFERENCE_TYPE)
9840                   quals = cp_type_quals (arg);
9841                 else
9842                   quals = cp_type_quals (arg) | cp_type_quals (t);
9843                   
9844                 return cp_build_qualified_type_real
9845                   (arg, quals, complain | tf_ignore_bad_quals);
9846               }
9847             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9848               {
9849                 /* We are processing a type constructed from a
9850                    template template parameter.  */
9851                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9852                                       args, complain, in_decl);
9853                 if (argvec == error_mark_node)
9854                   return error_mark_node;
9855
9856                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9857                    are resolving nested-types in the signature of a
9858                    member function templates.  Otherwise ARG is a
9859                    TEMPLATE_DECL and is the real template to be
9860                    instantiated.  */
9861                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9862                   arg = TYPE_NAME (arg);
9863
9864                 r = lookup_template_class (arg,
9865                                            argvec, in_decl,
9866                                            DECL_CONTEXT (arg),
9867                                             /*entering_scope=*/0,
9868                                            complain);
9869                 return cp_build_qualified_type_real
9870                   (r, TYPE_QUALS (t), complain);
9871               }
9872             else
9873               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9874               return arg;
9875           }
9876
9877         if (level == 1)
9878           /* This can happen during the attempted tsubst'ing in
9879              unify.  This means that we don't yet have any information
9880              about the template parameter in question.  */
9881           return t;
9882
9883         /* If we get here, we must have been looking at a parm for a
9884            more deeply nested template.  Make a new version of this
9885            template parameter, but with a lower level.  */
9886         switch (TREE_CODE (t))
9887           {
9888           case TEMPLATE_TYPE_PARM:
9889           case TEMPLATE_TEMPLATE_PARM:
9890           case BOUND_TEMPLATE_TEMPLATE_PARM:
9891             if (cp_type_quals (t))
9892               {
9893                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9894                 r = cp_build_qualified_type_real
9895                   (r, cp_type_quals (t),
9896                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9897                                ? tf_ignore_bad_quals : 0));
9898               }
9899             else
9900               {
9901                 r = copy_type (t);
9902                 TEMPLATE_TYPE_PARM_INDEX (r)
9903                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9904                                                 r, levels, args, complain);
9905                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9906                 TYPE_MAIN_VARIANT (r) = r;
9907                 TYPE_POINTER_TO (r) = NULL_TREE;
9908                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9909
9910                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9911                   /* We have reduced the level of the template
9912                      template parameter, but not the levels of its
9913                      template parameters, so canonical_type_parameter
9914                      will not be able to find the canonical template
9915                      template parameter for this level. Thus, we
9916                      require structural equality checking to compare
9917                      TEMPLATE_TEMPLATE_PARMs. */
9918                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9919                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9920                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9921                 else
9922                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9923
9924                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9925                   {
9926                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9927                                           complain, in_decl);
9928                     if (argvec == error_mark_node)
9929                       return error_mark_node;
9930
9931                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9932                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
9933                   }
9934               }
9935             break;
9936
9937           case TEMPLATE_PARM_INDEX:
9938             r = reduce_template_parm_level (t, type, levels, args, complain);
9939             break;
9940
9941           default:
9942             gcc_unreachable ();
9943           }
9944
9945         return r;
9946       }
9947
9948     case TREE_LIST:
9949       {
9950         tree purpose, value, chain;
9951
9952         if (t == void_list_node)
9953           return t;
9954
9955         purpose = TREE_PURPOSE (t);
9956         if (purpose)
9957           {
9958             purpose = tsubst (purpose, args, complain, in_decl);
9959             if (purpose == error_mark_node)
9960               return error_mark_node;
9961           }
9962         value = TREE_VALUE (t);
9963         if (value)
9964           {
9965             value = tsubst (value, args, complain, in_decl);
9966             if (value == error_mark_node)
9967               return error_mark_node;
9968           }
9969         chain = TREE_CHAIN (t);
9970         if (chain && chain != void_type_node)
9971           {
9972             chain = tsubst (chain, args, complain, in_decl);
9973             if (chain == error_mark_node)
9974               return error_mark_node;
9975           }
9976         if (purpose == TREE_PURPOSE (t)
9977             && value == TREE_VALUE (t)
9978             && chain == TREE_CHAIN (t))
9979           return t;
9980         return hash_tree_cons (purpose, value, chain);
9981       }
9982
9983     case TREE_BINFO:
9984       /* We should never be tsubsting a binfo.  */
9985       gcc_unreachable ();
9986
9987     case TREE_VEC:
9988       /* A vector of template arguments.  */
9989       gcc_assert (!type);
9990       return tsubst_template_args (t, args, complain, in_decl);
9991
9992     case POINTER_TYPE:
9993     case REFERENCE_TYPE:
9994       {
9995         enum tree_code code;
9996
9997         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9998           return t;
9999
10000         code = TREE_CODE (t);
10001
10002
10003         /* [temp.deduct]
10004
10005            Type deduction may fail for any of the following
10006            reasons:
10007
10008            -- Attempting to create a pointer to reference type.
10009            -- Attempting to create a reference to a reference type or
10010               a reference to void.
10011
10012           Core issue 106 says that creating a reference to a reference
10013           during instantiation is no longer a cause for failure. We
10014           only enforce this check in strict C++98 mode.  */
10015         if ((TREE_CODE (type) == REFERENCE_TYPE
10016              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10017             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10018           {
10019             static location_t last_loc;
10020
10021             /* We keep track of the last time we issued this error
10022                message to avoid spewing a ton of messages during a
10023                single bad template instantiation.  */
10024             if (complain & tf_error
10025                 && last_loc != input_location)
10026               {
10027                 if (TREE_CODE (type) == VOID_TYPE)
10028                   error ("forming reference to void");
10029                 else
10030                   error ("forming %s to reference type %qT",
10031                          (code == POINTER_TYPE) ? "pointer" : "reference",
10032                          type);
10033                 last_loc = input_location;
10034               }
10035
10036             return error_mark_node;
10037           }
10038         else if (code == POINTER_TYPE)
10039           {
10040             r = build_pointer_type (type);
10041             if (TREE_CODE (type) == METHOD_TYPE)
10042               r = build_ptrmemfunc_type (r);
10043           }
10044         else if (TREE_CODE (type) == REFERENCE_TYPE)
10045           /* In C++0x, during template argument substitution, when there is an
10046              attempt to create a reference to a reference type, reference
10047              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10048
10049              "If a template-argument for a template-parameter T names a type
10050              that is a reference to a type A, an attempt to create the type
10051              'lvalue reference to cv T' creates the type 'lvalue reference to
10052              A,' while an attempt to create the type type rvalue reference to
10053              cv T' creates the type T"
10054           */
10055           r = cp_build_reference_type
10056               (TREE_TYPE (type),
10057                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10058         else
10059           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10060         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10061
10062         if (r != error_mark_node)
10063           /* Will this ever be needed for TYPE_..._TO values?  */
10064           layout_type (r);
10065
10066         return r;
10067       }
10068     case OFFSET_TYPE:
10069       {
10070         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10071         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10072           {
10073             /* [temp.deduct]
10074
10075                Type deduction may fail for any of the following
10076                reasons:
10077
10078                -- Attempting to create "pointer to member of T" when T
10079                   is not a class type.  */
10080             if (complain & tf_error)
10081               error ("creating pointer to member of non-class type %qT", r);
10082             return error_mark_node;
10083           }
10084         if (TREE_CODE (type) == REFERENCE_TYPE)
10085           {
10086             if (complain & tf_error)
10087               error ("creating pointer to member reference type %qT", type);
10088             return error_mark_node;
10089           }
10090         if (TREE_CODE (type) == VOID_TYPE)
10091           {
10092             if (complain & tf_error)
10093               error ("creating pointer to member of type void");
10094             return error_mark_node;
10095           }
10096         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10097         if (TREE_CODE (type) == FUNCTION_TYPE)
10098           {
10099             /* The type of the implicit object parameter gets its
10100                cv-qualifiers from the FUNCTION_TYPE. */
10101             tree memptr;
10102             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10103             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10104             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10105                                                  complain);
10106           }
10107         else
10108           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10109                                                TYPE_QUALS (t),
10110                                                complain);
10111       }
10112     case FUNCTION_TYPE:
10113     case METHOD_TYPE:
10114       {
10115         tree fntype;
10116         tree specs;
10117         fntype = tsubst_function_type (t, args, complain, in_decl);
10118         if (fntype == error_mark_node)
10119           return error_mark_node;
10120
10121         /* Substitute the exception specification.  */
10122         specs = tsubst_exception_specification (t, args, complain,
10123                                                 in_decl);
10124         if (specs == error_mark_node)
10125           return error_mark_node;
10126         if (specs)
10127           fntype = build_exception_variant (fntype, specs);
10128         return fntype;
10129       }
10130     case ARRAY_TYPE:
10131       {
10132         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10133         if (domain == error_mark_node)
10134           return error_mark_node;
10135
10136         /* As an optimization, we avoid regenerating the array type if
10137            it will obviously be the same as T.  */
10138         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10139           return t;
10140
10141         /* These checks should match the ones in grokdeclarator.
10142
10143            [temp.deduct]
10144
10145            The deduction may fail for any of the following reasons:
10146
10147            -- Attempting to create an array with an element type that
10148               is void, a function type, or a reference type, or [DR337]
10149               an abstract class type.  */
10150         if (TREE_CODE (type) == VOID_TYPE
10151             || TREE_CODE (type) == FUNCTION_TYPE
10152             || TREE_CODE (type) == REFERENCE_TYPE)
10153           {
10154             if (complain & tf_error)
10155               error ("creating array of %qT", type);
10156             return error_mark_node;
10157           }
10158         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10159           {
10160             if (complain & tf_error)
10161               error ("creating array of %qT, which is an abstract class type",
10162                      type);
10163             return error_mark_node;
10164           }
10165
10166         r = build_cplus_array_type (type, domain);
10167
10168         if (TYPE_USER_ALIGN (t))
10169           {
10170             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10171             TYPE_USER_ALIGN (r) = 1;
10172           }
10173
10174         return r;
10175       }
10176
10177     case PLUS_EXPR:
10178     case MINUS_EXPR:
10179       {
10180         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10181         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10182
10183         if (e1 == error_mark_node || e2 == error_mark_node)
10184           return error_mark_node;
10185
10186         return fold_build2_loc (input_location,
10187                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10188       }
10189
10190     case NEGATE_EXPR:
10191     case NOP_EXPR:
10192       {
10193         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10194         if (e == error_mark_node)
10195           return error_mark_node;
10196
10197         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10198       }
10199
10200     case TYPENAME_TYPE:
10201       {
10202         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10203                                      in_decl, /*entering_scope=*/1);
10204         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10205                               complain, in_decl);
10206
10207         if (ctx == error_mark_node || f == error_mark_node)
10208           return error_mark_node;
10209
10210         if (!MAYBE_CLASS_TYPE_P (ctx))
10211           {
10212             if (complain & tf_error)
10213               error ("%qT is not a class, struct, or union type", ctx);
10214             return error_mark_node;
10215           }
10216         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10217           {
10218             /* Normally, make_typename_type does not require that the CTX
10219                have complete type in order to allow things like:
10220
10221                  template <class T> struct S { typename S<T>::X Y; };
10222
10223                But, such constructs have already been resolved by this
10224                point, so here CTX really should have complete type, unless
10225                it's a partial instantiation.  */
10226             if (!(complain & tf_no_class_instantiations))
10227               ctx = complete_type (ctx);
10228             if (!COMPLETE_TYPE_P (ctx))
10229               {
10230                 if (complain & tf_error)
10231                   cxx_incomplete_type_error (NULL_TREE, ctx);
10232                 return error_mark_node;
10233               }
10234           }
10235
10236         f = make_typename_type (ctx, f, typename_type,
10237                                 (complain & tf_error) | tf_keep_type_decl);
10238         if (f == error_mark_node)
10239           return f;
10240         if (TREE_CODE (f) == TYPE_DECL)
10241           {
10242             complain |= tf_ignore_bad_quals;
10243             f = TREE_TYPE (f);
10244           }
10245
10246         if (TREE_CODE (f) != TYPENAME_TYPE)
10247           {
10248             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10249               error ("%qT resolves to %qT, which is not an enumeration type",
10250                      t, f);
10251             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10252               error ("%qT resolves to %qT, which is is not a class type",
10253                      t, f);
10254           }
10255
10256         return cp_build_qualified_type_real
10257           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10258       }
10259
10260     case UNBOUND_CLASS_TEMPLATE:
10261       {
10262         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10263                                      in_decl, /*entering_scope=*/1);
10264         tree name = TYPE_IDENTIFIER (t);
10265         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10266
10267         if (ctx == error_mark_node || name == error_mark_node)
10268           return error_mark_node;
10269
10270         if (parm_list)
10271           parm_list = tsubst_template_parms (parm_list, args, complain);
10272         return make_unbound_class_template (ctx, name, parm_list, complain);
10273       }
10274
10275     case INDIRECT_REF:
10276     case ADDR_EXPR:
10277     case CALL_EXPR:
10278       gcc_unreachable ();
10279
10280     case ARRAY_REF:
10281       {
10282         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10283         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10284                                /*integral_constant_expression_p=*/false);
10285         if (e1 == error_mark_node || e2 == error_mark_node)
10286           return error_mark_node;
10287
10288         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10289       }
10290
10291     case SCOPE_REF:
10292       {
10293         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10294         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10295         if (e1 == error_mark_node || e2 == error_mark_node)
10296           return error_mark_node;
10297
10298         return build_qualified_name (/*type=*/NULL_TREE,
10299                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10300       }
10301
10302     case TYPEOF_TYPE:
10303       {
10304         tree type;
10305
10306         ++cp_unevaluated_operand;
10307         ++c_inhibit_evaluation_warnings;
10308
10309         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10310                             complain, in_decl,
10311                             /*integral_constant_expression_p=*/false);
10312
10313         --cp_unevaluated_operand;
10314         --c_inhibit_evaluation_warnings;
10315
10316         type = finish_typeof (type);
10317         return cp_build_qualified_type_real (type,
10318                                              cp_type_quals (t)
10319                                              | cp_type_quals (type),
10320                                              complain);
10321       }
10322
10323     case DECLTYPE_TYPE:
10324       {
10325         tree type;
10326
10327         ++cp_unevaluated_operand;
10328         ++c_inhibit_evaluation_warnings;
10329
10330         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10331                             complain, in_decl,
10332                             /*integral_constant_expression_p=*/false);
10333
10334         --cp_unevaluated_operand;
10335         --c_inhibit_evaluation_warnings;
10336
10337         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10338           type = lambda_capture_field_type (type);
10339         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10340           type = lambda_return_type (type);
10341         else
10342           type = finish_decltype_type
10343             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10344         return cp_build_qualified_type_real (type,
10345                                              cp_type_quals (t)
10346                                              | cp_type_quals (type),
10347                                              complain);
10348       }
10349
10350     case TYPE_ARGUMENT_PACK:
10351     case NONTYPE_ARGUMENT_PACK:
10352       {
10353         tree r = TYPE_P (t)
10354           ? cxx_make_type (TREE_CODE (t))
10355           : make_node (TREE_CODE (t));
10356         tree packed_out = 
10357           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10358                                 args,
10359                                 complain,
10360                                 in_decl);
10361         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10362
10363         /* For template nontype argument packs, also substitute into
10364            the type.  */
10365         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10366           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10367
10368         return r;
10369       }
10370       break;
10371
10372     default:
10373       sorry ("use of %qs in template",
10374              tree_code_name [(int) TREE_CODE (t)]);
10375       return error_mark_node;
10376     }
10377 }
10378
10379 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10380    type of the expression on the left-hand side of the "." or "->"
10381    operator.  */
10382
10383 static tree
10384 tsubst_baselink (tree baselink, tree object_type,
10385                  tree args, tsubst_flags_t complain, tree in_decl)
10386 {
10387     tree name;
10388     tree qualifying_scope;
10389     tree fns;
10390     tree optype;
10391     tree template_args = 0;
10392     bool template_id_p = false;
10393
10394     /* A baselink indicates a function from a base class.  Both the
10395        BASELINK_ACCESS_BINFO and the base class referenced may
10396        indicate bases of the template class, rather than the
10397        instantiated class.  In addition, lookups that were not
10398        ambiguous before may be ambiguous now.  Therefore, we perform
10399        the lookup again.  */
10400     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10401     qualifying_scope = tsubst (qualifying_scope, args,
10402                                complain, in_decl);
10403     fns = BASELINK_FUNCTIONS (baselink);
10404     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10405     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10406       {
10407         template_id_p = true;
10408         template_args = TREE_OPERAND (fns, 1);
10409         fns = TREE_OPERAND (fns, 0);
10410         if (template_args)
10411           template_args = tsubst_template_args (template_args, args,
10412                                                 complain, in_decl);
10413       }
10414     name = DECL_NAME (get_first_fn (fns));
10415     if (IDENTIFIER_TYPENAME_P (name))
10416       name = mangle_conv_op_name_for_type (optype);
10417     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10418
10419     /* If lookup found a single function, mark it as used at this
10420        point.  (If it lookup found multiple functions the one selected
10421        later by overload resolution will be marked as used at that
10422        point.)  */
10423     if (BASELINK_P (baselink))
10424       fns = BASELINK_FUNCTIONS (baselink);
10425     if (!template_id_p && !really_overloaded_fn (fns))
10426       mark_used (OVL_CURRENT (fns));
10427
10428     /* Add back the template arguments, if present.  */
10429     if (BASELINK_P (baselink) && template_id_p)
10430       BASELINK_FUNCTIONS (baselink)
10431         = build_nt (TEMPLATE_ID_EXPR,
10432                     BASELINK_FUNCTIONS (baselink),
10433                     template_args);
10434     /* Update the conversion operator type.  */
10435     BASELINK_OPTYPE (baselink) = optype;
10436
10437     if (!object_type)
10438       object_type = current_class_type;
10439     return adjust_result_of_qualified_name_lookup (baselink,
10440                                                    qualifying_scope,
10441                                                    object_type);
10442 }
10443
10444 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10445    true if the qualified-id will be a postfix-expression in-and-of
10446    itself; false if more of the postfix-expression follows the
10447    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10448    of "&".  */
10449
10450 static tree
10451 tsubst_qualified_id (tree qualified_id, tree args,
10452                      tsubst_flags_t complain, tree in_decl,
10453                      bool done, bool address_p)
10454 {
10455   tree expr;
10456   tree scope;
10457   tree name;
10458   bool is_template;
10459   tree template_args;
10460
10461   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10462
10463   /* Figure out what name to look up.  */
10464   name = TREE_OPERAND (qualified_id, 1);
10465   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10466     {
10467       is_template = true;
10468       template_args = TREE_OPERAND (name, 1);
10469       if (template_args)
10470         template_args = tsubst_template_args (template_args, args,
10471                                               complain, in_decl);
10472       name = TREE_OPERAND (name, 0);
10473     }
10474   else
10475     {
10476       is_template = false;
10477       template_args = NULL_TREE;
10478     }
10479
10480   /* Substitute into the qualifying scope.  When there are no ARGS, we
10481      are just trying to simplify a non-dependent expression.  In that
10482      case the qualifying scope may be dependent, and, in any case,
10483      substituting will not help.  */
10484   scope = TREE_OPERAND (qualified_id, 0);
10485   if (args)
10486     {
10487       scope = tsubst (scope, args, complain, in_decl);
10488       expr = tsubst_copy (name, args, complain, in_decl);
10489     }
10490   else
10491     expr = name;
10492
10493   if (dependent_type_p (scope))
10494     {
10495       tree type = NULL_TREE;
10496       if (DECL_P (expr) && !dependent_scope_p (scope))
10497         type = TREE_TYPE (expr);
10498       return build_qualified_name (type, scope, expr,
10499                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10500     }
10501
10502   if (!BASELINK_P (name) && !DECL_P (expr))
10503     {
10504       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10505         {
10506           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10507           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10508             {
10509               error ("qualifying type %qT does not match destructor name ~%qT",
10510                      scope, TREE_OPERAND (expr, 0));
10511               expr = error_mark_node;
10512             }
10513           else
10514             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10515                                           /*is_type_p=*/0, false);
10516         }
10517       else
10518         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10519       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10520                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10521         {
10522           if (complain & tf_error)
10523             {
10524               error ("dependent-name %qE is parsed as a non-type, but "
10525                      "instantiation yields a type", qualified_id);
10526               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10527             }
10528           return error_mark_node;
10529         }
10530     }
10531
10532   if (DECL_P (expr))
10533     {
10534       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10535                                            scope);
10536       /* Remember that there was a reference to this entity.  */
10537       mark_used (expr);
10538     }
10539
10540   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10541     {
10542       if (complain & tf_error)
10543         qualified_name_lookup_error (scope,
10544                                      TREE_OPERAND (qualified_id, 1),
10545                                      expr, input_location);
10546       return error_mark_node;
10547     }
10548
10549   if (is_template)
10550     expr = lookup_template_function (expr, template_args);
10551
10552   if (expr == error_mark_node && complain & tf_error)
10553     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10554                                  expr, input_location);
10555   else if (TYPE_P (scope))
10556     {
10557       expr = (adjust_result_of_qualified_name_lookup
10558               (expr, scope, current_class_type));
10559       expr = (finish_qualified_id_expr
10560               (scope, expr, done, address_p,
10561                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10562                /*template_arg_p=*/false));
10563     }
10564
10565   /* Expressions do not generally have reference type.  */
10566   if (TREE_CODE (expr) != SCOPE_REF
10567       /* However, if we're about to form a pointer-to-member, we just
10568          want the referenced member referenced.  */
10569       && TREE_CODE (expr) != OFFSET_REF)
10570     expr = convert_from_reference (expr);
10571
10572   return expr;
10573 }
10574
10575 /* Like tsubst, but deals with expressions.  This function just replaces
10576    template parms; to finish processing the resultant expression, use
10577    tsubst_expr.  */
10578
10579 static tree
10580 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10581 {
10582   enum tree_code code;
10583   tree r;
10584
10585   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10586     return t;
10587
10588   code = TREE_CODE (t);
10589
10590   switch (code)
10591     {
10592     case PARM_DECL:
10593       r = retrieve_local_specialization (t);
10594
10595       if (r == NULL)
10596         {
10597           tree c;
10598           /* This can happen for a parameter name used later in a function
10599              declaration (such as in a late-specified return type).  Just
10600              make a dummy decl, since it's only used for its type.  */
10601           gcc_assert (cp_unevaluated_operand != 0);
10602           /* We copy T because want to tsubst the PARM_DECL only,
10603              not the following PARM_DECLs that are chained to T.  */
10604           c = copy_node (t);
10605           r = tsubst_decl (c, args, complain);
10606           /* Give it the template pattern as its context; its true context
10607              hasn't been instantiated yet and this is good enough for
10608              mangling.  */
10609           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10610         }
10611       
10612       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10613         r = ARGUMENT_PACK_SELECT_ARG (r);
10614       mark_used (r);
10615       return r;
10616
10617     case CONST_DECL:
10618       {
10619         tree enum_type;
10620         tree v;
10621
10622         if (DECL_TEMPLATE_PARM_P (t))
10623           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10624         /* There is no need to substitute into namespace-scope
10625            enumerators.  */
10626         if (DECL_NAMESPACE_SCOPE_P (t))
10627           return t;
10628         /* If ARGS is NULL, then T is known to be non-dependent.  */
10629         if (args == NULL_TREE)
10630           return integral_constant_value (t);
10631
10632         /* Unfortunately, we cannot just call lookup_name here.
10633            Consider:
10634
10635              template <int I> int f() {
10636              enum E { a = I };
10637              struct S { void g() { E e = a; } };
10638              };
10639
10640            When we instantiate f<7>::S::g(), say, lookup_name is not
10641            clever enough to find f<7>::a.  */
10642         enum_type
10643           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10644                               /*entering_scope=*/0);
10645
10646         for (v = TYPE_VALUES (enum_type);
10647              v != NULL_TREE;
10648              v = TREE_CHAIN (v))
10649           if (TREE_PURPOSE (v) == DECL_NAME (t))
10650             return TREE_VALUE (v);
10651
10652           /* We didn't find the name.  That should never happen; if
10653              name-lookup found it during preliminary parsing, we
10654              should find it again here during instantiation.  */
10655         gcc_unreachable ();
10656       }
10657       return t;
10658
10659     case FIELD_DECL:
10660       if (DECL_CONTEXT (t))
10661         {
10662           tree ctx;
10663
10664           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10665                                   /*entering_scope=*/1);
10666           if (ctx != DECL_CONTEXT (t))
10667             {
10668               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10669               if (!r)
10670                 {
10671                   if (complain & tf_error)
10672                     error ("using invalid field %qD", t);
10673                   return error_mark_node;
10674                 }
10675               return r;
10676             }
10677         }
10678
10679       return t;
10680
10681     case VAR_DECL:
10682     case FUNCTION_DECL:
10683       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10684           || local_variable_p (t))
10685         t = tsubst (t, args, complain, in_decl);
10686       mark_used (t);
10687       return t;
10688
10689     case BASELINK:
10690       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10691
10692     case TEMPLATE_DECL:
10693       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10694         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10695                        args, complain, in_decl);
10696       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10697         return tsubst (t, args, complain, in_decl);
10698       else if (DECL_CLASS_SCOPE_P (t)
10699                && uses_template_parms (DECL_CONTEXT (t)))
10700         {
10701           /* Template template argument like the following example need
10702              special treatment:
10703
10704                template <template <class> class TT> struct C {};
10705                template <class T> struct D {
10706                  template <class U> struct E {};
10707                  C<E> c;                                // #1
10708                };
10709                D<int> d;                                // #2
10710
10711              We are processing the template argument `E' in #1 for
10712              the template instantiation #2.  Originally, `E' is a
10713              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10714              have to substitute this with one having context `D<int>'.  */
10715
10716           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10717           return lookup_field (context, DECL_NAME(t), 0, false);
10718         }
10719       else
10720         /* Ordinary template template argument.  */
10721         return t;
10722
10723     case CAST_EXPR:
10724     case REINTERPRET_CAST_EXPR:
10725     case CONST_CAST_EXPR:
10726     case STATIC_CAST_EXPR:
10727     case DYNAMIC_CAST_EXPR:
10728     case NOP_EXPR:
10729       return build1
10730         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10731          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10732
10733     case SIZEOF_EXPR:
10734       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10735         {
10736           /* We only want to compute the number of arguments.  */
10737           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10738                                                 complain, in_decl);
10739           int len = 0;
10740
10741           if (TREE_CODE (expanded) == TREE_VEC)
10742             len = TREE_VEC_LENGTH (expanded);
10743
10744           if (expanded == error_mark_node)
10745             return error_mark_node;
10746           else if (PACK_EXPANSION_P (expanded)
10747                    || (TREE_CODE (expanded) == TREE_VEC
10748                        && len > 0
10749                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10750             {
10751               if (TREE_CODE (expanded) == TREE_VEC)
10752                 expanded = TREE_VEC_ELT (expanded, len - 1);
10753
10754               if (TYPE_P (expanded))
10755                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10756                                                    complain & tf_error);
10757               else
10758                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10759                                                    complain & tf_error);
10760             }
10761           else
10762             return build_int_cst (size_type_node, len);
10763         }
10764       /* Fall through */
10765
10766     case INDIRECT_REF:
10767     case NEGATE_EXPR:
10768     case TRUTH_NOT_EXPR:
10769     case BIT_NOT_EXPR:
10770     case ADDR_EXPR:
10771     case UNARY_PLUS_EXPR:      /* Unary + */
10772     case ALIGNOF_EXPR:
10773     case ARROW_EXPR:
10774     case THROW_EXPR:
10775     case TYPEID_EXPR:
10776     case REALPART_EXPR:
10777     case IMAGPART_EXPR:
10778       return build1
10779         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10780          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10781
10782     case COMPONENT_REF:
10783       {
10784         tree object;
10785         tree name;
10786
10787         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10788         name = TREE_OPERAND (t, 1);
10789         if (TREE_CODE (name) == BIT_NOT_EXPR)
10790           {
10791             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10792                                 complain, in_decl);
10793             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10794           }
10795         else if (TREE_CODE (name) == SCOPE_REF
10796                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10797           {
10798             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10799                                      complain, in_decl);
10800             name = TREE_OPERAND (name, 1);
10801             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10802                                 complain, in_decl);
10803             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10804             name = build_qualified_name (/*type=*/NULL_TREE,
10805                                          base, name,
10806                                          /*template_p=*/false);
10807           }
10808         else if (TREE_CODE (name) == BASELINK)
10809           name = tsubst_baselink (name,
10810                                   non_reference (TREE_TYPE (object)),
10811                                   args, complain,
10812                                   in_decl);
10813         else
10814           name = tsubst_copy (name, args, complain, in_decl);
10815         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10816       }
10817
10818     case PLUS_EXPR:
10819     case MINUS_EXPR:
10820     case MULT_EXPR:
10821     case TRUNC_DIV_EXPR:
10822     case CEIL_DIV_EXPR:
10823     case FLOOR_DIV_EXPR:
10824     case ROUND_DIV_EXPR:
10825     case EXACT_DIV_EXPR:
10826     case BIT_AND_EXPR:
10827     case BIT_IOR_EXPR:
10828     case BIT_XOR_EXPR:
10829     case TRUNC_MOD_EXPR:
10830     case FLOOR_MOD_EXPR:
10831     case TRUTH_ANDIF_EXPR:
10832     case TRUTH_ORIF_EXPR:
10833     case TRUTH_AND_EXPR:
10834     case TRUTH_OR_EXPR:
10835     case RSHIFT_EXPR:
10836     case LSHIFT_EXPR:
10837     case RROTATE_EXPR:
10838     case LROTATE_EXPR:
10839     case EQ_EXPR:
10840     case NE_EXPR:
10841     case MAX_EXPR:
10842     case MIN_EXPR:
10843     case LE_EXPR:
10844     case GE_EXPR:
10845     case LT_EXPR:
10846     case GT_EXPR:
10847     case COMPOUND_EXPR:
10848     case DOTSTAR_EXPR:
10849     case MEMBER_REF:
10850     case PREDECREMENT_EXPR:
10851     case PREINCREMENT_EXPR:
10852     case POSTDECREMENT_EXPR:
10853     case POSTINCREMENT_EXPR:
10854       return build_nt
10855         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10856          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10857
10858     case SCOPE_REF:
10859       return build_qualified_name (/*type=*/NULL_TREE,
10860                                    tsubst_copy (TREE_OPERAND (t, 0),
10861                                                 args, complain, in_decl),
10862                                    tsubst_copy (TREE_OPERAND (t, 1),
10863                                                 args, complain, in_decl),
10864                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10865
10866     case ARRAY_REF:
10867       return build_nt
10868         (ARRAY_REF,
10869          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10870          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10871          NULL_TREE, NULL_TREE);
10872
10873     case CALL_EXPR:
10874       {
10875         int n = VL_EXP_OPERAND_LENGTH (t);
10876         tree result = build_vl_exp (CALL_EXPR, n);
10877         int i;
10878         for (i = 0; i < n; i++)
10879           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10880                                              complain, in_decl);
10881         return result;
10882       }
10883
10884     case COND_EXPR:
10885     case MODOP_EXPR:
10886     case PSEUDO_DTOR_EXPR:
10887       {
10888         r = build_nt
10889           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10890            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10891            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10892         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10893         return r;
10894       }
10895
10896     case NEW_EXPR:
10897       {
10898         r = build_nt
10899         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10900          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10901          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10902         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10903         return r;
10904       }
10905
10906     case DELETE_EXPR:
10907       {
10908         r = build_nt
10909         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10910          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10911         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10912         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10913         return r;
10914       }
10915
10916     case TEMPLATE_ID_EXPR:
10917       {
10918         /* Substituted template arguments */
10919         tree fn = TREE_OPERAND (t, 0);
10920         tree targs = TREE_OPERAND (t, 1);
10921
10922         fn = tsubst_copy (fn, args, complain, in_decl);
10923         if (targs)
10924           targs = tsubst_template_args (targs, args, complain, in_decl);
10925
10926         return lookup_template_function (fn, targs);
10927       }
10928
10929     case TREE_LIST:
10930       {
10931         tree purpose, value, chain;
10932
10933         if (t == void_list_node)
10934           return t;
10935
10936         purpose = TREE_PURPOSE (t);
10937         if (purpose)
10938           purpose = tsubst_copy (purpose, args, complain, in_decl);
10939         value = TREE_VALUE (t);
10940         if (value)
10941           value = tsubst_copy (value, args, complain, in_decl);
10942         chain = TREE_CHAIN (t);
10943         if (chain && chain != void_type_node)
10944           chain = tsubst_copy (chain, args, complain, in_decl);
10945         if (purpose == TREE_PURPOSE (t)
10946             && value == TREE_VALUE (t)
10947             && chain == TREE_CHAIN (t))
10948           return t;
10949         return tree_cons (purpose, value, chain);
10950       }
10951
10952     case RECORD_TYPE:
10953     case UNION_TYPE:
10954     case ENUMERAL_TYPE:
10955     case INTEGER_TYPE:
10956     case TEMPLATE_TYPE_PARM:
10957     case TEMPLATE_TEMPLATE_PARM:
10958     case BOUND_TEMPLATE_TEMPLATE_PARM:
10959     case TEMPLATE_PARM_INDEX:
10960     case POINTER_TYPE:
10961     case REFERENCE_TYPE:
10962     case OFFSET_TYPE:
10963     case FUNCTION_TYPE:
10964     case METHOD_TYPE:
10965     case ARRAY_TYPE:
10966     case TYPENAME_TYPE:
10967     case UNBOUND_CLASS_TEMPLATE:
10968     case TYPEOF_TYPE:
10969     case DECLTYPE_TYPE:
10970     case TYPE_DECL:
10971       return tsubst (t, args, complain, in_decl);
10972
10973     case IDENTIFIER_NODE:
10974       if (IDENTIFIER_TYPENAME_P (t))
10975         {
10976           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10977           return mangle_conv_op_name_for_type (new_type);
10978         }
10979       else
10980         return t;
10981
10982     case CONSTRUCTOR:
10983       /* This is handled by tsubst_copy_and_build.  */
10984       gcc_unreachable ();
10985
10986     case VA_ARG_EXPR:
10987       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10988                                           in_decl),
10989                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10990
10991     case CLEANUP_POINT_EXPR:
10992       /* We shouldn't have built any of these during initial template
10993          generation.  Instead, they should be built during instantiation
10994          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10995       gcc_unreachable ();
10996
10997     case OFFSET_REF:
10998       mark_used (TREE_OPERAND (t, 1));
10999       return t;
11000
11001     case EXPR_PACK_EXPANSION:
11002       error ("invalid use of pack expansion expression");
11003       return error_mark_node;
11004
11005     case NONTYPE_ARGUMENT_PACK:
11006       error ("use %<...%> to expand argument pack");
11007       return error_mark_node;
11008
11009     default:
11010       return t;
11011     }
11012 }
11013
11014 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11015
11016 static tree
11017 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11018                     tree in_decl)
11019 {
11020   tree new_clauses = NULL, nc, oc;
11021
11022   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11023     {
11024       nc = copy_node (oc);
11025       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11026       new_clauses = nc;
11027
11028       switch (OMP_CLAUSE_CODE (nc))
11029         {
11030         case OMP_CLAUSE_LASTPRIVATE:
11031           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11032             {
11033               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11034               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11035                            in_decl, /*integral_constant_expression_p=*/false);
11036               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11037                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11038             }
11039           /* FALLTHRU */
11040         case OMP_CLAUSE_PRIVATE:
11041         case OMP_CLAUSE_SHARED:
11042         case OMP_CLAUSE_FIRSTPRIVATE:
11043         case OMP_CLAUSE_REDUCTION:
11044         case OMP_CLAUSE_COPYIN:
11045         case OMP_CLAUSE_COPYPRIVATE:
11046         case OMP_CLAUSE_IF:
11047         case OMP_CLAUSE_NUM_THREADS:
11048         case OMP_CLAUSE_SCHEDULE:
11049         case OMP_CLAUSE_COLLAPSE:
11050           OMP_CLAUSE_OPERAND (nc, 0)
11051             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11052                            in_decl, /*integral_constant_expression_p=*/false);
11053           break;
11054         case OMP_CLAUSE_NOWAIT:
11055         case OMP_CLAUSE_ORDERED:
11056         case OMP_CLAUSE_DEFAULT:
11057         case OMP_CLAUSE_UNTIED:
11058           break;
11059         default:
11060           gcc_unreachable ();
11061         }
11062     }
11063
11064   return finish_omp_clauses (nreverse (new_clauses));
11065 }
11066
11067 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11068
11069 static tree
11070 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11071                           tree in_decl)
11072 {
11073 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11074
11075   tree purpose, value, chain;
11076
11077   if (t == NULL)
11078     return t;
11079
11080   if (TREE_CODE (t) != TREE_LIST)
11081     return tsubst_copy_and_build (t, args, complain, in_decl,
11082                                   /*function_p=*/false,
11083                                   /*integral_constant_expression_p=*/false);
11084
11085   if (t == void_list_node)
11086     return t;
11087
11088   purpose = TREE_PURPOSE (t);
11089   if (purpose)
11090     purpose = RECUR (purpose);
11091   value = TREE_VALUE (t);
11092   if (value && TREE_CODE (value) != LABEL_DECL)
11093     value = RECUR (value);
11094   chain = TREE_CHAIN (t);
11095   if (chain && chain != void_type_node)
11096     chain = RECUR (chain);
11097   return tree_cons (purpose, value, chain);
11098 #undef RECUR
11099 }
11100
11101 /* Substitute one OMP_FOR iterator.  */
11102
11103 static void
11104 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11105                          tree condv, tree incrv, tree *clauses,
11106                          tree args, tsubst_flags_t complain, tree in_decl,
11107                          bool integral_constant_expression_p)
11108 {
11109 #define RECUR(NODE)                             \
11110   tsubst_expr ((NODE), args, complain, in_decl, \
11111                integral_constant_expression_p)
11112   tree decl, init, cond, incr, auto_node;
11113
11114   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11115   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11116   decl = RECUR (TREE_OPERAND (init, 0));
11117   init = TREE_OPERAND (init, 1);
11118   auto_node = type_uses_auto (TREE_TYPE (decl));
11119   if (auto_node && init)
11120     {
11121       tree init_expr = init;
11122       if (TREE_CODE (init_expr) == DECL_EXPR)
11123         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11124       init_expr = RECUR (init_expr);
11125       TREE_TYPE (decl)
11126         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11127     }
11128   gcc_assert (!type_dependent_expression_p (decl));
11129
11130   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11131     {
11132       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11133       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11134       if (TREE_CODE (incr) == MODIFY_EXPR)
11135         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11136                                     RECUR (TREE_OPERAND (incr, 1)),
11137                                     complain);
11138       else
11139         incr = RECUR (incr);
11140       TREE_VEC_ELT (declv, i) = decl;
11141       TREE_VEC_ELT (initv, i) = init;
11142       TREE_VEC_ELT (condv, i) = cond;
11143       TREE_VEC_ELT (incrv, i) = incr;
11144       return;
11145     }
11146
11147   if (init && TREE_CODE (init) != DECL_EXPR)
11148     {
11149       tree c;
11150       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11151         {
11152           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11153                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11154               && OMP_CLAUSE_DECL (c) == decl)
11155             break;
11156           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11157                    && OMP_CLAUSE_DECL (c) == decl)
11158             error ("iteration variable %qD should not be firstprivate", decl);
11159           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11160                    && OMP_CLAUSE_DECL (c) == decl)
11161             error ("iteration variable %qD should not be reduction", decl);
11162         }
11163       if (c == NULL)
11164         {
11165           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11166           OMP_CLAUSE_DECL (c) = decl;
11167           c = finish_omp_clauses (c);
11168           if (c)
11169             {
11170               OMP_CLAUSE_CHAIN (c) = *clauses;
11171               *clauses = c;
11172             }
11173         }
11174     }
11175   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11176   if (COMPARISON_CLASS_P (cond))
11177     cond = build2 (TREE_CODE (cond), boolean_type_node,
11178                    RECUR (TREE_OPERAND (cond, 0)),
11179                    RECUR (TREE_OPERAND (cond, 1)));
11180   else
11181     cond = RECUR (cond);
11182   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11183   switch (TREE_CODE (incr))
11184     {
11185     case PREINCREMENT_EXPR:
11186     case PREDECREMENT_EXPR:
11187     case POSTINCREMENT_EXPR:
11188     case POSTDECREMENT_EXPR:
11189       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11190                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11191       break;
11192     case MODIFY_EXPR:
11193       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11194           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11195         {
11196           tree rhs = TREE_OPERAND (incr, 1);
11197           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11198                          RECUR (TREE_OPERAND (incr, 0)),
11199                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11200                                  RECUR (TREE_OPERAND (rhs, 0)),
11201                                  RECUR (TREE_OPERAND (rhs, 1))));
11202         }
11203       else
11204         incr = RECUR (incr);
11205       break;
11206     case MODOP_EXPR:
11207       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11208           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11209         {
11210           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11211           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11212                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11213                                  TREE_TYPE (decl), lhs,
11214                                  RECUR (TREE_OPERAND (incr, 2))));
11215         }
11216       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11217                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11218                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11219         {
11220           tree rhs = TREE_OPERAND (incr, 2);
11221           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11222                          RECUR (TREE_OPERAND (incr, 0)),
11223                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11224                                  RECUR (TREE_OPERAND (rhs, 0)),
11225                                  RECUR (TREE_OPERAND (rhs, 1))));
11226         }
11227       else
11228         incr = RECUR (incr);
11229       break;
11230     default:
11231       incr = RECUR (incr);
11232       break;
11233     }
11234
11235   TREE_VEC_ELT (declv, i) = decl;
11236   TREE_VEC_ELT (initv, i) = init;
11237   TREE_VEC_ELT (condv, i) = cond;
11238   TREE_VEC_ELT (incrv, i) = incr;
11239 #undef RECUR
11240 }
11241
11242 /* Like tsubst_copy for expressions, etc. but also does semantic
11243    processing.  */
11244
11245 static tree
11246 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11247              bool integral_constant_expression_p)
11248 {
11249 #define RECUR(NODE)                             \
11250   tsubst_expr ((NODE), args, complain, in_decl, \
11251                integral_constant_expression_p)
11252
11253   tree stmt, tmp;
11254
11255   if (t == NULL_TREE || t == error_mark_node)
11256     return t;
11257
11258   if (EXPR_HAS_LOCATION (t))
11259     input_location = EXPR_LOCATION (t);
11260   if (STATEMENT_CODE_P (TREE_CODE (t)))
11261     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11262
11263   switch (TREE_CODE (t))
11264     {
11265     case STATEMENT_LIST:
11266       {
11267         tree_stmt_iterator i;
11268         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11269           RECUR (tsi_stmt (i));
11270         break;
11271       }
11272
11273     case CTOR_INITIALIZER:
11274       finish_mem_initializers (tsubst_initializer_list
11275                                (TREE_OPERAND (t, 0), args));
11276       break;
11277
11278     case RETURN_EXPR:
11279       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11280       break;
11281
11282     case EXPR_STMT:
11283       tmp = RECUR (EXPR_STMT_EXPR (t));
11284       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11285         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11286       else
11287         finish_expr_stmt (tmp);
11288       break;
11289
11290     case USING_STMT:
11291       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11292       break;
11293
11294     case DECL_EXPR:
11295       {
11296         tree decl;
11297         tree init;
11298
11299         decl = DECL_EXPR_DECL (t);
11300         if (TREE_CODE (decl) == LABEL_DECL)
11301           finish_label_decl (DECL_NAME (decl));
11302         else if (TREE_CODE (decl) == USING_DECL)
11303           {
11304             tree scope = USING_DECL_SCOPE (decl);
11305             tree name = DECL_NAME (decl);
11306             tree decl;
11307
11308             scope = RECUR (scope);
11309             decl = lookup_qualified_name (scope, name,
11310                                           /*is_type_p=*/false,
11311                                           /*complain=*/false);
11312             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11313               qualified_name_lookup_error (scope, name, decl, input_location);
11314             else
11315               do_local_using_decl (decl, scope, name);
11316           }
11317         else
11318           {
11319             init = DECL_INITIAL (decl);
11320             decl = tsubst (decl, args, complain, in_decl);
11321             if (decl != error_mark_node)
11322               {
11323                 /* By marking the declaration as instantiated, we avoid
11324                    trying to instantiate it.  Since instantiate_decl can't
11325                    handle local variables, and since we've already done
11326                    all that needs to be done, that's the right thing to
11327                    do.  */
11328                 if (TREE_CODE (decl) == VAR_DECL)
11329                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11330                 if (TREE_CODE (decl) == VAR_DECL
11331                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11332                   /* Anonymous aggregates are a special case.  */
11333                   finish_anon_union (decl);
11334                 else
11335                   {
11336                     maybe_push_decl (decl);
11337                     if (TREE_CODE (decl) == VAR_DECL
11338                         && DECL_PRETTY_FUNCTION_P (decl))
11339                       {
11340                         /* For __PRETTY_FUNCTION__ we have to adjust the
11341                            initializer.  */
11342                         const char *const name
11343                           = cxx_printable_name (current_function_decl, 2);
11344                         init = cp_fname_init (name, &TREE_TYPE (decl));
11345                       }
11346                     else
11347                       {
11348                         tree t = RECUR (init);
11349
11350                         if (init && !t)
11351                           /* If we had an initializer but it
11352                              instantiated to nothing,
11353                              value-initialize the object.  This will
11354                              only occur when the initializer was a
11355                              pack expansion where the parameter packs
11356                              used in that expansion were of length
11357                              zero.  */
11358                           init = build_value_init (TREE_TYPE (decl));
11359                         else
11360                           init = t;
11361                       }
11362
11363                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11364                   }
11365               }
11366           }
11367
11368         /* A DECL_EXPR can also be used as an expression, in the condition
11369            clause of an if/for/while construct.  */
11370         return decl;
11371       }
11372
11373     case FOR_STMT:
11374       stmt = begin_for_stmt ();
11375                           RECUR (FOR_INIT_STMT (t));
11376       finish_for_init_stmt (stmt);
11377       tmp = RECUR (FOR_COND (t));
11378       finish_for_cond (tmp, stmt);
11379       tmp = RECUR (FOR_EXPR (t));
11380       finish_for_expr (tmp, stmt);
11381       RECUR (FOR_BODY (t));
11382       finish_for_stmt (stmt);
11383       break;
11384
11385     case WHILE_STMT:
11386       stmt = begin_while_stmt ();
11387       tmp = RECUR (WHILE_COND (t));
11388       finish_while_stmt_cond (tmp, stmt);
11389       RECUR (WHILE_BODY (t));
11390       finish_while_stmt (stmt);
11391       break;
11392
11393     case DO_STMT:
11394       stmt = begin_do_stmt ();
11395       RECUR (DO_BODY (t));
11396       finish_do_body (stmt);
11397       tmp = RECUR (DO_COND (t));
11398       finish_do_stmt (tmp, stmt);
11399       break;
11400
11401     case IF_STMT:
11402       stmt = begin_if_stmt ();
11403       tmp = RECUR (IF_COND (t));
11404       finish_if_stmt_cond (tmp, stmt);
11405       RECUR (THEN_CLAUSE (t));
11406       finish_then_clause (stmt);
11407
11408       if (ELSE_CLAUSE (t))
11409         {
11410           begin_else_clause (stmt);
11411           RECUR (ELSE_CLAUSE (t));
11412           finish_else_clause (stmt);
11413         }
11414
11415       finish_if_stmt (stmt);
11416       break;
11417
11418     case BIND_EXPR:
11419       if (BIND_EXPR_BODY_BLOCK (t))
11420         stmt = begin_function_body ();
11421       else
11422         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11423                                     ? BCS_TRY_BLOCK : 0);
11424
11425       RECUR (BIND_EXPR_BODY (t));
11426
11427       if (BIND_EXPR_BODY_BLOCK (t))
11428         finish_function_body (stmt);
11429       else
11430         finish_compound_stmt (stmt);
11431       break;
11432
11433     case BREAK_STMT:
11434       finish_break_stmt ();
11435       break;
11436
11437     case CONTINUE_STMT:
11438       finish_continue_stmt ();
11439       break;
11440
11441     case SWITCH_STMT:
11442       stmt = begin_switch_stmt ();
11443       tmp = RECUR (SWITCH_STMT_COND (t));
11444       finish_switch_cond (tmp, stmt);
11445       RECUR (SWITCH_STMT_BODY (t));
11446       finish_switch_stmt (stmt);
11447       break;
11448
11449     case CASE_LABEL_EXPR:
11450       finish_case_label (EXPR_LOCATION (t),
11451                          RECUR (CASE_LOW (t)),
11452                          RECUR (CASE_HIGH (t)));
11453       break;
11454
11455     case LABEL_EXPR:
11456       {
11457         tree decl = LABEL_EXPR_LABEL (t);
11458         tree label;
11459
11460         label = finish_label_stmt (DECL_NAME (decl));
11461         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11462           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11463       }
11464       break;
11465
11466     case GOTO_EXPR:
11467       tmp = GOTO_DESTINATION (t);
11468       if (TREE_CODE (tmp) != LABEL_DECL)
11469         /* Computed goto's must be tsubst'd into.  On the other hand,
11470            non-computed gotos must not be; the identifier in question
11471            will have no binding.  */
11472         tmp = RECUR (tmp);
11473       else
11474         tmp = DECL_NAME (tmp);
11475       finish_goto_stmt (tmp);
11476       break;
11477
11478     case ASM_EXPR:
11479       tmp = finish_asm_stmt
11480         (ASM_VOLATILE_P (t),
11481          RECUR (ASM_STRING (t)),
11482          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11483          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11484          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11485          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11486       {
11487         tree asm_expr = tmp;
11488         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11489           asm_expr = TREE_OPERAND (asm_expr, 0);
11490         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11491       }
11492       break;
11493
11494     case TRY_BLOCK:
11495       if (CLEANUP_P (t))
11496         {
11497           stmt = begin_try_block ();
11498           RECUR (TRY_STMTS (t));
11499           finish_cleanup_try_block (stmt);
11500           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11501         }
11502       else
11503         {
11504           tree compound_stmt = NULL_TREE;
11505
11506           if (FN_TRY_BLOCK_P (t))
11507             stmt = begin_function_try_block (&compound_stmt);
11508           else
11509             stmt = begin_try_block ();
11510
11511           RECUR (TRY_STMTS (t));
11512
11513           if (FN_TRY_BLOCK_P (t))
11514             finish_function_try_block (stmt);
11515           else
11516             finish_try_block (stmt);
11517
11518           RECUR (TRY_HANDLERS (t));
11519           if (FN_TRY_BLOCK_P (t))
11520             finish_function_handler_sequence (stmt, compound_stmt);
11521           else
11522             finish_handler_sequence (stmt);
11523         }
11524       break;
11525
11526     case HANDLER:
11527       {
11528         tree decl = HANDLER_PARMS (t);
11529
11530         if (decl)
11531           {
11532             decl = tsubst (decl, args, complain, in_decl);
11533             /* Prevent instantiate_decl from trying to instantiate
11534                this variable.  We've already done all that needs to be
11535                done.  */
11536             if (decl != error_mark_node)
11537               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11538           }
11539         stmt = begin_handler ();
11540         finish_handler_parms (decl, stmt);
11541         RECUR (HANDLER_BODY (t));
11542         finish_handler (stmt);
11543       }
11544       break;
11545
11546     case TAG_DEFN:
11547       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11548       break;
11549
11550     case STATIC_ASSERT:
11551       {
11552         tree condition = 
11553           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11554                        args,
11555                        complain, in_decl,
11556                        /*integral_constant_expression_p=*/true);
11557         finish_static_assert (condition,
11558                               STATIC_ASSERT_MESSAGE (t),
11559                               STATIC_ASSERT_SOURCE_LOCATION (t),
11560                               /*member_p=*/false);
11561       }
11562       break;
11563
11564     case OMP_PARALLEL:
11565       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11566                                 args, complain, in_decl);
11567       stmt = begin_omp_parallel ();
11568       RECUR (OMP_PARALLEL_BODY (t));
11569       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11570         = OMP_PARALLEL_COMBINED (t);
11571       break;
11572
11573     case OMP_TASK:
11574       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11575                                 args, complain, in_decl);
11576       stmt = begin_omp_task ();
11577       RECUR (OMP_TASK_BODY (t));
11578       finish_omp_task (tmp, stmt);
11579       break;
11580
11581     case OMP_FOR:
11582       {
11583         tree clauses, body, pre_body;
11584         tree declv, initv, condv, incrv;
11585         int i;
11586
11587         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11588                                       args, complain, in_decl);
11589         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11590         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11591         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11592         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11593
11594         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11595           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11596                                    &clauses, args, complain, in_decl,
11597                                    integral_constant_expression_p);
11598
11599         stmt = begin_omp_structured_block ();
11600
11601         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11602           if (TREE_VEC_ELT (initv, i) == NULL
11603               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11604             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11605           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11606             {
11607               tree init = RECUR (TREE_VEC_ELT (initv, i));
11608               gcc_assert (init == TREE_VEC_ELT (declv, i));
11609               TREE_VEC_ELT (initv, i) = NULL_TREE;
11610             }
11611           else
11612             {
11613               tree decl_expr = TREE_VEC_ELT (initv, i);
11614               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11615               gcc_assert (init != NULL);
11616               TREE_VEC_ELT (initv, i) = RECUR (init);
11617               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11618               RECUR (decl_expr);
11619               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11620             }
11621
11622         pre_body = push_stmt_list ();
11623         RECUR (OMP_FOR_PRE_BODY (t));
11624         pre_body = pop_stmt_list (pre_body);
11625
11626         body = push_stmt_list ();
11627         RECUR (OMP_FOR_BODY (t));
11628         body = pop_stmt_list (body);
11629
11630         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11631                             body, pre_body, clauses);
11632
11633         add_stmt (finish_omp_structured_block (stmt));
11634       }
11635       break;
11636
11637     case OMP_SECTIONS:
11638     case OMP_SINGLE:
11639       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11640       stmt = push_stmt_list ();
11641       RECUR (OMP_BODY (t));
11642       stmt = pop_stmt_list (stmt);
11643
11644       t = copy_node (t);
11645       OMP_BODY (t) = stmt;
11646       OMP_CLAUSES (t) = tmp;
11647       add_stmt (t);
11648       break;
11649
11650     case OMP_SECTION:
11651     case OMP_CRITICAL:
11652     case OMP_MASTER:
11653     case OMP_ORDERED:
11654       stmt = push_stmt_list ();
11655       RECUR (OMP_BODY (t));
11656       stmt = pop_stmt_list (stmt);
11657
11658       t = copy_node (t);
11659       OMP_BODY (t) = stmt;
11660       add_stmt (t);
11661       break;
11662
11663     case OMP_ATOMIC:
11664       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11665       {
11666         tree op1 = TREE_OPERAND (t, 1);
11667         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11668         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11669         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11670       }
11671       break;
11672
11673     case EXPR_PACK_EXPANSION:
11674       error ("invalid use of pack expansion expression");
11675       return error_mark_node;
11676
11677     case NONTYPE_ARGUMENT_PACK:
11678       error ("use %<...%> to expand argument pack");
11679       return error_mark_node;
11680
11681     default:
11682       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11683
11684       return tsubst_copy_and_build (t, args, complain, in_decl,
11685                                     /*function_p=*/false,
11686                                     integral_constant_expression_p);
11687     }
11688
11689   return NULL_TREE;
11690 #undef RECUR
11691 }
11692
11693 /* T is a postfix-expression that is not being used in a function
11694    call.  Return the substituted version of T.  */
11695
11696 static tree
11697 tsubst_non_call_postfix_expression (tree t, tree args,
11698                                     tsubst_flags_t complain,
11699                                     tree in_decl)
11700 {
11701   if (TREE_CODE (t) == SCOPE_REF)
11702     t = tsubst_qualified_id (t, args, complain, in_decl,
11703                              /*done=*/false, /*address_p=*/false);
11704   else
11705     t = tsubst_copy_and_build (t, args, complain, in_decl,
11706                                /*function_p=*/false,
11707                                /*integral_constant_expression_p=*/false);
11708
11709   return t;
11710 }
11711
11712 /* Like tsubst but deals with expressions and performs semantic
11713    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11714
11715 tree
11716 tsubst_copy_and_build (tree t,
11717                        tree args,
11718                        tsubst_flags_t complain,
11719                        tree in_decl,
11720                        bool function_p,
11721                        bool integral_constant_expression_p)
11722 {
11723 #define RECUR(NODE)                                             \
11724   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11725                          /*function_p=*/false,                  \
11726                          integral_constant_expression_p)
11727
11728   tree op1;
11729
11730   if (t == NULL_TREE || t == error_mark_node)
11731     return t;
11732
11733   switch (TREE_CODE (t))
11734     {
11735     case USING_DECL:
11736       t = DECL_NAME (t);
11737       /* Fall through.  */
11738     case IDENTIFIER_NODE:
11739       {
11740         tree decl;
11741         cp_id_kind idk;
11742         bool non_integral_constant_expression_p;
11743         const char *error_msg;
11744
11745         if (IDENTIFIER_TYPENAME_P (t))
11746           {
11747             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11748             t = mangle_conv_op_name_for_type (new_type);
11749           }
11750
11751         /* Look up the name.  */
11752         decl = lookup_name (t);
11753
11754         /* By convention, expressions use ERROR_MARK_NODE to indicate
11755            failure, not NULL_TREE.  */
11756         if (decl == NULL_TREE)
11757           decl = error_mark_node;
11758
11759         decl = finish_id_expression (t, decl, NULL_TREE,
11760                                      &idk,
11761                                      integral_constant_expression_p,
11762                                      /*allow_non_integral_constant_expression_p=*/false,
11763                                      &non_integral_constant_expression_p,
11764                                      /*template_p=*/false,
11765                                      /*done=*/true,
11766                                      /*address_p=*/false,
11767                                      /*template_arg_p=*/false,
11768                                      &error_msg,
11769                                      input_location);
11770         if (error_msg)
11771           error (error_msg);
11772         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11773           decl = unqualified_name_lookup_error (decl);
11774         return decl;
11775       }
11776
11777     case TEMPLATE_ID_EXPR:
11778       {
11779         tree object;
11780         tree templ = RECUR (TREE_OPERAND (t, 0));
11781         tree targs = TREE_OPERAND (t, 1);
11782
11783         if (targs)
11784           targs = tsubst_template_args (targs, args, complain, in_decl);
11785
11786         if (TREE_CODE (templ) == COMPONENT_REF)
11787           {
11788             object = TREE_OPERAND (templ, 0);
11789             templ = TREE_OPERAND (templ, 1);
11790           }
11791         else
11792           object = NULL_TREE;
11793         templ = lookup_template_function (templ, targs);
11794
11795         if (object)
11796           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11797                          object, templ, NULL_TREE);
11798         else
11799           return baselink_for_fns (templ);
11800       }
11801
11802     case INDIRECT_REF:
11803       {
11804         tree r = RECUR (TREE_OPERAND (t, 0));
11805
11806         if (REFERENCE_REF_P (t))
11807           {
11808             /* A type conversion to reference type will be enclosed in
11809                such an indirect ref, but the substitution of the cast
11810                will have also added such an indirect ref.  */
11811             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11812               r = convert_from_reference (r);
11813           }
11814         else
11815           r = build_x_indirect_ref (r, "unary *", complain);
11816         return r;
11817       }
11818
11819     case NOP_EXPR:
11820       return build_nop
11821         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11822          RECUR (TREE_OPERAND (t, 0)));
11823
11824     case CAST_EXPR:
11825     case REINTERPRET_CAST_EXPR:
11826     case CONST_CAST_EXPR:
11827     case DYNAMIC_CAST_EXPR:
11828     case STATIC_CAST_EXPR:
11829       {
11830         tree type;
11831         tree op;
11832
11833         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11834         if (integral_constant_expression_p
11835             && !cast_valid_in_integral_constant_expression_p (type))
11836           {
11837             if (complain & tf_error)
11838               error ("a cast to a type other than an integral or "
11839                      "enumeration type cannot appear in a constant-expression");
11840             return error_mark_node; 
11841           }
11842
11843         op = RECUR (TREE_OPERAND (t, 0));
11844
11845         switch (TREE_CODE (t))
11846           {
11847           case CAST_EXPR:
11848             return build_functional_cast (type, op, complain);
11849           case REINTERPRET_CAST_EXPR:
11850             return build_reinterpret_cast (type, op, complain);
11851           case CONST_CAST_EXPR:
11852             return build_const_cast (type, op, complain);
11853           case DYNAMIC_CAST_EXPR:
11854             return build_dynamic_cast (type, op, complain);
11855           case STATIC_CAST_EXPR:
11856             return build_static_cast (type, op, complain);
11857           default:
11858             gcc_unreachable ();
11859           }
11860       }
11861
11862     case POSTDECREMENT_EXPR:
11863     case POSTINCREMENT_EXPR:
11864       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11865                                                 args, complain, in_decl);
11866       return build_x_unary_op (TREE_CODE (t), op1, complain);
11867
11868     case PREDECREMENT_EXPR:
11869     case PREINCREMENT_EXPR:
11870     case NEGATE_EXPR:
11871     case BIT_NOT_EXPR:
11872     case ABS_EXPR:
11873     case TRUTH_NOT_EXPR:
11874     case UNARY_PLUS_EXPR:  /* Unary + */
11875     case REALPART_EXPR:
11876     case IMAGPART_EXPR:
11877       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11878                                complain);
11879
11880     case ADDR_EXPR:
11881       op1 = TREE_OPERAND (t, 0);
11882       if (TREE_CODE (op1) == SCOPE_REF)
11883         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11884                                    /*done=*/true, /*address_p=*/true);
11885       else
11886         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11887                                                   in_decl);
11888       if (TREE_CODE (op1) == LABEL_DECL)
11889         return finish_label_address_expr (DECL_NAME (op1),
11890                                           EXPR_LOCATION (op1));
11891       return build_x_unary_op (ADDR_EXPR, op1, complain);
11892
11893     case PLUS_EXPR:
11894     case MINUS_EXPR:
11895     case MULT_EXPR:
11896     case TRUNC_DIV_EXPR:
11897     case CEIL_DIV_EXPR:
11898     case FLOOR_DIV_EXPR:
11899     case ROUND_DIV_EXPR:
11900     case EXACT_DIV_EXPR:
11901     case BIT_AND_EXPR:
11902     case BIT_IOR_EXPR:
11903     case BIT_XOR_EXPR:
11904     case TRUNC_MOD_EXPR:
11905     case FLOOR_MOD_EXPR:
11906     case TRUTH_ANDIF_EXPR:
11907     case TRUTH_ORIF_EXPR:
11908     case TRUTH_AND_EXPR:
11909     case TRUTH_OR_EXPR:
11910     case RSHIFT_EXPR:
11911     case LSHIFT_EXPR:
11912     case RROTATE_EXPR:
11913     case LROTATE_EXPR:
11914     case EQ_EXPR:
11915     case NE_EXPR:
11916     case MAX_EXPR:
11917     case MIN_EXPR:
11918     case LE_EXPR:
11919     case GE_EXPR:
11920     case LT_EXPR:
11921     case GT_EXPR:
11922     case MEMBER_REF:
11923     case DOTSTAR_EXPR:
11924       return build_x_binary_op
11925         (TREE_CODE (t),
11926          RECUR (TREE_OPERAND (t, 0)),
11927          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11928           ? ERROR_MARK
11929           : TREE_CODE (TREE_OPERAND (t, 0))),
11930          RECUR (TREE_OPERAND (t, 1)),
11931          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11932           ? ERROR_MARK
11933           : TREE_CODE (TREE_OPERAND (t, 1))),
11934          /*overloaded_p=*/NULL,
11935          complain);
11936
11937     case SCOPE_REF:
11938       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11939                                   /*address_p=*/false);
11940     case ARRAY_REF:
11941       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11942                                                 args, complain, in_decl);
11943       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11944
11945     case SIZEOF_EXPR:
11946       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11947         return tsubst_copy (t, args, complain, in_decl);
11948       /* Fall through */
11949       
11950     case ALIGNOF_EXPR:
11951       op1 = TREE_OPERAND (t, 0);
11952       if (!args)
11953         {
11954           /* When there are no ARGS, we are trying to evaluate a
11955              non-dependent expression from the parser.  Trying to do
11956              the substitutions may not work.  */
11957           if (!TYPE_P (op1))
11958             op1 = TREE_TYPE (op1);
11959         }
11960       else
11961         {
11962           ++cp_unevaluated_operand;
11963           ++c_inhibit_evaluation_warnings;
11964           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11965                                        /*function_p=*/false,
11966                                        /*integral_constant_expression_p=*/false);
11967           --cp_unevaluated_operand;
11968           --c_inhibit_evaluation_warnings;
11969         }
11970       if (TYPE_P (op1))
11971         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11972                                            complain & tf_error);
11973       else
11974         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11975                                            complain & tf_error);
11976
11977     case MODOP_EXPR:
11978       {
11979         tree r = build_x_modify_expr
11980           (RECUR (TREE_OPERAND (t, 0)),
11981            TREE_CODE (TREE_OPERAND (t, 1)),
11982            RECUR (TREE_OPERAND (t, 2)),
11983            complain);
11984         /* TREE_NO_WARNING must be set if either the expression was
11985            parenthesized or it uses an operator such as >>= rather
11986            than plain assignment.  In the former case, it was already
11987            set and must be copied.  In the latter case,
11988            build_x_modify_expr sets it and it must not be reset
11989            here.  */
11990         if (TREE_NO_WARNING (t))
11991           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11992         return r;
11993       }
11994
11995     case ARROW_EXPR:
11996       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11997                                                 args, complain, in_decl);
11998       /* Remember that there was a reference to this entity.  */
11999       if (DECL_P (op1))
12000         mark_used (op1);
12001       return build_x_arrow (op1);
12002
12003     case NEW_EXPR:
12004       {
12005         tree placement = RECUR (TREE_OPERAND (t, 0));
12006         tree init = RECUR (TREE_OPERAND (t, 3));
12007         VEC(tree,gc) *placement_vec;
12008         VEC(tree,gc) *init_vec;
12009         tree ret;
12010
12011         if (placement == NULL_TREE)
12012           placement_vec = NULL;
12013         else
12014           {
12015             placement_vec = make_tree_vector ();
12016             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12017               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12018           }
12019
12020         /* If there was an initializer in the original tree, but it
12021            instantiated to an empty list, then we should pass a
12022            non-NULL empty vector to tell build_new that it was an
12023            empty initializer() rather than no initializer.  This can
12024            only happen when the initializer is a pack expansion whose
12025            parameter packs are of length zero.  */
12026         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12027           init_vec = NULL;
12028         else
12029           {
12030             init_vec = make_tree_vector ();
12031             if (init == void_zero_node)
12032               gcc_assert (init_vec != NULL);
12033             else
12034               {
12035                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12036                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12037               }
12038           }
12039
12040         ret = build_new (&placement_vec,
12041                          RECUR (TREE_OPERAND (t, 1)),
12042                          RECUR (TREE_OPERAND (t, 2)),
12043                          &init_vec,
12044                          NEW_EXPR_USE_GLOBAL (t),
12045                          complain);
12046
12047         if (placement_vec != NULL)
12048           release_tree_vector (placement_vec);
12049         if (init_vec != NULL)
12050           release_tree_vector (init_vec);
12051
12052         return ret;
12053       }
12054
12055     case DELETE_EXPR:
12056      return delete_sanity
12057        (RECUR (TREE_OPERAND (t, 0)),
12058         RECUR (TREE_OPERAND (t, 1)),
12059         DELETE_EXPR_USE_VEC (t),
12060         DELETE_EXPR_USE_GLOBAL (t));
12061
12062     case COMPOUND_EXPR:
12063       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12064                                     RECUR (TREE_OPERAND (t, 1)),
12065                                     complain);
12066
12067     case CALL_EXPR:
12068       {
12069         tree function;
12070         VEC(tree,gc) *call_args;
12071         unsigned int nargs, i;
12072         bool qualified_p;
12073         bool koenig_p;
12074         tree ret;
12075
12076         function = CALL_EXPR_FN (t);
12077         /* When we parsed the expression,  we determined whether or
12078            not Koenig lookup should be performed.  */
12079         koenig_p = KOENIG_LOOKUP_P (t);
12080         if (TREE_CODE (function) == SCOPE_REF)
12081           {
12082             qualified_p = true;
12083             function = tsubst_qualified_id (function, args, complain, in_decl,
12084                                             /*done=*/false,
12085                                             /*address_p=*/false);
12086           }
12087         else
12088           {
12089             if (TREE_CODE (function) == COMPONENT_REF)
12090               {
12091                 tree op = TREE_OPERAND (function, 1);
12092
12093                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12094                                || (BASELINK_P (op)
12095                                    && BASELINK_QUALIFIED_P (op)));
12096               }
12097             else
12098               qualified_p = false;
12099
12100             function = tsubst_copy_and_build (function, args, complain,
12101                                               in_decl,
12102                                               !qualified_p,
12103                                               integral_constant_expression_p);
12104
12105             if (BASELINK_P (function))
12106               qualified_p = true;
12107           }
12108
12109         nargs = call_expr_nargs (t);
12110         call_args = make_tree_vector ();
12111         for (i = 0; i < nargs; ++i)
12112           {
12113             tree arg = CALL_EXPR_ARG (t, i);
12114
12115             if (!PACK_EXPANSION_P (arg))
12116               VEC_safe_push (tree, gc, call_args,
12117                              RECUR (CALL_EXPR_ARG (t, i)));
12118             else
12119               {
12120                 /* Expand the pack expansion and push each entry onto
12121                    CALL_ARGS.  */
12122                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12123                 if (TREE_CODE (arg) == TREE_VEC)
12124                   {
12125                     unsigned int len, j;
12126
12127                     len = TREE_VEC_LENGTH (arg);
12128                     for (j = 0; j < len; ++j)
12129                       {
12130                         tree value = TREE_VEC_ELT (arg, j);
12131                         if (value != NULL_TREE)
12132                           value = convert_from_reference (value);
12133                         VEC_safe_push (tree, gc, call_args, value);
12134                       }
12135                   }
12136                 else
12137                   {
12138                     /* A partial substitution.  Add one entry.  */
12139                     VEC_safe_push (tree, gc, call_args, arg);
12140                   }
12141               }
12142           }
12143
12144         /* We do not perform argument-dependent lookup if normal
12145            lookup finds a non-function, in accordance with the
12146            expected resolution of DR 218.  */
12147         if (koenig_p
12148             && ((is_overloaded_fn (function)
12149                  /* If lookup found a member function, the Koenig lookup is
12150                     not appropriate, even if an unqualified-name was used
12151                     to denote the function.  */
12152                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12153                 || TREE_CODE (function) == IDENTIFIER_NODE)
12154             /* Only do this when substitution turns a dependent call
12155                into a non-dependent call.  */
12156             && type_dependent_expression_p_push (t)
12157             && !any_type_dependent_arguments_p (call_args))
12158           function = perform_koenig_lookup (function, call_args);
12159
12160         if (TREE_CODE (function) == IDENTIFIER_NODE)
12161           {
12162             unqualified_name_lookup_error (function);
12163             release_tree_vector (call_args);
12164             return error_mark_node;
12165           }
12166
12167         /* Remember that there was a reference to this entity.  */
12168         if (DECL_P (function))
12169           mark_used (function);
12170
12171         if (TREE_CODE (function) == OFFSET_REF)
12172           ret = build_offset_ref_call_from_tree (function, &call_args);
12173         else if (TREE_CODE (function) == COMPONENT_REF)
12174           {
12175             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12176               ret = finish_call_expr (function, &call_args,
12177                                        /*disallow_virtual=*/false,
12178                                        /*koenig_p=*/false,
12179                                        complain);
12180             else
12181               ret = (build_new_method_call
12182                       (TREE_OPERAND (function, 0),
12183                        TREE_OPERAND (function, 1),
12184                        &call_args, NULL_TREE,
12185                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12186                        /*fn_p=*/NULL,
12187                        complain));
12188           }
12189         else
12190           ret = finish_call_expr (function, &call_args,
12191                                   /*disallow_virtual=*/qualified_p,
12192                                   koenig_p,
12193                                   complain);
12194
12195         release_tree_vector (call_args);
12196
12197         return ret;
12198       }
12199
12200     case COND_EXPR:
12201       return build_x_conditional_expr
12202         (RECUR (TREE_OPERAND (t, 0)),
12203          RECUR (TREE_OPERAND (t, 1)),
12204          RECUR (TREE_OPERAND (t, 2)),
12205          complain);
12206
12207     case PSEUDO_DTOR_EXPR:
12208       return finish_pseudo_destructor_expr
12209         (RECUR (TREE_OPERAND (t, 0)),
12210          RECUR (TREE_OPERAND (t, 1)),
12211          RECUR (TREE_OPERAND (t, 2)));
12212
12213     case TREE_LIST:
12214       {
12215         tree purpose, value, chain;
12216
12217         if (t == void_list_node)
12218           return t;
12219
12220         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12221             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12222           {
12223             /* We have pack expansions, so expand those and
12224                create a new list out of it.  */
12225             tree purposevec = NULL_TREE;
12226             tree valuevec = NULL_TREE;
12227             tree chain;
12228             int i, len = -1;
12229
12230             /* Expand the argument expressions.  */
12231             if (TREE_PURPOSE (t))
12232               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12233                                                  complain, in_decl);
12234             if (TREE_VALUE (t))
12235               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12236                                                complain, in_decl);
12237
12238             /* Build the rest of the list.  */
12239             chain = TREE_CHAIN (t);
12240             if (chain && chain != void_type_node)
12241               chain = RECUR (chain);
12242
12243             /* Determine the number of arguments.  */
12244             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12245               {
12246                 len = TREE_VEC_LENGTH (purposevec);
12247                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12248               }
12249             else if (TREE_CODE (valuevec) == TREE_VEC)
12250               len = TREE_VEC_LENGTH (valuevec);
12251             else
12252               {
12253                 /* Since we only performed a partial substitution into
12254                    the argument pack, we only return a single list
12255                    node.  */
12256                 if (purposevec == TREE_PURPOSE (t)
12257                     && valuevec == TREE_VALUE (t)
12258                     && chain == TREE_CHAIN (t))
12259                   return t;
12260
12261                 return tree_cons (purposevec, valuevec, chain);
12262               }
12263             
12264             /* Convert the argument vectors into a TREE_LIST */
12265             i = len;
12266             while (i > 0)
12267               {
12268                 /* Grab the Ith values.  */
12269                 i--;
12270                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12271                                      : NULL_TREE;
12272                 value 
12273                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12274                              : NULL_TREE;
12275
12276                 /* Build the list (backwards).  */
12277                 chain = tree_cons (purpose, value, chain);
12278               }
12279
12280             return chain;
12281           }
12282
12283         purpose = TREE_PURPOSE (t);
12284         if (purpose)
12285           purpose = RECUR (purpose);
12286         value = TREE_VALUE (t);
12287         if (value)
12288           value = RECUR (value);
12289         chain = TREE_CHAIN (t);
12290         if (chain && chain != void_type_node)
12291           chain = RECUR (chain);
12292         if (purpose == TREE_PURPOSE (t)
12293             && value == TREE_VALUE (t)
12294             && chain == TREE_CHAIN (t))
12295           return t;
12296         return tree_cons (purpose, value, chain);
12297       }
12298
12299     case COMPONENT_REF:
12300       {
12301         tree object;
12302         tree object_type;
12303         tree member;
12304
12305         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12306                                                      args, complain, in_decl);
12307         /* Remember that there was a reference to this entity.  */
12308         if (DECL_P (object))
12309           mark_used (object);
12310         object_type = TREE_TYPE (object);
12311
12312         member = TREE_OPERAND (t, 1);
12313         if (BASELINK_P (member))
12314           member = tsubst_baselink (member,
12315                                     non_reference (TREE_TYPE (object)),
12316                                     args, complain, in_decl);
12317         else
12318           member = tsubst_copy (member, args, complain, in_decl);
12319         if (member == error_mark_node)
12320           return error_mark_node;
12321
12322         if (object_type && !CLASS_TYPE_P (object_type))
12323           {
12324             if (SCALAR_TYPE_P (object_type))
12325               {
12326                 tree s = NULL_TREE;
12327                 tree dtor = member;
12328
12329                 if (TREE_CODE (dtor) == SCOPE_REF)
12330                   {
12331                     s = TREE_OPERAND (dtor, 0);
12332                     dtor = TREE_OPERAND (dtor, 1);
12333                   }
12334                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12335                   {
12336                     dtor = TREE_OPERAND (dtor, 0);
12337                     if (TYPE_P (dtor))
12338                       return finish_pseudo_destructor_expr (object, s, dtor);
12339                   }
12340               }
12341           }
12342         else if (TREE_CODE (member) == SCOPE_REF
12343                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12344           {
12345             tree tmpl;
12346             tree args;
12347
12348             /* Lookup the template functions now that we know what the
12349                scope is.  */
12350             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12351             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12352             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12353                                             /*is_type_p=*/false,
12354                                             /*complain=*/false);
12355             if (BASELINK_P (member))
12356               {
12357                 BASELINK_FUNCTIONS (member)
12358                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12359                               args);
12360                 member = (adjust_result_of_qualified_name_lookup
12361                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12362                            object_type));
12363               }
12364             else
12365               {
12366                 qualified_name_lookup_error (object_type, tmpl, member,
12367                                              input_location);
12368                 return error_mark_node;
12369               }
12370           }
12371         else if (TREE_CODE (member) == SCOPE_REF
12372                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12373                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12374           {
12375             if (complain & tf_error)
12376               {
12377                 if (TYPE_P (TREE_OPERAND (member, 0)))
12378                   error ("%qT is not a class or namespace",
12379                          TREE_OPERAND (member, 0));
12380                 else
12381                   error ("%qD is not a class or namespace",
12382                          TREE_OPERAND (member, 0));
12383               }
12384             return error_mark_node;
12385           }
12386         else if (TREE_CODE (member) == FIELD_DECL)
12387           return finish_non_static_data_member (member, object, NULL_TREE);
12388
12389         return finish_class_member_access_expr (object, member,
12390                                                 /*template_p=*/false,
12391                                                 complain);
12392       }
12393
12394     case THROW_EXPR:
12395       return build_throw
12396         (RECUR (TREE_OPERAND (t, 0)));
12397
12398     case CONSTRUCTOR:
12399       {
12400         VEC(constructor_elt,gc) *n;
12401         constructor_elt *ce;
12402         unsigned HOST_WIDE_INT idx;
12403         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12404         bool process_index_p;
12405         int newlen;
12406         bool need_copy_p = false;
12407         tree r;
12408
12409         if (type == error_mark_node)
12410           return error_mark_node;
12411
12412         /* digest_init will do the wrong thing if we let it.  */
12413         if (type && TYPE_PTRMEMFUNC_P (type))
12414           return t;
12415
12416         /* We do not want to process the index of aggregate
12417            initializers as they are identifier nodes which will be
12418            looked up by digest_init.  */
12419         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12420
12421         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12422         newlen = VEC_length (constructor_elt, n);
12423         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12424           {
12425             if (ce->index && process_index_p)
12426               ce->index = RECUR (ce->index);
12427
12428             if (PACK_EXPANSION_P (ce->value))
12429               {
12430                 /* Substitute into the pack expansion.  */
12431                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12432                                                   in_decl);
12433
12434                 if (ce->value == error_mark_node)
12435                   ;
12436                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12437                   /* Just move the argument into place.  */
12438                   ce->value = TREE_VEC_ELT (ce->value, 0);
12439                 else
12440                   {
12441                     /* Update the length of the final CONSTRUCTOR
12442                        arguments vector, and note that we will need to
12443                        copy.*/
12444                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12445                     need_copy_p = true;
12446                   }
12447               }
12448             else
12449               ce->value = RECUR (ce->value);
12450           }
12451
12452         if (need_copy_p)
12453           {
12454             VEC(constructor_elt,gc) *old_n = n;
12455
12456             n = VEC_alloc (constructor_elt, gc, newlen);
12457             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12458                  idx++)
12459               {
12460                 if (TREE_CODE (ce->value) == TREE_VEC)
12461                   {
12462                     int i, len = TREE_VEC_LENGTH (ce->value);
12463                     for (i = 0; i < len; ++i)
12464                       CONSTRUCTOR_APPEND_ELT (n, 0,
12465                                               TREE_VEC_ELT (ce->value, i));
12466                   }
12467                 else
12468                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12469               }
12470           }
12471
12472         r = build_constructor (init_list_type_node, n);
12473         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12474
12475         if (TREE_HAS_CONSTRUCTOR (t))
12476           return finish_compound_literal (type, r);
12477
12478         return r;
12479       }
12480
12481     case TYPEID_EXPR:
12482       {
12483         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12484         if (TYPE_P (operand_0))
12485           return get_typeid (operand_0);
12486         return build_typeid (operand_0);
12487       }
12488
12489     case VAR_DECL:
12490       if (!args)
12491         return t;
12492       /* Fall through */
12493
12494     case PARM_DECL:
12495       {
12496         tree r = tsubst_copy (t, args, complain, in_decl);
12497
12498         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12499           /* If the original type was a reference, we'll be wrapped in
12500              the appropriate INDIRECT_REF.  */
12501           r = convert_from_reference (r);
12502         return r;
12503       }
12504
12505     case VA_ARG_EXPR:
12506       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12507                              tsubst_copy (TREE_TYPE (t), args, complain,
12508                                           in_decl));
12509
12510     case OFFSETOF_EXPR:
12511       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12512
12513     case TRAIT_EXPR:
12514       {
12515         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12516                                   complain, in_decl);
12517
12518         tree type2 = TRAIT_EXPR_TYPE2 (t);
12519         if (type2)
12520           type2 = tsubst_copy (type2, args, complain, in_decl);
12521         
12522         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12523       }
12524
12525     case STMT_EXPR:
12526       {
12527         tree old_stmt_expr = cur_stmt_expr;
12528         tree stmt_expr = begin_stmt_expr ();
12529
12530         cur_stmt_expr = stmt_expr;
12531         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12532                      integral_constant_expression_p);
12533         stmt_expr = finish_stmt_expr (stmt_expr, false);
12534         cur_stmt_expr = old_stmt_expr;
12535
12536         return stmt_expr;
12537       }
12538
12539     case CONST_DECL:
12540       t = tsubst_copy (t, args, complain, in_decl);
12541       /* As in finish_id_expression, we resolve enumeration constants
12542          to their underlying values.  */
12543       if (TREE_CODE (t) == CONST_DECL)
12544         {
12545           used_types_insert (TREE_TYPE (t));
12546           return DECL_INITIAL (t);
12547         }
12548       return t;
12549
12550     case LAMBDA_EXPR:
12551       {
12552         tree r = build_lambda_expr ();
12553
12554         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12555         TREE_TYPE (r) = type;
12556         CLASSTYPE_LAMBDA_EXPR (type) = r;
12557
12558         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12559           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12560         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12561         LAMBDA_EXPR_DISCRIMINATOR (r)
12562           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12563         LAMBDA_EXPR_CAPTURE_LIST (r)
12564           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12565         LAMBDA_EXPR_THIS_CAPTURE (r)
12566           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12567         LAMBDA_EXPR_EXTRA_SCOPE (r)
12568           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12569
12570         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12571         determine_visibility (TYPE_NAME (type));
12572         /* Now that we know visibility, instantiate the type so we have a
12573            declaration of the op() for later calls to lambda_function.  */
12574         complete_type (type);
12575
12576         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12577         if (type)
12578           apply_lambda_return_type (r, type);
12579
12580         return build_lambda_object (r);
12581       }
12582
12583     default:
12584       /* Handle Objective-C++ constructs, if appropriate.  */
12585       {
12586         tree subst
12587           = objcp_tsubst_copy_and_build (t, args, complain,
12588                                          in_decl, /*function_p=*/false);
12589         if (subst)
12590           return subst;
12591       }
12592       return tsubst_copy (t, args, complain, in_decl);
12593     }
12594
12595 #undef RECUR
12596 }
12597
12598 /* Verify that the instantiated ARGS are valid. For type arguments,
12599    make sure that the type's linkage is ok. For non-type arguments,
12600    make sure they are constants if they are integral or enumerations.
12601    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12602
12603 static bool
12604 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12605 {
12606   if (ARGUMENT_PACK_P (t))
12607     {
12608       tree vec = ARGUMENT_PACK_ARGS (t);
12609       int len = TREE_VEC_LENGTH (vec);
12610       bool result = false;
12611       int i;
12612
12613       for (i = 0; i < len; ++i)
12614         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12615           result = true;
12616       return result;
12617     }
12618   else if (TYPE_P (t))
12619     {
12620       /* [basic.link]: A name with no linkage (notably, the name
12621          of a class or enumeration declared in a local scope)
12622          shall not be used to declare an entity with linkage.
12623          This implies that names with no linkage cannot be used as
12624          template arguments
12625
12626          DR 757 relaxes this restriction for C++0x.  */
12627       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12628                  : no_linkage_check (t, /*relaxed_p=*/false));
12629
12630       if (nt)
12631         {
12632           /* DR 488 makes use of a type with no linkage cause
12633              type deduction to fail.  */
12634           if (complain & tf_error)
12635             {
12636               if (TYPE_ANONYMOUS_P (nt))
12637                 error ("%qT is/uses anonymous type", t);
12638               else
12639                 error ("template argument for %qD uses local type %qT",
12640                        tmpl, t);
12641             }
12642           return true;
12643         }
12644       /* In order to avoid all sorts of complications, we do not
12645          allow variably-modified types as template arguments.  */
12646       else if (variably_modified_type_p (t, NULL_TREE))
12647         {
12648           if (complain & tf_error)
12649             error ("%qT is a variably modified type", t);
12650           return true;
12651         }
12652     }
12653   /* A non-type argument of integral or enumerated type must be a
12654      constant.  */
12655   else if (TREE_TYPE (t)
12656            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12657            && !TREE_CONSTANT (t))
12658     {
12659       if (complain & tf_error)
12660         error ("integral expression %qE is not constant", t);
12661       return true;
12662     }
12663   return false;
12664 }
12665
12666 static bool
12667 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12668 {
12669   int ix, len = DECL_NTPARMS (tmpl);
12670   bool result = false;
12671
12672   for (ix = 0; ix != len; ix++)
12673     {
12674       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12675         result = true;
12676     }
12677   if (result && (complain & tf_error))
12678     error ("  trying to instantiate %qD", tmpl);
12679   return result;
12680 }
12681
12682 /* Instantiate the indicated variable or function template TMPL with
12683    the template arguments in TARG_PTR.  */
12684
12685 tree
12686 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12687 {
12688   tree targ_ptr = orig_args;
12689   tree fndecl;
12690   tree gen_tmpl;
12691   tree spec;
12692   HOST_WIDE_INT saved_processing_template_decl;
12693
12694   if (tmpl == error_mark_node)
12695     return error_mark_node;
12696
12697   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12698
12699   /* If this function is a clone, handle it specially.  */
12700   if (DECL_CLONED_FUNCTION_P (tmpl))
12701     {
12702       tree spec;
12703       tree clone;
12704
12705       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12706          DECL_CLONED_FUNCTION.  */
12707       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12708                                    targ_ptr, complain);
12709       if (spec == error_mark_node)
12710         return error_mark_node;
12711
12712       /* Look for the clone.  */
12713       FOR_EACH_CLONE (clone, spec)
12714         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12715           return clone;
12716       /* We should always have found the clone by now.  */
12717       gcc_unreachable ();
12718       return NULL_TREE;
12719     }
12720
12721   /* Check to see if we already have this specialization.  */
12722   gen_tmpl = most_general_template (tmpl);
12723   if (tmpl != gen_tmpl)
12724     /* The TMPL is a partial instantiation.  To get a full set of
12725        arguments we must add the arguments used to perform the
12726        partial instantiation.  */
12727     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12728                                             targ_ptr);
12729
12730   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12731      but it doesn't seem to be on the hot path.  */
12732   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12733
12734   gcc_assert (tmpl == gen_tmpl
12735               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12736                   == spec)
12737               || fndecl == NULL_TREE);
12738
12739   if (spec != NULL_TREE)
12740     return spec;
12741
12742   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12743                                complain))
12744     return error_mark_node;
12745
12746   /* We are building a FUNCTION_DECL, during which the access of its
12747      parameters and return types have to be checked.  However this
12748      FUNCTION_DECL which is the desired context for access checking
12749      is not built yet.  We solve this chicken-and-egg problem by
12750      deferring all checks until we have the FUNCTION_DECL.  */
12751   push_deferring_access_checks (dk_deferred);
12752
12753   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12754      (because, for example, we have encountered a non-dependent
12755      function call in the body of a template function and must now
12756      determine which of several overloaded functions will be called),
12757      within the instantiation itself we are not processing a
12758      template.  */  
12759   saved_processing_template_decl = processing_template_decl;
12760   processing_template_decl = 0;
12761   /* Substitute template parameters to obtain the specialization.  */
12762   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12763                    targ_ptr, complain, gen_tmpl);
12764   processing_template_decl = saved_processing_template_decl;
12765   if (fndecl == error_mark_node)
12766     return error_mark_node;
12767
12768   /* Now we know the specialization, compute access previously
12769      deferred.  */
12770   push_access_scope (fndecl);
12771
12772   /* Some typedefs referenced from within the template code need to be access
12773      checked at template instantiation time, i.e now. These types were
12774      added to the template at parsing time. Let's get those and perfom
12775      the acces checks then.  */
12776   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12777   perform_deferred_access_checks ();
12778   pop_access_scope (fndecl);
12779   pop_deferring_access_checks ();
12780
12781   /* The DECL_TI_TEMPLATE should always be the immediate parent
12782      template, not the most general template.  */
12783   DECL_TI_TEMPLATE (fndecl) = tmpl;
12784
12785   /* If we've just instantiated the main entry point for a function,
12786      instantiate all the alternate entry points as well.  We do this
12787      by cloning the instantiation of the main entry point, not by
12788      instantiating the template clones.  */
12789   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12790     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12791
12792   return fndecl;
12793 }
12794
12795 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12796    NARGS elements of the arguments that are being used when calling
12797    it.  TARGS is a vector into which the deduced template arguments
12798    are placed.
12799
12800    Return zero for success, 2 for an incomplete match that doesn't resolve
12801    all the types, and 1 for complete failure.  An error message will be
12802    printed only for an incomplete match.
12803
12804    If FN is a conversion operator, or we are trying to produce a specific
12805    specialization, RETURN_TYPE is the return type desired.
12806
12807    The EXPLICIT_TARGS are explicit template arguments provided via a
12808    template-id.
12809
12810    The parameter STRICT is one of:
12811
12812    DEDUCE_CALL:
12813      We are deducing arguments for a function call, as in
12814      [temp.deduct.call].
12815
12816    DEDUCE_CONV:
12817      We are deducing arguments for a conversion function, as in
12818      [temp.deduct.conv].
12819
12820    DEDUCE_EXACT:
12821      We are deducing arguments when doing an explicit instantiation
12822      as in [temp.explicit], when determining an explicit specialization
12823      as in [temp.expl.spec], or when taking the address of a function
12824      template, as in [temp.deduct.funcaddr].  */
12825
12826 int
12827 fn_type_unification (tree fn,
12828                      tree explicit_targs,
12829                      tree targs,
12830                      const tree *args,
12831                      unsigned int nargs,
12832                      tree return_type,
12833                      unification_kind_t strict,
12834                      int flags)
12835 {
12836   tree parms;
12837   tree fntype;
12838   int result;
12839   bool incomplete_argument_packs_p = false;
12840
12841   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12842
12843   fntype = TREE_TYPE (fn);
12844   if (explicit_targs)
12845     {
12846       /* [temp.deduct]
12847
12848          The specified template arguments must match the template
12849          parameters in kind (i.e., type, nontype, template), and there
12850          must not be more arguments than there are parameters;
12851          otherwise type deduction fails.
12852
12853          Nontype arguments must match the types of the corresponding
12854          nontype template parameters, or must be convertible to the
12855          types of the corresponding nontype parameters as specified in
12856          _temp.arg.nontype_, otherwise type deduction fails.
12857
12858          All references in the function type of the function template
12859          to the corresponding template parameters are replaced by the
12860          specified template argument values.  If a substitution in a
12861          template parameter or in the function type of the function
12862          template results in an invalid type, type deduction fails.  */
12863       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12864       int i, len = TREE_VEC_LENGTH (tparms);
12865       tree converted_args;
12866       bool incomplete = false;
12867
12868       if (explicit_targs == error_mark_node)
12869         return 1;
12870
12871       converted_args
12872         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12873                                   /*require_all_args=*/false,
12874                                   /*use_default_args=*/false));
12875       if (converted_args == error_mark_node)
12876         return 1;
12877
12878       /* Substitute the explicit args into the function type.  This is
12879          necessary so that, for instance, explicitly declared function
12880          arguments can match null pointed constants.  If we were given
12881          an incomplete set of explicit args, we must not do semantic
12882          processing during substitution as we could create partial
12883          instantiations.  */
12884       for (i = 0; i < len; i++)
12885         {
12886           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12887           bool parameter_pack = false;
12888
12889           /* Dig out the actual parm.  */
12890           if (TREE_CODE (parm) == TYPE_DECL
12891               || TREE_CODE (parm) == TEMPLATE_DECL)
12892             {
12893               parm = TREE_TYPE (parm);
12894               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12895             }
12896           else if (TREE_CODE (parm) == PARM_DECL)
12897             {
12898               parm = DECL_INITIAL (parm);
12899               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12900             }
12901
12902           if (parameter_pack)
12903             {
12904               int level, idx;
12905               tree targ;
12906               template_parm_level_and_index (parm, &level, &idx);
12907
12908               /* Mark the argument pack as "incomplete". We could
12909                  still deduce more arguments during unification.  */
12910               targ = TMPL_ARG (converted_args, level, idx);
12911               if (targ)
12912                 {
12913                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12914                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12915                     = ARGUMENT_PACK_ARGS (targ);
12916                 }
12917
12918               /* We have some incomplete argument packs.  */
12919               incomplete_argument_packs_p = true;
12920             }
12921         }
12922
12923       if (incomplete_argument_packs_p)
12924         /* Any substitution is guaranteed to be incomplete if there
12925            are incomplete argument packs, because we can still deduce
12926            more arguments.  */
12927         incomplete = 1;
12928       else
12929         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12930
12931       processing_template_decl += incomplete;
12932       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12933       processing_template_decl -= incomplete;
12934
12935       if (fntype == error_mark_node)
12936         return 1;
12937
12938       /* Place the explicitly specified arguments in TARGS.  */
12939       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12940         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12941     }
12942
12943   /* Never do unification on the 'this' parameter.  */
12944   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12945
12946   if (return_type)
12947     {
12948       tree *new_args;
12949
12950       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12951       new_args = XALLOCAVEC (tree, nargs + 1);
12952       new_args[0] = return_type;
12953       memcpy (new_args + 1, args, nargs * sizeof (tree));
12954       args = new_args;
12955       ++nargs;
12956     }
12957
12958   /* We allow incomplete unification without an error message here
12959      because the standard doesn't seem to explicitly prohibit it.  Our
12960      callers must be ready to deal with unification failures in any
12961      event.  */
12962   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12963                                   targs, parms, args, nargs, /*subr=*/0,
12964                                   strict, flags);
12965
12966   if (result == 0 && incomplete_argument_packs_p)
12967     {
12968       int i, len = NUM_TMPL_ARGS (targs);
12969
12970       /* Clear the "incomplete" flags on all argument packs.  */
12971       for (i = 0; i < len; i++)
12972         {
12973           tree arg = TREE_VEC_ELT (targs, i);
12974           if (ARGUMENT_PACK_P (arg))
12975             {
12976               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12977               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12978             }
12979         }
12980     }
12981
12982   /* Now that we have bindings for all of the template arguments,
12983      ensure that the arguments deduced for the template template
12984      parameters have compatible template parameter lists.  We cannot
12985      check this property before we have deduced all template
12986      arguments, because the template parameter types of a template
12987      template parameter might depend on prior template parameters
12988      deduced after the template template parameter.  The following
12989      ill-formed example illustrates this issue:
12990
12991        template<typename T, template<T> class C> void f(C<5>, T);
12992
12993        template<int N> struct X {};
12994
12995        void g() {
12996          f(X<5>(), 5l); // error: template argument deduction fails
12997        }
12998
12999      The template parameter list of 'C' depends on the template type
13000      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13001      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13002      time that we deduce 'C'.  */
13003   if (result == 0
13004       && !template_template_parm_bindings_ok_p 
13005            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13006     return 1;
13007
13008   if (result == 0)
13009     /* All is well so far.  Now, check:
13010
13011        [temp.deduct]
13012
13013        When all template arguments have been deduced, all uses of
13014        template parameters in nondeduced contexts are replaced with
13015        the corresponding deduced argument values.  If the
13016        substitution results in an invalid type, as described above,
13017        type deduction fails.  */
13018     {
13019       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13020       if (substed == error_mark_node)
13021         return 1;
13022
13023       /* If we're looking for an exact match, check that what we got
13024          is indeed an exact match.  It might not be if some template
13025          parameters are used in non-deduced contexts.  */
13026       if (strict == DEDUCE_EXACT)
13027         {
13028           unsigned int i;
13029
13030           tree sarg
13031             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13032           if (return_type)
13033             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13034           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13035             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13036               return 1;
13037         }
13038     }
13039
13040   return result;
13041 }
13042
13043 /* Adjust types before performing type deduction, as described in
13044    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13045    sections are symmetric.  PARM is the type of a function parameter
13046    or the return type of the conversion function.  ARG is the type of
13047    the argument passed to the call, or the type of the value
13048    initialized with the result of the conversion function.
13049    ARG_EXPR is the original argument expression, which may be null.  */
13050
13051 static int
13052 maybe_adjust_types_for_deduction (unification_kind_t strict,
13053                                   tree* parm,
13054                                   tree* arg,
13055                                   tree arg_expr)
13056 {
13057   int result = 0;
13058
13059   switch (strict)
13060     {
13061     case DEDUCE_CALL:
13062       break;
13063
13064     case DEDUCE_CONV:
13065       {
13066         /* Swap PARM and ARG throughout the remainder of this
13067            function; the handling is precisely symmetric since PARM
13068            will initialize ARG rather than vice versa.  */
13069         tree* temp = parm;
13070         parm = arg;
13071         arg = temp;
13072         break;
13073       }
13074
13075     case DEDUCE_EXACT:
13076       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13077          too, but here handle it by stripping the reference from PARM
13078          rather than by adding it to ARG.  */
13079       if (TREE_CODE (*parm) == REFERENCE_TYPE
13080           && TYPE_REF_IS_RVALUE (*parm)
13081           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13082           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13083           && TREE_CODE (*arg) == REFERENCE_TYPE
13084           && !TYPE_REF_IS_RVALUE (*arg))
13085         *parm = TREE_TYPE (*parm);
13086       /* Nothing else to do in this case.  */
13087       return 0;
13088
13089     default:
13090       gcc_unreachable ();
13091     }
13092
13093   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13094     {
13095       /* [temp.deduct.call]
13096
13097          If P is not a reference type:
13098
13099          --If A is an array type, the pointer type produced by the
13100          array-to-pointer standard conversion (_conv.array_) is
13101          used in place of A for type deduction; otherwise,
13102
13103          --If A is a function type, the pointer type produced by
13104          the function-to-pointer standard conversion
13105          (_conv.func_) is used in place of A for type deduction;
13106          otherwise,
13107
13108          --If A is a cv-qualified type, the top level
13109          cv-qualifiers of A's type are ignored for type
13110          deduction.  */
13111       if (TREE_CODE (*arg) == ARRAY_TYPE)
13112         *arg = build_pointer_type (TREE_TYPE (*arg));
13113       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13114         *arg = build_pointer_type (*arg);
13115       else
13116         *arg = TYPE_MAIN_VARIANT (*arg);
13117     }
13118
13119   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13120      of the form T&&, where T is a template parameter, and the argument
13121      is an lvalue, T is deduced as A& */
13122   if (TREE_CODE (*parm) == REFERENCE_TYPE
13123       && TYPE_REF_IS_RVALUE (*parm)
13124       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13125       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13126       && arg_expr && real_lvalue_p (arg_expr))
13127     *arg = build_reference_type (*arg);
13128
13129   /* [temp.deduct.call]
13130
13131      If P is a cv-qualified type, the top level cv-qualifiers
13132      of P's type are ignored for type deduction.  If P is a
13133      reference type, the type referred to by P is used for
13134      type deduction.  */
13135   *parm = TYPE_MAIN_VARIANT (*parm);
13136   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13137     {
13138       *parm = TREE_TYPE (*parm);
13139       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13140     }
13141
13142   /* DR 322. For conversion deduction, remove a reference type on parm
13143      too (which has been swapped into ARG).  */
13144   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13145     *arg = TREE_TYPE (*arg);
13146
13147   return result;
13148 }
13149
13150 /* Most parms like fn_type_unification.
13151
13152    If SUBR is 1, we're being called recursively (to unify the
13153    arguments of a function or method parameter of a function
13154    template). */
13155
13156 static int
13157 type_unification_real (tree tparms,
13158                        tree targs,
13159                        tree xparms,
13160                        const tree *xargs,
13161                        unsigned int xnargs,
13162                        int subr,
13163                        unification_kind_t strict,
13164                        int flags)
13165 {
13166   tree parm, arg, arg_expr;
13167   int i;
13168   int ntparms = TREE_VEC_LENGTH (tparms);
13169   int sub_strict;
13170   int saw_undeduced = 0;
13171   tree parms;
13172   const tree *args;
13173   unsigned int nargs;
13174   unsigned int ia;
13175
13176   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13177   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13178   gcc_assert (ntparms > 0);
13179
13180   switch (strict)
13181     {
13182     case DEDUCE_CALL:
13183       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13184                     | UNIFY_ALLOW_DERIVED);
13185       break;
13186
13187     case DEDUCE_CONV:
13188       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13189       break;
13190
13191     case DEDUCE_EXACT:
13192       sub_strict = UNIFY_ALLOW_NONE;
13193       break;
13194
13195     default:
13196       gcc_unreachable ();
13197     }
13198
13199  again:
13200   parms = xparms;
13201   args = xargs;
13202   nargs = xnargs;
13203
13204   ia = 0;
13205   while (parms && parms != void_list_node
13206          && ia < nargs)
13207     {
13208       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13209         break;
13210
13211       parm = TREE_VALUE (parms);
13212       parms = TREE_CHAIN (parms);
13213       arg = args[ia];
13214       ++ia;
13215       arg_expr = NULL;
13216
13217       if (arg == error_mark_node)
13218         return 1;
13219       if (arg == unknown_type_node)
13220         /* We can't deduce anything from this, but we might get all the
13221            template args from other function args.  */
13222         continue;
13223
13224       /* Conversions will be performed on a function argument that
13225          corresponds with a function parameter that contains only
13226          non-deducible template parameters and explicitly specified
13227          template parameters.  */
13228       if (!uses_template_parms (parm))
13229         {
13230           tree type;
13231
13232           if (!TYPE_P (arg))
13233             type = TREE_TYPE (arg);
13234           else
13235             type = arg;
13236
13237           if (same_type_p (parm, type))
13238             continue;
13239           if (strict != DEDUCE_EXACT
13240               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13241                                   flags))
13242             continue;
13243
13244           return 1;
13245         }
13246
13247       if (!TYPE_P (arg))
13248         {
13249           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13250           if (type_unknown_p (arg))
13251             {
13252               /* [temp.deduct.type] 
13253
13254                  A template-argument can be deduced from a pointer to
13255                  function or pointer to member function argument if
13256                  the set of overloaded functions does not contain
13257                  function templates and at most one of a set of
13258                  overloaded functions provides a unique match.  */
13259               if (resolve_overloaded_unification
13260                   (tparms, targs, parm, arg, strict, sub_strict))
13261                 continue;
13262
13263               return 1;
13264             }
13265           arg_expr = arg;
13266           arg = unlowered_expr_type (arg);
13267           if (arg == error_mark_node)
13268             return 1;
13269         }
13270
13271       {
13272         int arg_strict = sub_strict;
13273
13274         if (!subr)
13275           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13276                                                           arg_expr);
13277
13278         if (arg == init_list_type_node && arg_expr)
13279           arg = arg_expr;
13280         if (unify (tparms, targs, parm, arg, arg_strict))
13281           return 1;
13282       }
13283     }
13284
13285
13286   if (parms 
13287       && parms != void_list_node
13288       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13289     {
13290       /* Unify the remaining arguments with the pack expansion type.  */
13291       tree argvec;
13292       tree parmvec = make_tree_vec (1);
13293
13294       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13295       argvec = make_tree_vec (nargs - ia);
13296       for (i = 0; ia < nargs; ++ia, ++i)
13297         TREE_VEC_ELT (argvec, i) = args[ia];
13298
13299       /* Copy the parameter into parmvec.  */
13300       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13301       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13302                                 /*call_args_p=*/true, /*subr=*/subr))
13303         return 1;
13304
13305       /* Advance to the end of the list of parameters.  */
13306       parms = TREE_CHAIN (parms);
13307     }
13308
13309   /* Fail if we've reached the end of the parm list, and more args
13310      are present, and the parm list isn't variadic.  */
13311   if (ia < nargs && parms == void_list_node)
13312     return 1;
13313   /* Fail if parms are left and they don't have default values.  */
13314   if (parms && parms != void_list_node
13315       && TREE_PURPOSE (parms) == NULL_TREE)
13316     return 1;
13317
13318   if (!subr)
13319     for (i = 0; i < ntparms; i++)
13320       if (!TREE_VEC_ELT (targs, i))
13321         {
13322           tree tparm;
13323
13324           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13325             continue;
13326
13327           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13328
13329           /* If this is an undeduced nontype parameter that depends on
13330              a type parameter, try another pass; its type may have been
13331              deduced from a later argument than the one from which
13332              this parameter can be deduced.  */
13333           if (TREE_CODE (tparm) == PARM_DECL
13334               && uses_template_parms (TREE_TYPE (tparm))
13335               && !saw_undeduced++)
13336             goto again;
13337
13338           /* Core issue #226 (C++0x) [temp.deduct]:
13339
13340                If a template argument has not been deduced, its
13341                default template argument, if any, is used. 
13342
13343              When we are in C++98 mode, TREE_PURPOSE will either
13344              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13345              to explicitly check cxx_dialect here.  */
13346           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13347             {
13348               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13349               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13350               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13351               arg = convert_template_argument (parm, arg, targs, tf_none,
13352                                                i, NULL_TREE);
13353               if (arg == error_mark_node)
13354                 return 1;
13355               else
13356                 {
13357                   TREE_VEC_ELT (targs, i) = arg;
13358                   continue;
13359                 }
13360             }
13361
13362           /* If the type parameter is a parameter pack, then it will
13363              be deduced to an empty parameter pack.  */
13364           if (template_parameter_pack_p (tparm))
13365             {
13366               tree arg;
13367
13368               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13369                 {
13370                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13371                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13372                   TREE_CONSTANT (arg) = 1;
13373                 }
13374               else
13375                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13376
13377               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13378
13379               TREE_VEC_ELT (targs, i) = arg;
13380               continue;
13381             }
13382
13383           return 2;
13384         }
13385
13386   return 0;
13387 }
13388
13389 /* Subroutine of type_unification_real.  Args are like the variables
13390    at the call site.  ARG is an overloaded function (or template-id);
13391    we try deducing template args from each of the overloads, and if
13392    only one succeeds, we go with that.  Modifies TARGS and returns
13393    true on success.  */
13394
13395 static bool
13396 resolve_overloaded_unification (tree tparms,
13397                                 tree targs,
13398                                 tree parm,
13399                                 tree arg,
13400                                 unification_kind_t strict,
13401                                 int sub_strict)
13402 {
13403   tree tempargs = copy_node (targs);
13404   int good = 0;
13405   tree goodfn = NULL_TREE;
13406   bool addr_p;
13407
13408   if (TREE_CODE (arg) == ADDR_EXPR)
13409     {
13410       arg = TREE_OPERAND (arg, 0);
13411       addr_p = true;
13412     }
13413   else
13414     addr_p = false;
13415
13416   if (TREE_CODE (arg) == COMPONENT_REF)
13417     /* Handle `&x' where `x' is some static or non-static member
13418        function name.  */
13419     arg = TREE_OPERAND (arg, 1);
13420
13421   if (TREE_CODE (arg) == OFFSET_REF)
13422     arg = TREE_OPERAND (arg, 1);
13423
13424   /* Strip baselink information.  */
13425   if (BASELINK_P (arg))
13426     arg = BASELINK_FUNCTIONS (arg);
13427
13428   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13429     {
13430       /* If we got some explicit template args, we need to plug them into
13431          the affected templates before we try to unify, in case the
13432          explicit args will completely resolve the templates in question.  */
13433
13434       tree expl_subargs = TREE_OPERAND (arg, 1);
13435       arg = TREE_OPERAND (arg, 0);
13436
13437       for (; arg; arg = OVL_NEXT (arg))
13438         {
13439           tree fn = OVL_CURRENT (arg);
13440           tree subargs, elem;
13441
13442           if (TREE_CODE (fn) != TEMPLATE_DECL)
13443             continue;
13444
13445           ++processing_template_decl;
13446           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13447                                   expl_subargs, /*check_ret=*/false);
13448           if (subargs)
13449             {
13450               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13451               if (try_one_overload (tparms, targs, tempargs, parm,
13452                                     elem, strict, sub_strict, addr_p)
13453                   && (!goodfn || !decls_match (goodfn, elem)))
13454                 {
13455                   goodfn = elem;
13456                   ++good;
13457                 }
13458             }
13459           --processing_template_decl;
13460         }
13461     }
13462   else if (TREE_CODE (arg) != OVERLOAD
13463            && TREE_CODE (arg) != FUNCTION_DECL)
13464     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13465        -- but the deduction does not succeed because the expression is
13466        not just the function on its own.  */
13467     return false;
13468   else
13469     for (; arg; arg = OVL_NEXT (arg))
13470       if (try_one_overload (tparms, targs, tempargs, parm,
13471                             TREE_TYPE (OVL_CURRENT (arg)),
13472                             strict, sub_strict, addr_p)
13473           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13474         {
13475           goodfn = OVL_CURRENT (arg);
13476           ++good;
13477         }
13478
13479   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13480      to function or pointer to member function argument if the set of
13481      overloaded functions does not contain function templates and at most
13482      one of a set of overloaded functions provides a unique match.
13483
13484      So if we found multiple possibilities, we return success but don't
13485      deduce anything.  */
13486
13487   if (good == 1)
13488     {
13489       int i = TREE_VEC_LENGTH (targs);
13490       for (; i--; )
13491         if (TREE_VEC_ELT (tempargs, i))
13492           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13493     }
13494   if (good)
13495     return true;
13496
13497   return false;
13498 }
13499
13500 /* Core DR 115: In contexts where deduction is done and fails, or in
13501    contexts where deduction is not done, if a template argument list is
13502    specified and it, along with any default template arguments, identifies
13503    a single function template specialization, then the template-id is an
13504    lvalue for the function template specialization.  */
13505
13506 tree
13507 resolve_nondeduced_context (tree orig_expr)
13508 {
13509   tree expr, offset, baselink;
13510   bool addr;
13511
13512   if (!type_unknown_p (orig_expr))
13513     return orig_expr;
13514
13515   expr = orig_expr;
13516   addr = false;
13517   offset = NULL_TREE;
13518   baselink = NULL_TREE;
13519
13520   if (TREE_CODE (expr) == ADDR_EXPR)
13521     {
13522       expr = TREE_OPERAND (expr, 0);
13523       addr = true;
13524     }
13525   if (TREE_CODE (expr) == OFFSET_REF)
13526     {
13527       offset = expr;
13528       expr = TREE_OPERAND (expr, 1);
13529     }
13530   if (TREE_CODE (expr) == BASELINK)
13531     {
13532       baselink = expr;
13533       expr = BASELINK_FUNCTIONS (expr);
13534     }
13535
13536   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13537     {
13538       int good = 0;
13539       tree goodfn = NULL_TREE;
13540
13541       /* If we got some explicit template args, we need to plug them into
13542          the affected templates before we try to unify, in case the
13543          explicit args will completely resolve the templates in question.  */
13544
13545       tree expl_subargs = TREE_OPERAND (expr, 1);
13546       tree arg = TREE_OPERAND (expr, 0);
13547       tree badfn = NULL_TREE;
13548       tree badargs = NULL_TREE;
13549
13550       for (; arg; arg = OVL_NEXT (arg))
13551         {
13552           tree fn = OVL_CURRENT (arg);
13553           tree subargs, elem;
13554
13555           if (TREE_CODE (fn) != TEMPLATE_DECL)
13556             continue;
13557
13558           ++processing_template_decl;
13559           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13560                                   expl_subargs, /*check_ret=*/false);
13561           if (subargs && !any_dependent_template_arguments_p (subargs))
13562             {
13563               elem = instantiate_template (fn, subargs, tf_none);
13564               if (elem == error_mark_node)
13565                 {
13566                   badfn = fn;
13567                   badargs = subargs;
13568                 }
13569               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13570                 {
13571                   goodfn = elem;
13572                   ++good;
13573                 }
13574             }
13575           --processing_template_decl;
13576         }
13577       if (good == 1)
13578         {
13579           expr = goodfn;
13580           if (baselink)
13581             expr = build_baselink (BASELINK_BINFO (baselink),
13582                                    BASELINK_ACCESS_BINFO (baselink),
13583                                    expr, BASELINK_OPTYPE (baselink));
13584           if (offset)
13585             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13586                            TREE_OPERAND (offset, 0), expr);
13587           if (addr)
13588             expr = build_address (expr);
13589           return expr;
13590         }
13591       else if (good == 0 && badargs)
13592         /* There were no good options and at least one bad one, so let the
13593            user know what the problem is.  */
13594         instantiate_template (badfn, badargs, tf_warning_or_error);
13595     }
13596   return orig_expr;
13597 }
13598
13599 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13600    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13601    different overloads deduce different arguments for a given parm.
13602    ADDR_P is true if the expression for which deduction is being
13603    performed was of the form "& fn" rather than simply "fn".
13604
13605    Returns 1 on success.  */
13606
13607 static int
13608 try_one_overload (tree tparms,
13609                   tree orig_targs,
13610                   tree targs,
13611                   tree parm,
13612                   tree arg,
13613                   unification_kind_t strict,
13614                   int sub_strict,
13615                   bool addr_p)
13616 {
13617   int nargs;
13618   tree tempargs;
13619   int i;
13620
13621   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13622      to function or pointer to member function argument if the set of
13623      overloaded functions does not contain function templates and at most
13624      one of a set of overloaded functions provides a unique match.
13625
13626      So if this is a template, just return success.  */
13627
13628   if (uses_template_parms (arg))
13629     return 1;
13630
13631   if (TREE_CODE (arg) == METHOD_TYPE)
13632     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13633   else if (addr_p)
13634     arg = build_pointer_type (arg);
13635
13636   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13637
13638   /* We don't copy orig_targs for this because if we have already deduced
13639      some template args from previous args, unify would complain when we
13640      try to deduce a template parameter for the same argument, even though
13641      there isn't really a conflict.  */
13642   nargs = TREE_VEC_LENGTH (targs);
13643   tempargs = make_tree_vec (nargs);
13644
13645   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13646     return 0;
13647
13648   /* First make sure we didn't deduce anything that conflicts with
13649      explicitly specified args.  */
13650   for (i = nargs; i--; )
13651     {
13652       tree elt = TREE_VEC_ELT (tempargs, i);
13653       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13654
13655       if (!elt)
13656         /*NOP*/;
13657       else if (uses_template_parms (elt))
13658         /* Since we're unifying against ourselves, we will fill in
13659            template args used in the function parm list with our own
13660            template parms.  Discard them.  */
13661         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13662       else if (oldelt && !template_args_equal (oldelt, elt))
13663         return 0;
13664     }
13665
13666   for (i = nargs; i--; )
13667     {
13668       tree elt = TREE_VEC_ELT (tempargs, i);
13669
13670       if (elt)
13671         TREE_VEC_ELT (targs, i) = elt;
13672     }
13673
13674   return 1;
13675 }
13676
13677 /* PARM is a template class (perhaps with unbound template
13678    parameters).  ARG is a fully instantiated type.  If ARG can be
13679    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13680    TARGS are as for unify.  */
13681
13682 static tree
13683 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13684 {
13685   tree copy_of_targs;
13686
13687   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13688       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13689           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13690     return NULL_TREE;
13691
13692   /* We need to make a new template argument vector for the call to
13693      unify.  If we used TARGS, we'd clutter it up with the result of
13694      the attempted unification, even if this class didn't work out.
13695      We also don't want to commit ourselves to all the unifications
13696      we've already done, since unification is supposed to be done on
13697      an argument-by-argument basis.  In other words, consider the
13698      following pathological case:
13699
13700        template <int I, int J, int K>
13701        struct S {};
13702
13703        template <int I, int J>
13704        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13705
13706        template <int I, int J, int K>
13707        void f(S<I, J, K>, S<I, I, I>);
13708
13709        void g() {
13710          S<0, 0, 0> s0;
13711          S<0, 1, 2> s2;
13712
13713          f(s0, s2);
13714        }
13715
13716      Now, by the time we consider the unification involving `s2', we
13717      already know that we must have `f<0, 0, 0>'.  But, even though
13718      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13719      because there are two ways to unify base classes of S<0, 1, 2>
13720      with S<I, I, I>.  If we kept the already deduced knowledge, we
13721      would reject the possibility I=1.  */
13722   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13723
13724   /* If unification failed, we're done.  */
13725   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13726              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13727     return NULL_TREE;
13728
13729   return arg;
13730 }
13731
13732 /* Given a template type PARM and a class type ARG, find the unique
13733    base type in ARG that is an instance of PARM.  We do not examine
13734    ARG itself; only its base-classes.  If there is not exactly one
13735    appropriate base class, return NULL_TREE.  PARM may be the type of
13736    a partial specialization, as well as a plain template type.  Used
13737    by unify.  */
13738
13739 static tree
13740 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13741 {
13742   tree rval = NULL_TREE;
13743   tree binfo;
13744
13745   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13746
13747   binfo = TYPE_BINFO (complete_type (arg));
13748   if (!binfo)
13749     /* The type could not be completed.  */
13750     return NULL_TREE;
13751
13752   /* Walk in inheritance graph order.  The search order is not
13753      important, and this avoids multiple walks of virtual bases.  */
13754   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13755     {
13756       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13757
13758       if (r)
13759         {
13760           /* If there is more than one satisfactory baseclass, then:
13761
13762                [temp.deduct.call]
13763
13764               If they yield more than one possible deduced A, the type
13765               deduction fails.
13766
13767              applies.  */
13768           if (rval && !same_type_p (r, rval))
13769             return NULL_TREE;
13770
13771           rval = r;
13772         }
13773     }
13774
13775   return rval;
13776 }
13777
13778 /* Returns the level of DECL, which declares a template parameter.  */
13779
13780 static int
13781 template_decl_level (tree decl)
13782 {
13783   switch (TREE_CODE (decl))
13784     {
13785     case TYPE_DECL:
13786     case TEMPLATE_DECL:
13787       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13788
13789     case PARM_DECL:
13790       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13791
13792     default:
13793       gcc_unreachable ();
13794     }
13795   return 0;
13796 }
13797
13798 /* Decide whether ARG can be unified with PARM, considering only the
13799    cv-qualifiers of each type, given STRICT as documented for unify.
13800    Returns nonzero iff the unification is OK on that basis.  */
13801
13802 static int
13803 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13804 {
13805   int arg_quals = cp_type_quals (arg);
13806   int parm_quals = cp_type_quals (parm);
13807
13808   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13809       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13810     {
13811       /*  Although a CVR qualifier is ignored when being applied to a
13812           substituted template parameter ([8.3.2]/1 for example), that
13813           does not apply during deduction [14.8.2.4]/1, (even though
13814           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13815           this).  Except when we're allowing additional CV qualifiers
13816           at the outer level [14.8.2.1]/3,1st bullet.  */
13817       if ((TREE_CODE (arg) == REFERENCE_TYPE
13818            || TREE_CODE (arg) == FUNCTION_TYPE
13819            || TREE_CODE (arg) == METHOD_TYPE)
13820           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13821         return 0;
13822
13823       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13824           && (parm_quals & TYPE_QUAL_RESTRICT))
13825         return 0;
13826     }
13827
13828   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13829       && (arg_quals & parm_quals) != parm_quals)
13830     return 0;
13831
13832   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13833       && (parm_quals & arg_quals) != arg_quals)
13834     return 0;
13835
13836   return 1;
13837 }
13838
13839 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13840 void 
13841 template_parm_level_and_index (tree parm, int* level, int* index)
13842 {
13843   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13844       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13845       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13846     {
13847       *index = TEMPLATE_TYPE_IDX (parm);
13848       *level = TEMPLATE_TYPE_LEVEL (parm);
13849     }
13850   else
13851     {
13852       *index = TEMPLATE_PARM_IDX (parm);
13853       *level = TEMPLATE_PARM_LEVEL (parm);
13854     }
13855 }
13856
13857 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13858    expansion at the end of PACKED_PARMS. Returns 0 if the type
13859    deduction succeeds, 1 otherwise. STRICT is the same as in
13860    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13861    call argument list. We'll need to adjust the arguments to make them
13862    types. SUBR tells us if this is from a recursive call to
13863    type_unification_real.  */
13864 int
13865 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13866                       tree packed_args, int strict, bool call_args_p,
13867                       bool subr)
13868 {
13869   tree parm 
13870     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13871   tree pattern = PACK_EXPANSION_PATTERN (parm);
13872   tree pack, packs = NULL_TREE;
13873   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13874   int len = TREE_VEC_LENGTH (packed_args);
13875
13876   /* Determine the parameter packs we will be deducing from the
13877      pattern, and record their current deductions.  */
13878   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13879        pack; pack = TREE_CHAIN (pack))
13880     {
13881       tree parm_pack = TREE_VALUE (pack);
13882       int idx, level;
13883
13884       /* Determine the index and level of this parameter pack.  */
13885       template_parm_level_and_index (parm_pack, &level, &idx);
13886
13887       /* Keep track of the parameter packs and their corresponding
13888          argument packs.  */
13889       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13890       TREE_TYPE (packs) = make_tree_vec (len - start);
13891     }
13892   
13893   /* Loop through all of the arguments that have not yet been
13894      unified and unify each with the pattern.  */
13895   for (i = start; i < len; i++)
13896     {
13897       tree parm = pattern;
13898
13899       /* For each parameter pack, clear out the deduced value so that
13900          we can deduce it again.  */
13901       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13902         {
13903           int idx, level;
13904           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13905
13906           TMPL_ARG (targs, level, idx) = NULL_TREE;
13907         }
13908
13909       /* Unify the pattern with the current argument.  */
13910       {
13911         tree arg = TREE_VEC_ELT (packed_args, i);
13912         tree arg_expr = NULL_TREE;
13913         int arg_strict = strict;
13914         bool skip_arg_p = false;
13915
13916         if (call_args_p)
13917           {
13918             int sub_strict;
13919
13920             /* This mirrors what we do in type_unification_real.  */
13921             switch (strict)
13922               {
13923               case DEDUCE_CALL:
13924                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13925                               | UNIFY_ALLOW_MORE_CV_QUAL
13926                               | UNIFY_ALLOW_DERIVED);
13927                 break;
13928                 
13929               case DEDUCE_CONV:
13930                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13931                 break;
13932                 
13933               case DEDUCE_EXACT:
13934                 sub_strict = UNIFY_ALLOW_NONE;
13935                 break;
13936                 
13937               default:
13938                 gcc_unreachable ();
13939               }
13940
13941             if (!TYPE_P (arg))
13942               {
13943                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13944                 if (type_unknown_p (arg))
13945                   {
13946                     /* [temp.deduct.type] A template-argument can be
13947                        deduced from a pointer to function or pointer
13948                        to member function argument if the set of
13949                        overloaded functions does not contain function
13950                        templates and at most one of a set of
13951                        overloaded functions provides a unique
13952                        match.  */
13953
13954                     if (resolve_overloaded_unification
13955                         (tparms, targs, parm, arg,
13956                          (unification_kind_t) strict,
13957                          sub_strict)
13958                         != 0)
13959                       return 1;
13960                     skip_arg_p = true;
13961                   }
13962
13963                 if (!skip_arg_p)
13964                   {
13965                     arg_expr = arg;
13966                     arg = unlowered_expr_type (arg);
13967                     if (arg == error_mark_node)
13968                       return 1;
13969                   }
13970               }
13971       
13972             arg_strict = sub_strict;
13973
13974             if (!subr)
13975               arg_strict |= 
13976                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13977                                                   &parm, &arg, arg_expr);
13978           }
13979
13980         if (!skip_arg_p)
13981           {
13982             if (unify (tparms, targs, parm, arg, arg_strict))
13983               return 1;
13984           }
13985       }
13986
13987       /* For each parameter pack, collect the deduced value.  */
13988       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13989         {
13990           int idx, level;
13991           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13992
13993           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13994             TMPL_ARG (targs, level, idx);
13995         }
13996     }
13997
13998   /* Verify that the results of unification with the parameter packs
13999      produce results consistent with what we've seen before, and make
14000      the deduced argument packs available.  */
14001   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14002     {
14003       tree old_pack = TREE_VALUE (pack);
14004       tree new_args = TREE_TYPE (pack);
14005       int i, len = TREE_VEC_LENGTH (new_args);
14006       bool nondeduced_p = false;
14007
14008       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14009          actually deduce anything.  */
14010       for (i = 0; i < len && !nondeduced_p; ++i)
14011         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14012           nondeduced_p = true;
14013       if (nondeduced_p)
14014         continue;
14015
14016       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14017         {
14018           /* Prepend the explicit arguments onto NEW_ARGS.  */
14019           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14020           tree old_args = new_args;
14021           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14022           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14023
14024           /* Copy the explicit arguments.  */
14025           new_args = make_tree_vec (len);
14026           for (i = 0; i < explicit_len; i++)
14027             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14028
14029           /* Copy the deduced arguments.  */
14030           for (; i < len; i++)
14031             TREE_VEC_ELT (new_args, i) =
14032               TREE_VEC_ELT (old_args, i - explicit_len);
14033         }
14034
14035       if (!old_pack)
14036         {
14037           tree result;
14038           int idx, level;
14039           
14040           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14041
14042           /* Build the deduced *_ARGUMENT_PACK.  */
14043           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14044             {
14045               result = make_node (NONTYPE_ARGUMENT_PACK);
14046               TREE_TYPE (result) = 
14047                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14048               TREE_CONSTANT (result) = 1;
14049             }
14050           else
14051             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14052
14053           SET_ARGUMENT_PACK_ARGS (result, new_args);
14054
14055           /* Note the deduced argument packs for this parameter
14056              pack.  */
14057           TMPL_ARG (targs, level, idx) = result;
14058         }
14059       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14060                && (ARGUMENT_PACK_ARGS (old_pack) 
14061                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14062         {
14063           /* We only had the explicitly-provided arguments before, but
14064              now we have a complete set of arguments.  */
14065           int idx, level;
14066           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14067           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14068
14069           /* Keep the original deduced argument pack.  */
14070           TMPL_ARG (targs, level, idx) = old_pack;
14071
14072           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14073           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14074           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14075         }
14076       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14077                                     new_args))
14078         /* Inconsistent unification of this parameter pack.  */
14079         return 1;
14080       else
14081         {
14082           int idx, level;
14083           
14084           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14085
14086           /* Keep the original deduced argument pack.  */
14087           TMPL_ARG (targs, level, idx) = old_pack;
14088         }
14089     }
14090
14091   return 0;
14092 }
14093
14094 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14095    set of template parameters to a template.  TARGS is the bindings
14096    for those template parameters, as determined thus far; TARGS may
14097    include template arguments for outer levels of template parameters
14098    as well.  PARM is a parameter to a template function, or a
14099    subcomponent of that parameter; ARG is the corresponding argument.
14100    This function attempts to match PARM with ARG in a manner
14101    consistent with the existing assignments in TARGS.  If more values
14102    are deduced, then TARGS is updated.
14103
14104    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14105    parameter STRICT is a bitwise or of the following flags:
14106
14107      UNIFY_ALLOW_NONE:
14108        Require an exact match between PARM and ARG.
14109      UNIFY_ALLOW_MORE_CV_QUAL:
14110        Allow the deduced ARG to be more cv-qualified (by qualification
14111        conversion) than ARG.
14112      UNIFY_ALLOW_LESS_CV_QUAL:
14113        Allow the deduced ARG to be less cv-qualified than ARG.
14114      UNIFY_ALLOW_DERIVED:
14115        Allow the deduced ARG to be a template base class of ARG,
14116        or a pointer to a template base class of the type pointed to by
14117        ARG.
14118      UNIFY_ALLOW_INTEGER:
14119        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14120        case for more information.
14121      UNIFY_ALLOW_OUTER_LEVEL:
14122        This is the outermost level of a deduction. Used to determine validity
14123        of qualification conversions. A valid qualification conversion must
14124        have const qualified pointers leading up to the inner type which
14125        requires additional CV quals, except at the outer level, where const
14126        is not required [conv.qual]. It would be normal to set this flag in
14127        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14128      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14129        This is the outermost level of a deduction, and PARM can be more CV
14130        qualified at this point.
14131      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14132        This is the outermost level of a deduction, and PARM can be less CV
14133        qualified at this point.  */
14134
14135 static int
14136 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14137 {
14138   int idx;
14139   tree targ;
14140   tree tparm;
14141   int strict_in = strict;
14142
14143   /* I don't think this will do the right thing with respect to types.
14144      But the only case I've seen it in so far has been array bounds, where
14145      signedness is the only information lost, and I think that will be
14146      okay.  */
14147   while (TREE_CODE (parm) == NOP_EXPR)
14148     parm = TREE_OPERAND (parm, 0);
14149
14150   if (arg == error_mark_node)
14151     return 1;
14152   if (arg == unknown_type_node
14153       || arg == init_list_type_node)
14154     /* We can't deduce anything from this, but we might get all the
14155        template args from other function args.  */
14156     return 0;
14157
14158   /* If PARM uses template parameters, then we can't bail out here,
14159      even if ARG == PARM, since we won't record unifications for the
14160      template parameters.  We might need them if we're trying to
14161      figure out which of two things is more specialized.  */
14162   if (arg == parm && !uses_template_parms (parm))
14163     return 0;
14164
14165   /* Handle init lists early, so the rest of the function can assume
14166      we're dealing with a type. */
14167   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14168     {
14169       tree elt, elttype;
14170       unsigned i;
14171       tree orig_parm = parm;
14172
14173       /* Replace T with std::initializer_list<T> for deduction.  */
14174       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14175           && flag_deduce_init_list)
14176         parm = listify (parm);
14177
14178       if (!is_std_init_list (parm))
14179         /* We can only deduce from an initializer list argument if the
14180            parameter is std::initializer_list; otherwise this is a
14181            non-deduced context. */
14182         return 0;
14183
14184       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14185
14186       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14187         {
14188           int elt_strict = strict;
14189           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14190             {
14191               tree type = TREE_TYPE (elt);
14192               /* It should only be possible to get here for a call.  */
14193               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14194               elt_strict |= maybe_adjust_types_for_deduction
14195                 (DEDUCE_CALL, &elttype, &type, elt);
14196               elt = type;
14197             }
14198
14199           if (unify (tparms, targs, elttype, elt, elt_strict))
14200             return 1;
14201         }
14202
14203       /* If the std::initializer_list<T> deduction worked, replace the
14204          deduced A with std::initializer_list<A>.  */
14205       if (orig_parm != parm)
14206         {
14207           idx = TEMPLATE_TYPE_IDX (orig_parm);
14208           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14209           targ = listify (targ);
14210           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14211         }
14212       return 0;
14213     }
14214
14215   /* Immediately reject some pairs that won't unify because of
14216      cv-qualification mismatches.  */
14217   if (TREE_CODE (arg) == TREE_CODE (parm)
14218       && TYPE_P (arg)
14219       /* It is the elements of the array which hold the cv quals of an array
14220          type, and the elements might be template type parms. We'll check
14221          when we recurse.  */
14222       && TREE_CODE (arg) != ARRAY_TYPE
14223       /* We check the cv-qualifiers when unifying with template type
14224          parameters below.  We want to allow ARG `const T' to unify with
14225          PARM `T' for example, when computing which of two templates
14226          is more specialized, for example.  */
14227       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14228       && !check_cv_quals_for_unify (strict_in, arg, parm))
14229     return 1;
14230
14231   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14232       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14233     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14234   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14235   strict &= ~UNIFY_ALLOW_DERIVED;
14236   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14237   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14238
14239   switch (TREE_CODE (parm))
14240     {
14241     case TYPENAME_TYPE:
14242     case SCOPE_REF:
14243     case UNBOUND_CLASS_TEMPLATE:
14244       /* In a type which contains a nested-name-specifier, template
14245          argument values cannot be deduced for template parameters used
14246          within the nested-name-specifier.  */
14247       return 0;
14248
14249     case TEMPLATE_TYPE_PARM:
14250     case TEMPLATE_TEMPLATE_PARM:
14251     case BOUND_TEMPLATE_TEMPLATE_PARM:
14252       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14253       if (tparm == error_mark_node)
14254         return 1;
14255
14256       if (TEMPLATE_TYPE_LEVEL (parm)
14257           != template_decl_level (tparm))
14258         /* The PARM is not one we're trying to unify.  Just check
14259            to see if it matches ARG.  */
14260         return (TREE_CODE (arg) == TREE_CODE (parm)
14261                 && same_type_p (parm, arg)) ? 0 : 1;
14262       idx = TEMPLATE_TYPE_IDX (parm);
14263       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14264       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14265
14266       /* Check for mixed types and values.  */
14267       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14268            && TREE_CODE (tparm) != TYPE_DECL)
14269           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14270               && TREE_CODE (tparm) != TEMPLATE_DECL))
14271         return 1;
14272
14273       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14274         {
14275           /* ARG must be constructed from a template class or a template
14276              template parameter.  */
14277           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14278               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14279             return 1;
14280
14281           {
14282             tree parmvec = TYPE_TI_ARGS (parm);
14283             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14284             tree parm_parms 
14285               = DECL_INNERMOST_TEMPLATE_PARMS
14286                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14287             int i, len;
14288             int parm_variadic_p = 0;
14289
14290             /* The resolution to DR150 makes clear that default
14291                arguments for an N-argument may not be used to bind T
14292                to a template template parameter with fewer than N
14293                parameters.  It is not safe to permit the binding of
14294                default arguments as an extension, as that may change
14295                the meaning of a conforming program.  Consider:
14296
14297                   struct Dense { static const unsigned int dim = 1; };
14298
14299                   template <template <typename> class View,
14300                             typename Block>
14301                   void operator+(float, View<Block> const&);
14302
14303                   template <typename Block,
14304                             unsigned int Dim = Block::dim>
14305                   struct Lvalue_proxy { operator float() const; };
14306
14307                   void
14308                   test_1d (void) {
14309                     Lvalue_proxy<Dense> p;
14310                     float b;
14311                     b + p;
14312                   }
14313
14314               Here, if Lvalue_proxy is permitted to bind to View, then
14315               the global operator+ will be used; if they are not, the
14316               Lvalue_proxy will be converted to float.  */
14317             if (coerce_template_parms (parm_parms,
14318                                        argvec,
14319                                        TYPE_TI_TEMPLATE (parm),
14320                                        tf_none,
14321                                        /*require_all_args=*/true,
14322                                        /*use_default_args=*/false)
14323                 == error_mark_node)
14324               return 1;
14325
14326             /* Deduce arguments T, i from TT<T> or TT<i>.
14327                We check each element of PARMVEC and ARGVEC individually
14328                rather than the whole TREE_VEC since they can have
14329                different number of elements.  */
14330
14331             parmvec = expand_template_argument_pack (parmvec);
14332             argvec = expand_template_argument_pack (argvec);
14333
14334             len = TREE_VEC_LENGTH (parmvec);
14335
14336             /* Check if the parameters end in a pack, making them
14337                variadic.  */
14338             if (len > 0
14339                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14340               parm_variadic_p = 1;
14341             
14342             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14343               return 1;
14344
14345              for (i = 0; i < len - parm_variadic_p; ++i)
14346               {
14347                 if (unify (tparms, targs,
14348                            TREE_VEC_ELT (parmvec, i),
14349                            TREE_VEC_ELT (argvec, i),
14350                            UNIFY_ALLOW_NONE))
14351                   return 1;
14352               }
14353
14354             if (parm_variadic_p
14355                 && unify_pack_expansion (tparms, targs,
14356                                          parmvec, argvec,
14357                                          UNIFY_ALLOW_NONE,
14358                                          /*call_args_p=*/false,
14359                                          /*subr=*/false))
14360               return 1;
14361           }
14362           arg = TYPE_TI_TEMPLATE (arg);
14363
14364           /* Fall through to deduce template name.  */
14365         }
14366
14367       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14368           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14369         {
14370           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14371
14372           /* Simple cases: Value already set, does match or doesn't.  */
14373           if (targ != NULL_TREE && template_args_equal (targ, arg))
14374             return 0;
14375           else if (targ)
14376             return 1;
14377         }
14378       else
14379         {
14380           /* If PARM is `const T' and ARG is only `int', we don't have
14381              a match unless we are allowing additional qualification.
14382              If ARG is `const int' and PARM is just `T' that's OK;
14383              that binds `const int' to `T'.  */
14384           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14385                                          arg, parm))
14386             return 1;
14387
14388           /* Consider the case where ARG is `const volatile int' and
14389              PARM is `const T'.  Then, T should be `volatile int'.  */
14390           arg = cp_build_qualified_type_real
14391             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14392           if (arg == error_mark_node)
14393             return 1;
14394
14395           /* Simple cases: Value already set, does match or doesn't.  */
14396           if (targ != NULL_TREE && same_type_p (targ, arg))
14397             return 0;
14398           else if (targ)
14399             return 1;
14400
14401           /* Make sure that ARG is not a variable-sized array.  (Note
14402              that were talking about variable-sized arrays (like
14403              `int[n]'), rather than arrays of unknown size (like
14404              `int[]').)  We'll get very confused by such a type since
14405              the bound of the array will not be computable in an
14406              instantiation.  Besides, such types are not allowed in
14407              ISO C++, so we can do as we please here.  */
14408           if (variably_modified_type_p (arg, NULL_TREE))
14409             return 1;
14410
14411           /* Strip typedefs as in convert_template_argument.  */
14412           arg = strip_typedefs (arg);
14413         }
14414
14415       /* If ARG is a parameter pack or an expansion, we cannot unify
14416          against it unless PARM is also a parameter pack.  */
14417       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14418           && !template_parameter_pack_p (parm))
14419         return 1;
14420
14421       /* If the argument deduction results is a METHOD_TYPE,
14422          then there is a problem.
14423          METHOD_TYPE doesn't map to any real C++ type the result of
14424          the deduction can not be of that type.  */
14425       if (TREE_CODE (arg) == METHOD_TYPE)
14426         return 1;
14427
14428       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14429       return 0;
14430
14431     case TEMPLATE_PARM_INDEX:
14432       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14433       if (tparm == error_mark_node)
14434         return 1;
14435
14436       if (TEMPLATE_PARM_LEVEL (parm)
14437           != template_decl_level (tparm))
14438         /* The PARM is not one we're trying to unify.  Just check
14439            to see if it matches ARG.  */
14440         return !(TREE_CODE (arg) == TREE_CODE (parm)
14441                  && cp_tree_equal (parm, arg));
14442
14443       idx = TEMPLATE_PARM_IDX (parm);
14444       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14445
14446       if (targ)
14447         return !cp_tree_equal (targ, arg);
14448
14449       /* [temp.deduct.type] If, in the declaration of a function template
14450          with a non-type template-parameter, the non-type
14451          template-parameter is used in an expression in the function
14452          parameter-list and, if the corresponding template-argument is
14453          deduced, the template-argument type shall match the type of the
14454          template-parameter exactly, except that a template-argument
14455          deduced from an array bound may be of any integral type.
14456          The non-type parameter might use already deduced type parameters.  */
14457       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14458       if (!TREE_TYPE (arg))
14459         /* Template-parameter dependent expression.  Just accept it for now.
14460            It will later be processed in convert_template_argument.  */
14461         ;
14462       else if (same_type_p (TREE_TYPE (arg), tparm))
14463         /* OK */;
14464       else if ((strict & UNIFY_ALLOW_INTEGER)
14465                && (TREE_CODE (tparm) == INTEGER_TYPE
14466                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14467         /* Convert the ARG to the type of PARM; the deduced non-type
14468            template argument must exactly match the types of the
14469            corresponding parameter.  */
14470         arg = fold (build_nop (tparm, arg));
14471       else if (uses_template_parms (tparm))
14472         /* We haven't deduced the type of this parameter yet.  Try again
14473            later.  */
14474         return 0;
14475       else
14476         return 1;
14477
14478       /* If ARG is a parameter pack or an expansion, we cannot unify
14479          against it unless PARM is also a parameter pack.  */
14480       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14481           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14482         return 1;
14483
14484       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14485       return 0;
14486
14487     case PTRMEM_CST:
14488      {
14489         /* A pointer-to-member constant can be unified only with
14490          another constant.  */
14491       if (TREE_CODE (arg) != PTRMEM_CST)
14492         return 1;
14493
14494       /* Just unify the class member. It would be useless (and possibly
14495          wrong, depending on the strict flags) to unify also
14496          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14497          arg refer to the same variable, even if through different
14498          classes. For instance:
14499
14500          struct A { int x; };
14501          struct B : A { };
14502
14503          Unification of &A::x and &B::x must succeed.  */
14504       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14505                     PTRMEM_CST_MEMBER (arg), strict);
14506      }
14507
14508     case POINTER_TYPE:
14509       {
14510         if (TREE_CODE (arg) != POINTER_TYPE)
14511           return 1;
14512
14513         /* [temp.deduct.call]
14514
14515            A can be another pointer or pointer to member type that can
14516            be converted to the deduced A via a qualification
14517            conversion (_conv.qual_).
14518
14519            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14520            This will allow for additional cv-qualification of the
14521            pointed-to types if appropriate.  */
14522
14523         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14524           /* The derived-to-base conversion only persists through one
14525              level of pointers.  */
14526           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14527
14528         return unify (tparms, targs, TREE_TYPE (parm),
14529                       TREE_TYPE (arg), strict);
14530       }
14531
14532     case REFERENCE_TYPE:
14533       if (TREE_CODE (arg) != REFERENCE_TYPE)
14534         return 1;
14535       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14536                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14537
14538     case ARRAY_TYPE:
14539       if (TREE_CODE (arg) != ARRAY_TYPE)
14540         return 1;
14541       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14542           != (TYPE_DOMAIN (arg) == NULL_TREE))
14543         return 1;
14544       if (TYPE_DOMAIN (parm) != NULL_TREE)
14545         {
14546           tree parm_max;
14547           tree arg_max;
14548           bool parm_cst;
14549           bool arg_cst;
14550
14551           /* Our representation of array types uses "N - 1" as the
14552              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14553              not an integer constant.  We cannot unify arbitrarily
14554              complex expressions, so we eliminate the MINUS_EXPRs
14555              here.  */
14556           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14557           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14558           if (!parm_cst)
14559             {
14560               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14561               parm_max = TREE_OPERAND (parm_max, 0);
14562             }
14563           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14564           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14565           if (!arg_cst)
14566             {
14567               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14568                  trying to unify the type of a variable with the type
14569                  of a template parameter.  For example:
14570
14571                    template <unsigned int N>
14572                    void f (char (&) [N]);
14573                    int g(); 
14574                    void h(int i) {
14575                      char a[g(i)];
14576                      f(a); 
14577                    }
14578
14579                 Here, the type of the ARG will be "int [g(i)]", and
14580                 may be a SAVE_EXPR, etc.  */
14581               if (TREE_CODE (arg_max) != MINUS_EXPR)
14582                 return 1;
14583               arg_max = TREE_OPERAND (arg_max, 0);
14584             }
14585
14586           /* If only one of the bounds used a MINUS_EXPR, compensate
14587              by adding one to the other bound.  */
14588           if (parm_cst && !arg_cst)
14589             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14590                                     integer_type_node,
14591                                     parm_max,
14592                                     integer_one_node);
14593           else if (arg_cst && !parm_cst)
14594             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14595                                    integer_type_node,
14596                                    arg_max,
14597                                    integer_one_node);
14598
14599           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14600             return 1;
14601         }
14602       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14603                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14604
14605     case REAL_TYPE:
14606     case COMPLEX_TYPE:
14607     case VECTOR_TYPE:
14608     case INTEGER_TYPE:
14609     case BOOLEAN_TYPE:
14610     case ENUMERAL_TYPE:
14611     case VOID_TYPE:
14612       if (TREE_CODE (arg) != TREE_CODE (parm))
14613         return 1;
14614
14615       /* We have already checked cv-qualification at the top of the
14616          function.  */
14617       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14618         return 1;
14619
14620       /* As far as unification is concerned, this wins.  Later checks
14621          will invalidate it if necessary.  */
14622       return 0;
14623
14624       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14625       /* Type INTEGER_CST can come from ordinary constant template args.  */
14626     case INTEGER_CST:
14627       while (TREE_CODE (arg) == NOP_EXPR)
14628         arg = TREE_OPERAND (arg, 0);
14629
14630       if (TREE_CODE (arg) != INTEGER_CST)
14631         return 1;
14632       return !tree_int_cst_equal (parm, arg);
14633
14634     case TREE_VEC:
14635       {
14636         int i;
14637         if (TREE_CODE (arg) != TREE_VEC)
14638           return 1;
14639         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14640           return 1;
14641         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14642           if (unify (tparms, targs,
14643                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14644                      UNIFY_ALLOW_NONE))
14645             return 1;
14646         return 0;
14647       }
14648
14649     case RECORD_TYPE:
14650     case UNION_TYPE:
14651       if (TREE_CODE (arg) != TREE_CODE (parm))
14652         return 1;
14653
14654       if (TYPE_PTRMEMFUNC_P (parm))
14655         {
14656           if (!TYPE_PTRMEMFUNC_P (arg))
14657             return 1;
14658
14659           return unify (tparms, targs,
14660                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14661                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14662                         strict);
14663         }
14664
14665       if (CLASSTYPE_TEMPLATE_INFO (parm))
14666         {
14667           tree t = NULL_TREE;
14668
14669           if (strict_in & UNIFY_ALLOW_DERIVED)
14670             {
14671               /* First, we try to unify the PARM and ARG directly.  */
14672               t = try_class_unification (tparms, targs,
14673                                          parm, arg);
14674
14675               if (!t)
14676                 {
14677                   /* Fallback to the special case allowed in
14678                      [temp.deduct.call]:
14679
14680                        If P is a class, and P has the form
14681                        template-id, then A can be a derived class of
14682                        the deduced A.  Likewise, if P is a pointer to
14683                        a class of the form template-id, A can be a
14684                        pointer to a derived class pointed to by the
14685                        deduced A.  */
14686                   t = get_template_base (tparms, targs, parm, arg);
14687
14688                   if (!t)
14689                     return 1;
14690                 }
14691             }
14692           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14693                    && (CLASSTYPE_TI_TEMPLATE (parm)
14694                        == CLASSTYPE_TI_TEMPLATE (arg)))
14695             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14696                Then, we should unify `int' and `U'.  */
14697             t = arg;
14698           else
14699             /* There's no chance of unification succeeding.  */
14700             return 1;
14701
14702           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14703                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14704         }
14705       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14706         return 1;
14707       return 0;
14708
14709     case METHOD_TYPE:
14710     case FUNCTION_TYPE:
14711       {
14712         unsigned int nargs;
14713         tree *args;
14714         tree a;
14715         unsigned int i;
14716
14717         if (TREE_CODE (arg) != TREE_CODE (parm))
14718           return 1;
14719
14720         /* CV qualifications for methods can never be deduced, they must
14721            match exactly.  We need to check them explicitly here,
14722            because type_unification_real treats them as any other
14723            cv-qualified parameter.  */
14724         if (TREE_CODE (parm) == METHOD_TYPE
14725             && (!check_cv_quals_for_unify
14726                 (UNIFY_ALLOW_NONE,
14727                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14728                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14729           return 1;
14730
14731         if (unify (tparms, targs, TREE_TYPE (parm),
14732                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14733           return 1;
14734
14735         nargs = list_length (TYPE_ARG_TYPES (arg));
14736         args = XALLOCAVEC (tree, nargs);
14737         for (a = TYPE_ARG_TYPES (arg), i = 0;
14738              a != NULL_TREE && a != void_list_node;
14739              a = TREE_CHAIN (a), ++i)
14740           args[i] = TREE_VALUE (a);
14741         nargs = i;
14742
14743         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14744                                       args, nargs, 1, DEDUCE_EXACT,
14745                                       LOOKUP_NORMAL);
14746       }
14747
14748     case OFFSET_TYPE:
14749       /* Unify a pointer to member with a pointer to member function, which
14750          deduces the type of the member as a function type. */
14751       if (TYPE_PTRMEMFUNC_P (arg))
14752         {
14753           tree method_type;
14754           tree fntype;
14755           cp_cv_quals cv_quals;
14756
14757           /* Check top-level cv qualifiers */
14758           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14759             return 1;
14760
14761           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14762                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14763             return 1;
14764
14765           /* Determine the type of the function we are unifying against. */
14766           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14767           fntype =
14768             build_function_type (TREE_TYPE (method_type),
14769                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14770
14771           /* Extract the cv-qualifiers of the member function from the
14772              implicit object parameter and place them on the function
14773              type to be restored later. */
14774           cv_quals =
14775             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14776           fntype = build_qualified_type (fntype, cv_quals);
14777           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14778         }
14779
14780       if (TREE_CODE (arg) != OFFSET_TYPE)
14781         return 1;
14782       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14783                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14784         return 1;
14785       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14786                     strict);
14787
14788     case CONST_DECL:
14789       if (DECL_TEMPLATE_PARM_P (parm))
14790         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14791       if (arg != integral_constant_value (parm))
14792         return 1;
14793       return 0;
14794
14795     case FIELD_DECL:
14796     case TEMPLATE_DECL:
14797       /* Matched cases are handled by the ARG == PARM test above.  */
14798       return 1;
14799
14800     case TYPE_ARGUMENT_PACK:
14801     case NONTYPE_ARGUMENT_PACK:
14802       {
14803         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14804         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14805         int i, len = TREE_VEC_LENGTH (packed_parms);
14806         int argslen = TREE_VEC_LENGTH (packed_args);
14807         int parm_variadic_p = 0;
14808
14809         for (i = 0; i < len; ++i)
14810           {
14811             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14812               {
14813                 if (i == len - 1)
14814                   /* We can unify against something with a trailing
14815                      parameter pack.  */
14816                   parm_variadic_p = 1;
14817                 else
14818                   /* Since there is something following the pack
14819                      expansion, we cannot unify this template argument
14820                      list.  */
14821                   return 0;
14822               }
14823           }
14824           
14825
14826         /* If we don't have enough arguments to satisfy the parameters
14827            (not counting the pack expression at the end), or we have
14828            too many arguments for a parameter list that doesn't end in
14829            a pack expression, we can't unify.  */
14830         if (argslen < (len - parm_variadic_p)
14831             || (argslen > len && !parm_variadic_p))
14832           return 1;
14833
14834         /* Unify all of the parameters that precede the (optional)
14835            pack expression.  */
14836         for (i = 0; i < len - parm_variadic_p; ++i)
14837           {
14838             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14839                        TREE_VEC_ELT (packed_args, i), strict))
14840               return 1;
14841           }
14842
14843         if (parm_variadic_p)
14844           return unify_pack_expansion (tparms, targs, 
14845                                        packed_parms, packed_args,
14846                                        strict, /*call_args_p=*/false,
14847                                        /*subr=*/false);
14848         return 0;
14849       }
14850
14851       break;
14852
14853     case TYPEOF_TYPE:
14854     case DECLTYPE_TYPE:
14855       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14856          nodes.  */
14857       return 0;
14858
14859     case ERROR_MARK:
14860       /* Unification fails if we hit an error node.  */
14861       return 1;
14862
14863     default:
14864       gcc_assert (EXPR_P (parm));
14865
14866       /* We must be looking at an expression.  This can happen with
14867          something like:
14868
14869            template <int I>
14870            void foo(S<I>, S<I + 2>);
14871
14872          This is a "nondeduced context":
14873
14874            [deduct.type]
14875
14876            The nondeduced contexts are:
14877
14878            --A type that is a template-id in which one or more of
14879              the template-arguments is an expression that references
14880              a template-parameter.
14881
14882          In these cases, we assume deduction succeeded, but don't
14883          actually infer any unifications.  */
14884
14885       if (!uses_template_parms (parm)
14886           && !template_args_equal (parm, arg))
14887         return 1;
14888       else
14889         return 0;
14890     }
14891 }
14892 \f
14893 /* Note that DECL can be defined in this translation unit, if
14894    required.  */
14895
14896 static void
14897 mark_definable (tree decl)
14898 {
14899   tree clone;
14900   DECL_NOT_REALLY_EXTERN (decl) = 1;
14901   FOR_EACH_CLONE (clone, decl)
14902     DECL_NOT_REALLY_EXTERN (clone) = 1;
14903 }
14904
14905 /* Called if RESULT is explicitly instantiated, or is a member of an
14906    explicitly instantiated class.  */
14907
14908 void
14909 mark_decl_instantiated (tree result, int extern_p)
14910 {
14911   SET_DECL_EXPLICIT_INSTANTIATION (result);
14912
14913   /* If this entity has already been written out, it's too late to
14914      make any modifications.  */
14915   if (TREE_ASM_WRITTEN (result))
14916     return;
14917
14918   if (TREE_CODE (result) != FUNCTION_DECL)
14919     /* The TREE_PUBLIC flag for function declarations will have been
14920        set correctly by tsubst.  */
14921     TREE_PUBLIC (result) = 1;
14922
14923   /* This might have been set by an earlier implicit instantiation.  */
14924   DECL_COMDAT (result) = 0;
14925
14926   if (extern_p)
14927     DECL_NOT_REALLY_EXTERN (result) = 0;
14928   else
14929     {
14930       mark_definable (result);
14931       /* Always make artificials weak.  */
14932       if (DECL_ARTIFICIAL (result) && flag_weak)
14933         comdat_linkage (result);
14934       /* For WIN32 we also want to put explicit instantiations in
14935          linkonce sections.  */
14936       else if (TREE_PUBLIC (result))
14937         maybe_make_one_only (result);
14938     }
14939
14940   /* If EXTERN_P, then this function will not be emitted -- unless
14941      followed by an explicit instantiation, at which point its linkage
14942      will be adjusted.  If !EXTERN_P, then this function will be
14943      emitted here.  In neither circumstance do we want
14944      import_export_decl to adjust the linkage.  */
14945   DECL_INTERFACE_KNOWN (result) = 1;
14946 }
14947
14948 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
14949    important template arguments.  If any are missing, we check whether
14950    they're important by using error_mark_node for substituting into any
14951    args that were used for partial ordering (the ones between ARGS and END)
14952    and seeing if it bubbles up.  */
14953
14954 static bool
14955 check_undeduced_parms (tree targs, tree args, tree end)
14956 {
14957   bool found = false;
14958   int i;
14959   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
14960     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
14961       {
14962         found = true;
14963         TREE_VEC_ELT (targs, i) = error_mark_node;
14964       }
14965   if (found)
14966     {
14967       for (; args != end; args = TREE_CHAIN (args))
14968         {
14969           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
14970           if (substed == error_mark_node)
14971             return true;
14972         }
14973     }
14974   return false;
14975 }
14976
14977 /* Given two function templates PAT1 and PAT2, return:
14978
14979    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14980    -1 if PAT2 is more specialized than PAT1.
14981    0 if neither is more specialized.
14982
14983    LEN indicates the number of parameters we should consider
14984    (defaulted parameters should not be considered).
14985
14986    The 1998 std underspecified function template partial ordering, and
14987    DR214 addresses the issue.  We take pairs of arguments, one from
14988    each of the templates, and deduce them against each other.  One of
14989    the templates will be more specialized if all the *other*
14990    template's arguments deduce against its arguments and at least one
14991    of its arguments *does* *not* deduce against the other template's
14992    corresponding argument.  Deduction is done as for class templates.
14993    The arguments used in deduction have reference and top level cv
14994    qualifiers removed.  Iff both arguments were originally reference
14995    types *and* deduction succeeds in both directions, the template
14996    with the more cv-qualified argument wins for that pairing (if
14997    neither is more cv-qualified, they both are equal).  Unlike regular
14998    deduction, after all the arguments have been deduced in this way,
14999    we do *not* verify the deduced template argument values can be
15000    substituted into non-deduced contexts.
15001
15002    The logic can be a bit confusing here, because we look at deduce1 and
15003    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15004    can find template arguments for pat1 to make arg1 look like arg2, that
15005    means that arg2 is at least as specialized as arg1.  */
15006
15007 int
15008 more_specialized_fn (tree pat1, tree pat2, int len)
15009 {
15010   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15011   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15012   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15013   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15014   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15015   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15016   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15017   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15018   tree origs1, origs2;
15019   bool lose1 = false;
15020   bool lose2 = false;
15021
15022   /* Remove the this parameter from non-static member functions.  If
15023      one is a non-static member function and the other is not a static
15024      member function, remove the first parameter from that function
15025      also.  This situation occurs for operator functions where we
15026      locate both a member function (with this pointer) and non-member
15027      operator (with explicit first operand).  */
15028   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15029     {
15030       len--; /* LEN is the number of significant arguments for DECL1 */
15031       args1 = TREE_CHAIN (args1);
15032       if (!DECL_STATIC_FUNCTION_P (decl2))
15033         args2 = TREE_CHAIN (args2);
15034     }
15035   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15036     {
15037       args2 = TREE_CHAIN (args2);
15038       if (!DECL_STATIC_FUNCTION_P (decl1))
15039         {
15040           len--;
15041           args1 = TREE_CHAIN (args1);
15042         }
15043     }
15044
15045   /* If only one is a conversion operator, they are unordered.  */
15046   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15047     return 0;
15048
15049   /* Consider the return type for a conversion function */
15050   if (DECL_CONV_FN_P (decl1))
15051     {
15052       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15053       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15054       len++;
15055     }
15056
15057   processing_template_decl++;
15058
15059   origs1 = args1;
15060   origs2 = args2;
15061
15062   while (len--
15063          /* Stop when an ellipsis is seen.  */
15064          && args1 != NULL_TREE && args2 != NULL_TREE)
15065     {
15066       tree arg1 = TREE_VALUE (args1);
15067       tree arg2 = TREE_VALUE (args2);
15068       int deduce1, deduce2;
15069       int quals1 = -1;
15070       int quals2 = -1;
15071
15072       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15073           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15074         {
15075           /* When both arguments are pack expansions, we need only
15076              unify the patterns themselves.  */
15077           arg1 = PACK_EXPANSION_PATTERN (arg1);
15078           arg2 = PACK_EXPANSION_PATTERN (arg2);
15079
15080           /* This is the last comparison we need to do.  */
15081           len = 0;
15082         }
15083
15084       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15085         {
15086           arg1 = TREE_TYPE (arg1);
15087           quals1 = cp_type_quals (arg1);
15088         }
15089
15090       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15091         {
15092           arg2 = TREE_TYPE (arg2);
15093           quals2 = cp_type_quals (arg2);
15094         }
15095
15096       if ((quals1 < 0) != (quals2 < 0))
15097         {
15098           /* Only of the args is a reference, see if we should apply
15099              array/function pointer decay to it.  This is not part of
15100              DR214, but is, IMHO, consistent with the deduction rules
15101              for the function call itself, and with our earlier
15102              implementation of the underspecified partial ordering
15103              rules.  (nathan).  */
15104           if (quals1 >= 0)
15105             {
15106               switch (TREE_CODE (arg1))
15107                 {
15108                 case ARRAY_TYPE:
15109                   arg1 = TREE_TYPE (arg1);
15110                   /* FALLTHROUGH. */
15111                 case FUNCTION_TYPE:
15112                   arg1 = build_pointer_type (arg1);
15113                   break;
15114
15115                 default:
15116                   break;
15117                 }
15118             }
15119           else
15120             {
15121               switch (TREE_CODE (arg2))
15122                 {
15123                 case ARRAY_TYPE:
15124                   arg2 = TREE_TYPE (arg2);
15125                   /* FALLTHROUGH. */
15126                 case FUNCTION_TYPE:
15127                   arg2 = build_pointer_type (arg2);
15128                   break;
15129
15130                 default:
15131                   break;
15132                 }
15133             }
15134         }
15135
15136       arg1 = TYPE_MAIN_VARIANT (arg1);
15137       arg2 = TYPE_MAIN_VARIANT (arg2);
15138
15139       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15140         {
15141           int i, len2 = list_length (args2);
15142           tree parmvec = make_tree_vec (1);
15143           tree argvec = make_tree_vec (len2);
15144           tree ta = args2;
15145
15146           /* Setup the parameter vector, which contains only ARG1.  */
15147           TREE_VEC_ELT (parmvec, 0) = arg1;
15148
15149           /* Setup the argument vector, which contains the remaining
15150              arguments.  */
15151           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15152             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15153
15154           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15155                                            argvec, UNIFY_ALLOW_NONE, 
15156                                            /*call_args_p=*/false, 
15157                                            /*subr=*/0);
15158
15159           /* We cannot deduce in the other direction, because ARG1 is
15160              a pack expansion but ARG2 is not.  */
15161           deduce2 = 0;
15162         }
15163       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15164         {
15165           int i, len1 = list_length (args1);
15166           tree parmvec = make_tree_vec (1);
15167           tree argvec = make_tree_vec (len1);
15168           tree ta = args1;
15169
15170           /* Setup the parameter vector, which contains only ARG1.  */
15171           TREE_VEC_ELT (parmvec, 0) = arg2;
15172
15173           /* Setup the argument vector, which contains the remaining
15174              arguments.  */
15175           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15176             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15177
15178           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15179                                            argvec, UNIFY_ALLOW_NONE, 
15180                                            /*call_args_p=*/false, 
15181                                            /*subr=*/0);
15182
15183           /* We cannot deduce in the other direction, because ARG2 is
15184              a pack expansion but ARG1 is not.*/
15185           deduce1 = 0;
15186         }
15187
15188       else
15189         {
15190           /* The normal case, where neither argument is a pack
15191              expansion.  */
15192           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15193           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15194         }
15195
15196       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15197          arg2, then arg2 is not as specialized as arg1.  */
15198       if (!deduce1)
15199         lose2 = true;
15200       if (!deduce2)
15201         lose1 = true;
15202
15203       /* "If, for a given type, deduction succeeds in both directions
15204          (i.e., the types are identical after the transformations above)
15205          and if the type from the argument template is more cv-qualified
15206          than the type from the parameter template (as described above)
15207          that type is considered to be more specialized than the other. If
15208          neither type is more cv-qualified than the other then neither type
15209          is more specialized than the other."
15210
15211          We check same_type_p explicitly because deduction can also succeed
15212          in both directions when there is a nondeduced context.  */
15213       if (deduce1 && deduce2
15214           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15215           && same_type_p (arg1, arg2))
15216         {
15217           if ((quals1 & quals2) == quals2)
15218             lose2 = true;
15219           if ((quals1 & quals2) == quals1)
15220             lose1 = true;
15221         }
15222
15223       if (lose1 && lose2)
15224         /* We've failed to deduce something in either direction.
15225            These must be unordered.  */
15226         break;
15227
15228       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15229           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15230         /* We have already processed all of the arguments in our
15231            handing of the pack expansion type.  */
15232         len = 0;
15233
15234       args1 = TREE_CHAIN (args1);
15235       args2 = TREE_CHAIN (args2);
15236     }
15237
15238   /* "In most cases, all template parameters must have values in order for
15239      deduction to succeed, but for partial ordering purposes a template
15240      parameter may remain without a value provided it is not used in the
15241      types being used for partial ordering."
15242
15243      Thus, if we are missing any of the targs1 we need to substitute into
15244      origs1, then pat2 is not as specialized as pat1.  This can happen when
15245      there is a nondeduced context.  */
15246   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15247     lose2 = true;
15248   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15249     lose1 = true;
15250
15251   processing_template_decl--;
15252
15253   /* All things being equal, if the next argument is a pack expansion
15254      for one function but not for the other, prefer the
15255      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15256   if (lose1 == lose2
15257       && args1 && TREE_VALUE (args1)
15258       && args2 && TREE_VALUE (args2))
15259     {
15260       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15261       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15262     }
15263
15264   if (lose1 == lose2)
15265     return 0;
15266   else if (!lose1)
15267     return 1;
15268   else
15269     return -1;
15270 }
15271
15272 /* Determine which of two partial specializations is more specialized.
15273
15274    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15275    to the first partial specialization.  The TREE_VALUE is the
15276    innermost set of template parameters for the partial
15277    specialization.  PAT2 is similar, but for the second template.
15278
15279    Return 1 if the first partial specialization is more specialized;
15280    -1 if the second is more specialized; 0 if neither is more
15281    specialized.
15282
15283    See [temp.class.order] for information about determining which of
15284    two templates is more specialized.  */
15285
15286 static int
15287 more_specialized_class (tree pat1, tree pat2)
15288 {
15289   tree targs;
15290   tree tmpl1, tmpl2;
15291   int winner = 0;
15292   bool any_deductions = false;
15293
15294   tmpl1 = TREE_TYPE (pat1);
15295   tmpl2 = TREE_TYPE (pat2);
15296
15297   /* Just like what happens for functions, if we are ordering between
15298      different class template specializations, we may encounter dependent
15299      types in the arguments, and we need our dependency check functions
15300      to behave correctly.  */
15301   ++processing_template_decl;
15302   targs = get_class_bindings (TREE_VALUE (pat1),
15303                               CLASSTYPE_TI_ARGS (tmpl1),
15304                               CLASSTYPE_TI_ARGS (tmpl2));
15305   if (targs)
15306     {
15307       --winner;
15308       any_deductions = true;
15309     }
15310
15311   targs = get_class_bindings (TREE_VALUE (pat2),
15312                               CLASSTYPE_TI_ARGS (tmpl2),
15313                               CLASSTYPE_TI_ARGS (tmpl1));
15314   if (targs)
15315     {
15316       ++winner;
15317       any_deductions = true;
15318     }
15319   --processing_template_decl;
15320
15321   /* In the case of a tie where at least one of the class templates
15322      has a parameter pack at the end, the template with the most
15323      non-packed parameters wins.  */
15324   if (winner == 0
15325       && any_deductions
15326       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15327           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15328     {
15329       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15330       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15331       int len1 = TREE_VEC_LENGTH (args1);
15332       int len2 = TREE_VEC_LENGTH (args2);
15333
15334       /* We don't count the pack expansion at the end.  */
15335       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15336         --len1;
15337       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15338         --len2;
15339
15340       if (len1 > len2)
15341         return 1;
15342       else if (len1 < len2)
15343         return -1;
15344     }
15345
15346   return winner;
15347 }
15348
15349 /* Return the template arguments that will produce the function signature
15350    DECL from the function template FN, with the explicit template
15351    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15352    also match.  Return NULL_TREE if no satisfactory arguments could be
15353    found.  */
15354
15355 static tree
15356 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15357 {
15358   int ntparms = DECL_NTPARMS (fn);
15359   tree targs = make_tree_vec (ntparms);
15360   tree decl_type;
15361   tree decl_arg_types;
15362   tree *args;
15363   unsigned int nargs, ix;
15364   tree arg;
15365
15366   /* Substitute the explicit template arguments into the type of DECL.
15367      The call to fn_type_unification will handle substitution into the
15368      FN.  */
15369   decl_type = TREE_TYPE (decl);
15370   if (explicit_args && uses_template_parms (decl_type))
15371     {
15372       tree tmpl;
15373       tree converted_args;
15374
15375       if (DECL_TEMPLATE_INFO (decl))
15376         tmpl = DECL_TI_TEMPLATE (decl);
15377       else
15378         /* We can get here for some invalid specializations.  */
15379         return NULL_TREE;
15380
15381       converted_args
15382         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15383                                  explicit_args, NULL_TREE,
15384                                  tf_none,
15385                                  /*require_all_args=*/false,
15386                                  /*use_default_args=*/false);
15387       if (converted_args == error_mark_node)
15388         return NULL_TREE;
15389
15390       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15391       if (decl_type == error_mark_node)
15392         return NULL_TREE;
15393     }
15394
15395   /* Never do unification on the 'this' parameter.  */
15396   decl_arg_types = skip_artificial_parms_for (decl, 
15397                                               TYPE_ARG_TYPES (decl_type));
15398
15399   nargs = list_length (decl_arg_types);
15400   args = XALLOCAVEC (tree, nargs);
15401   for (arg = decl_arg_types, ix = 0;
15402        arg != NULL_TREE && arg != void_list_node;
15403        arg = TREE_CHAIN (arg), ++ix)
15404     args[ix] = TREE_VALUE (arg);
15405
15406   if (fn_type_unification (fn, explicit_args, targs,
15407                            args, ix,
15408                            (check_rettype || DECL_CONV_FN_P (fn)
15409                             ? TREE_TYPE (decl_type) : NULL_TREE),
15410                            DEDUCE_EXACT, LOOKUP_NORMAL))
15411     return NULL_TREE;
15412
15413   return targs;
15414 }
15415
15416 /* Return the innermost template arguments that, when applied to a
15417    template specialization whose innermost template parameters are
15418    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15419    ARGS.
15420
15421    For example, suppose we have:
15422
15423      template <class T, class U> struct S {};
15424      template <class T> struct S<T*, int> {};
15425
15426    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15427    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15428    int}.  The resulting vector will be {double}, indicating that `T'
15429    is bound to `double'.  */
15430
15431 static tree
15432 get_class_bindings (tree tparms, tree spec_args, tree args)
15433 {
15434   int i, ntparms = TREE_VEC_LENGTH (tparms);
15435   tree deduced_args;
15436   tree innermost_deduced_args;
15437
15438   innermost_deduced_args = make_tree_vec (ntparms);
15439   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15440     {
15441       deduced_args = copy_node (args);
15442       SET_TMPL_ARGS_LEVEL (deduced_args,
15443                            TMPL_ARGS_DEPTH (deduced_args),
15444                            innermost_deduced_args);
15445     }
15446   else
15447     deduced_args = innermost_deduced_args;
15448
15449   if (unify (tparms, deduced_args,
15450              INNERMOST_TEMPLATE_ARGS (spec_args),
15451              INNERMOST_TEMPLATE_ARGS (args),
15452              UNIFY_ALLOW_NONE))
15453     return NULL_TREE;
15454
15455   for (i =  0; i < ntparms; ++i)
15456     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15457       return NULL_TREE;
15458
15459   /* Verify that nondeduced template arguments agree with the type
15460      obtained from argument deduction.
15461
15462      For example:
15463
15464        struct A { typedef int X; };
15465        template <class T, class U> struct C {};
15466        template <class T> struct C<T, typename T::X> {};
15467
15468      Then with the instantiation `C<A, int>', we can deduce that
15469      `T' is `A' but unify () does not check whether `typename T::X'
15470      is `int'.  */
15471   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15472   if (spec_args == error_mark_node
15473       /* We only need to check the innermost arguments; the other
15474          arguments will always agree.  */
15475       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15476                               INNERMOST_TEMPLATE_ARGS (args)))
15477     return NULL_TREE;
15478
15479   /* Now that we have bindings for all of the template arguments,
15480      ensure that the arguments deduced for the template template
15481      parameters have compatible template parameter lists.  See the use
15482      of template_template_parm_bindings_ok_p in fn_type_unification
15483      for more information.  */
15484   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15485     return NULL_TREE;
15486
15487   return deduced_args;
15488 }
15489
15490 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15491    Return the TREE_LIST node with the most specialized template, if
15492    any.  If there is no most specialized template, the error_mark_node
15493    is returned.
15494
15495    Note that this function does not look at, or modify, the
15496    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15497    returned is one of the elements of INSTANTIATIONS, callers may
15498    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15499    and retrieve it from the value returned.  */
15500
15501 tree
15502 most_specialized_instantiation (tree templates)
15503 {
15504   tree fn, champ;
15505
15506   ++processing_template_decl;
15507
15508   champ = templates;
15509   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15510     {
15511       int fate = 0;
15512
15513       if (get_bindings (TREE_VALUE (champ),
15514                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15515                         NULL_TREE, /*check_ret=*/false))
15516         fate--;
15517
15518       if (get_bindings (TREE_VALUE (fn),
15519                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15520                         NULL_TREE, /*check_ret=*/false))
15521         fate++;
15522
15523       if (fate == -1)
15524         champ = fn;
15525       else if (!fate)
15526         {
15527           /* Equally specialized, move to next function.  If there
15528              is no next function, nothing's most specialized.  */
15529           fn = TREE_CHAIN (fn);
15530           champ = fn;
15531           if (!fn)
15532             break;
15533         }
15534     }
15535
15536   if (champ)
15537     /* Now verify that champ is better than everything earlier in the
15538        instantiation list.  */
15539     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15540       if (get_bindings (TREE_VALUE (champ),
15541                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15542                         NULL_TREE, /*check_ret=*/false)
15543           || !get_bindings (TREE_VALUE (fn),
15544                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15545                             NULL_TREE, /*check_ret=*/false))
15546         {
15547           champ = NULL_TREE;
15548           break;
15549         }
15550
15551   processing_template_decl--;
15552
15553   if (!champ)
15554     return error_mark_node;
15555
15556   return champ;
15557 }
15558
15559 /* If DECL is a specialization of some template, return the most
15560    general such template.  Otherwise, returns NULL_TREE.
15561
15562    For example, given:
15563
15564      template <class T> struct S { template <class U> void f(U); };
15565
15566    if TMPL is `template <class U> void S<int>::f(U)' this will return
15567    the full template.  This function will not trace past partial
15568    specializations, however.  For example, given in addition:
15569
15570      template <class T> struct S<T*> { template <class U> void f(U); };
15571
15572    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15573    `template <class T> template <class U> S<T*>::f(U)'.  */
15574
15575 tree
15576 most_general_template (tree decl)
15577 {
15578   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15579      an immediate specialization.  */
15580   if (TREE_CODE (decl) == FUNCTION_DECL)
15581     {
15582       if (DECL_TEMPLATE_INFO (decl)) {
15583         decl = DECL_TI_TEMPLATE (decl);
15584
15585         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15586            template friend.  */
15587         if (TREE_CODE (decl) != TEMPLATE_DECL)
15588           return NULL_TREE;
15589       } else
15590         return NULL_TREE;
15591     }
15592
15593   /* Look for more and more general templates.  */
15594   while (DECL_TEMPLATE_INFO (decl))
15595     {
15596       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15597          (See cp-tree.h for details.)  */
15598       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15599         break;
15600
15601       if (CLASS_TYPE_P (TREE_TYPE (decl))
15602           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15603         break;
15604
15605       /* Stop if we run into an explicitly specialized class template.  */
15606       if (!DECL_NAMESPACE_SCOPE_P (decl)
15607           && DECL_CONTEXT (decl)
15608           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15609         break;
15610
15611       decl = DECL_TI_TEMPLATE (decl);
15612     }
15613
15614   return decl;
15615 }
15616
15617 /* Return the most specialized of the class template partial
15618    specializations of TMPL which can produce TYPE, a specialization of
15619    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15620    a _TYPE node corresponding to the partial specialization, while the
15621    TREE_PURPOSE is the set of template arguments that must be
15622    substituted into the TREE_TYPE in order to generate TYPE.
15623
15624    If the choice of partial specialization is ambiguous, a diagnostic
15625    is issued, and the error_mark_node is returned.  If there are no
15626    partial specializations of TMPL matching TYPE, then NULL_TREE is
15627    returned.  */
15628
15629 static tree
15630 most_specialized_class (tree type, tree tmpl)
15631 {
15632   tree list = NULL_TREE;
15633   tree t;
15634   tree champ;
15635   int fate;
15636   bool ambiguous_p;
15637   tree args;
15638   tree outer_args = NULL_TREE;
15639
15640   tmpl = most_general_template (tmpl);
15641   args = CLASSTYPE_TI_ARGS (type);
15642
15643   /* For determining which partial specialization to use, only the
15644      innermost args are interesting.  */
15645   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15646     {
15647       outer_args = strip_innermost_template_args (args, 1);
15648       args = INNERMOST_TEMPLATE_ARGS (args);
15649     }
15650
15651   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15652     {
15653       tree partial_spec_args;
15654       tree spec_args;
15655       tree parms = TREE_VALUE (t);
15656
15657       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15658       if (outer_args)
15659         {
15660           int i;
15661
15662           ++processing_template_decl;
15663
15664           /* Discard the outer levels of args, and then substitute in the
15665              template args from the enclosing class.  */
15666           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15667           partial_spec_args = tsubst_template_args
15668             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15669
15670           /* PARMS already refers to just the innermost parms, but the
15671              template parms in partial_spec_args had their levels lowered
15672              by tsubst, so we need to do the same for the parm list.  We
15673              can't just tsubst the TREE_VEC itself, as tsubst wants to
15674              treat a TREE_VEC as an argument vector.  */
15675           parms = copy_node (parms);
15676           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15677             TREE_VEC_ELT (parms, i) =
15678               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15679
15680           --processing_template_decl;
15681         }
15682       spec_args = get_class_bindings (parms,
15683                                       partial_spec_args,
15684                                       args);
15685       if (spec_args)
15686         {
15687           if (outer_args)
15688             spec_args = add_to_template_args (outer_args, spec_args);
15689           list = tree_cons (spec_args, TREE_VALUE (t), list);
15690           TREE_TYPE (list) = TREE_TYPE (t);
15691         }
15692     }
15693
15694   if (! list)
15695     return NULL_TREE;
15696
15697   ambiguous_p = false;
15698   t = list;
15699   champ = t;
15700   t = TREE_CHAIN (t);
15701   for (; t; t = TREE_CHAIN (t))
15702     {
15703       fate = more_specialized_class (champ, t);
15704       if (fate == 1)
15705         ;
15706       else
15707         {
15708           if (fate == 0)
15709             {
15710               t = TREE_CHAIN (t);
15711               if (! t)
15712                 {
15713                   ambiguous_p = true;
15714                   break;
15715                 }
15716             }
15717           champ = t;
15718         }
15719     }
15720
15721   if (!ambiguous_p)
15722     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15723       {
15724         fate = more_specialized_class (champ, t);
15725         if (fate != 1)
15726           {
15727             ambiguous_p = true;
15728             break;
15729           }
15730       }
15731
15732   if (ambiguous_p)
15733     {
15734       const char *str = "candidates are:";
15735       error ("ambiguous class template instantiation for %q#T", type);
15736       for (t = list; t; t = TREE_CHAIN (t))
15737         {
15738           error ("%s %+#T", str, TREE_TYPE (t));
15739           str = "               ";
15740         }
15741       return error_mark_node;
15742     }
15743
15744   return champ;
15745 }
15746
15747 /* Explicitly instantiate DECL.  */
15748
15749 void
15750 do_decl_instantiation (tree decl, tree storage)
15751 {
15752   tree result = NULL_TREE;
15753   int extern_p = 0;
15754
15755   if (!decl || decl == error_mark_node)
15756     /* An error occurred, for which grokdeclarator has already issued
15757        an appropriate message.  */
15758     return;
15759   else if (! DECL_LANG_SPECIFIC (decl))
15760     {
15761       error ("explicit instantiation of non-template %q#D", decl);
15762       return;
15763     }
15764   else if (TREE_CODE (decl) == VAR_DECL)
15765     {
15766       /* There is an asymmetry here in the way VAR_DECLs and
15767          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15768          the latter, the DECL we get back will be marked as a
15769          template instantiation, and the appropriate
15770          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15771          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15772          should handle VAR_DECLs as it currently handles
15773          FUNCTION_DECLs.  */
15774       if (!DECL_CLASS_SCOPE_P (decl))
15775         {
15776           error ("%qD is not a static data member of a class template", decl);
15777           return;
15778         }
15779       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15780       if (!result || TREE_CODE (result) != VAR_DECL)
15781         {
15782           error ("no matching template for %qD found", decl);
15783           return;
15784         }
15785       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15786         {
15787           error ("type %qT for explicit instantiation %qD does not match "
15788                  "declared type %qT", TREE_TYPE (result), decl,
15789                  TREE_TYPE (decl));
15790           return;
15791         }
15792     }
15793   else if (TREE_CODE (decl) != FUNCTION_DECL)
15794     {
15795       error ("explicit instantiation of %q#D", decl);
15796       return;
15797     }
15798   else
15799     result = decl;
15800
15801   /* Check for various error cases.  Note that if the explicit
15802      instantiation is valid the RESULT will currently be marked as an
15803      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15804      until we get here.  */
15805
15806   if (DECL_TEMPLATE_SPECIALIZATION (result))
15807     {
15808       /* DR 259 [temp.spec].
15809
15810          Both an explicit instantiation and a declaration of an explicit
15811          specialization shall not appear in a program unless the explicit
15812          instantiation follows a declaration of the explicit specialization.
15813
15814          For a given set of template parameters, if an explicit
15815          instantiation of a template appears after a declaration of an
15816          explicit specialization for that template, the explicit
15817          instantiation has no effect.  */
15818       return;
15819     }
15820   else if (DECL_EXPLICIT_INSTANTIATION (result))
15821     {
15822       /* [temp.spec]
15823
15824          No program shall explicitly instantiate any template more
15825          than once.
15826
15827          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15828          the first instantiation was `extern' and the second is not,
15829          and EXTERN_P for the opposite case.  */
15830       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15831         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15832       /* If an "extern" explicit instantiation follows an ordinary
15833          explicit instantiation, the template is instantiated.  */
15834       if (extern_p)
15835         return;
15836     }
15837   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15838     {
15839       error ("no matching template for %qD found", result);
15840       return;
15841     }
15842   else if (!DECL_TEMPLATE_INFO (result))
15843     {
15844       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15845       return;
15846     }
15847
15848   if (storage == NULL_TREE)
15849     ;
15850   else if (storage == ridpointers[(int) RID_EXTERN])
15851     {
15852       if (!in_system_header && (cxx_dialect == cxx98))
15853         pedwarn (input_location, OPT_pedantic, 
15854                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15855                  "instantiations");
15856       extern_p = 1;
15857     }
15858   else
15859     error ("storage class %qD applied to template instantiation", storage);
15860
15861   check_explicit_instantiation_namespace (result);
15862   mark_decl_instantiated (result, extern_p);
15863   if (! extern_p)
15864     instantiate_decl (result, /*defer_ok=*/1,
15865                       /*expl_inst_class_mem_p=*/false);
15866 }
15867
15868 static void
15869 mark_class_instantiated (tree t, int extern_p)
15870 {
15871   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15872   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15873   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15874   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15875   if (! extern_p)
15876     {
15877       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15878       rest_of_type_compilation (t, 1);
15879     }
15880 }
15881
15882 /* Called from do_type_instantiation through binding_table_foreach to
15883    do recursive instantiation for the type bound in ENTRY.  */
15884 static void
15885 bt_instantiate_type_proc (binding_entry entry, void *data)
15886 {
15887   tree storage = *(tree *) data;
15888
15889   if (MAYBE_CLASS_TYPE_P (entry->type)
15890       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15891     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15892 }
15893
15894 /* Called from do_type_instantiation to instantiate a member
15895    (a member function or a static member variable) of an
15896    explicitly instantiated class template.  */
15897 static void
15898 instantiate_class_member (tree decl, int extern_p)
15899 {
15900   mark_decl_instantiated (decl, extern_p);
15901   if (! extern_p)
15902     instantiate_decl (decl, /*defer_ok=*/1,
15903                       /*expl_inst_class_mem_p=*/true);
15904 }
15905
15906 /* Perform an explicit instantiation of template class T.  STORAGE, if
15907    non-null, is the RID for extern, inline or static.  COMPLAIN is
15908    nonzero if this is called from the parser, zero if called recursively,
15909    since the standard is unclear (as detailed below).  */
15910
15911 void
15912 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15913 {
15914   int extern_p = 0;
15915   int nomem_p = 0;
15916   int static_p = 0;
15917   int previous_instantiation_extern_p = 0;
15918
15919   if (TREE_CODE (t) == TYPE_DECL)
15920     t = TREE_TYPE (t);
15921
15922   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15923     {
15924       error ("explicit instantiation of non-template type %qT", t);
15925       return;
15926     }
15927
15928   complete_type (t);
15929
15930   if (!COMPLETE_TYPE_P (t))
15931     {
15932       if (complain & tf_error)
15933         error ("explicit instantiation of %q#T before definition of template",
15934                t);
15935       return;
15936     }
15937
15938   if (storage != NULL_TREE)
15939     {
15940       if (!in_system_header)
15941         {
15942           if (storage == ridpointers[(int) RID_EXTERN])
15943             {
15944               if (cxx_dialect == cxx98)
15945                 pedwarn (input_location, OPT_pedantic, 
15946                          "ISO C++ 1998 forbids the use of %<extern%> on "
15947                          "explicit instantiations");
15948             }
15949           else
15950             pedwarn (input_location, OPT_pedantic, 
15951                      "ISO C++ forbids the use of %qE"
15952                      " on explicit instantiations", storage);
15953         }
15954
15955       if (storage == ridpointers[(int) RID_INLINE])
15956         nomem_p = 1;
15957       else if (storage == ridpointers[(int) RID_EXTERN])
15958         extern_p = 1;
15959       else if (storage == ridpointers[(int) RID_STATIC])
15960         static_p = 1;
15961       else
15962         {
15963           error ("storage class %qD applied to template instantiation",
15964                  storage);
15965           extern_p = 0;
15966         }
15967     }
15968
15969   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15970     {
15971       /* DR 259 [temp.spec].
15972
15973          Both an explicit instantiation and a declaration of an explicit
15974          specialization shall not appear in a program unless the explicit
15975          instantiation follows a declaration of the explicit specialization.
15976
15977          For a given set of template parameters, if an explicit
15978          instantiation of a template appears after a declaration of an
15979          explicit specialization for that template, the explicit
15980          instantiation has no effect.  */
15981       return;
15982     }
15983   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15984     {
15985       /* [temp.spec]
15986
15987          No program shall explicitly instantiate any template more
15988          than once.
15989
15990          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15991          instantiation was `extern'.  If EXTERN_P then the second is.
15992          These cases are OK.  */
15993       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15994
15995       if (!previous_instantiation_extern_p && !extern_p
15996           && (complain & tf_error))
15997         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15998
15999       /* If we've already instantiated the template, just return now.  */
16000       if (!CLASSTYPE_INTERFACE_ONLY (t))
16001         return;
16002     }
16003
16004   check_explicit_instantiation_namespace (TYPE_NAME (t));
16005   mark_class_instantiated (t, extern_p);
16006
16007   if (nomem_p)
16008     return;
16009
16010   {
16011     tree tmp;
16012
16013     /* In contrast to implicit instantiation, where only the
16014        declarations, and not the definitions, of members are
16015        instantiated, we have here:
16016
16017          [temp.explicit]
16018
16019          The explicit instantiation of a class template specialization
16020          implies the instantiation of all of its members not
16021          previously explicitly specialized in the translation unit
16022          containing the explicit instantiation.
16023
16024        Of course, we can't instantiate member template classes, since
16025        we don't have any arguments for them.  Note that the standard
16026        is unclear on whether the instantiation of the members are
16027        *explicit* instantiations or not.  However, the most natural
16028        interpretation is that it should be an explicit instantiation.  */
16029
16030     if (! static_p)
16031       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16032         if (TREE_CODE (tmp) == FUNCTION_DECL
16033             && DECL_TEMPLATE_INSTANTIATION (tmp))
16034           instantiate_class_member (tmp, extern_p);
16035
16036     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16037       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16038         instantiate_class_member (tmp, extern_p);
16039
16040     if (CLASSTYPE_NESTED_UTDS (t))
16041       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16042                              bt_instantiate_type_proc, &storage);
16043   }
16044 }
16045
16046 /* Given a function DECL, which is a specialization of TMPL, modify
16047    DECL to be a re-instantiation of TMPL with the same template
16048    arguments.  TMPL should be the template into which tsubst'ing
16049    should occur for DECL, not the most general template.
16050
16051    One reason for doing this is a scenario like this:
16052
16053      template <class T>
16054      void f(const T&, int i);
16055
16056      void g() { f(3, 7); }
16057
16058      template <class T>
16059      void f(const T& t, const int i) { }
16060
16061    Note that when the template is first instantiated, with
16062    instantiate_template, the resulting DECL will have no name for the
16063    first parameter, and the wrong type for the second.  So, when we go
16064    to instantiate the DECL, we regenerate it.  */
16065
16066 static void
16067 regenerate_decl_from_template (tree decl, tree tmpl)
16068 {
16069   /* The arguments used to instantiate DECL, from the most general
16070      template.  */
16071   tree args;
16072   tree code_pattern;
16073
16074   args = DECL_TI_ARGS (decl);
16075   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16076
16077   /* Make sure that we can see identifiers, and compute access
16078      correctly.  */
16079   push_access_scope (decl);
16080
16081   if (TREE_CODE (decl) == FUNCTION_DECL)
16082     {
16083       tree decl_parm;
16084       tree pattern_parm;
16085       tree specs;
16086       int args_depth;
16087       int parms_depth;
16088
16089       args_depth = TMPL_ARGS_DEPTH (args);
16090       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16091       if (args_depth > parms_depth)
16092         args = get_innermost_template_args (args, parms_depth);
16093
16094       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16095                                               args, tf_error, NULL_TREE);
16096       if (specs)
16097         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16098                                                     specs);
16099
16100       /* Merge parameter declarations.  */
16101       decl_parm = skip_artificial_parms_for (decl,
16102                                              DECL_ARGUMENTS (decl));
16103       pattern_parm
16104         = skip_artificial_parms_for (code_pattern,
16105                                      DECL_ARGUMENTS (code_pattern));
16106       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16107         {
16108           tree parm_type;
16109           tree attributes;
16110           
16111           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16112             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16113           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16114                               NULL_TREE);
16115           parm_type = type_decays_to (parm_type);
16116           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16117             TREE_TYPE (decl_parm) = parm_type;
16118           attributes = DECL_ATTRIBUTES (pattern_parm);
16119           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16120             {
16121               DECL_ATTRIBUTES (decl_parm) = attributes;
16122               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16123             }
16124           decl_parm = TREE_CHAIN (decl_parm);
16125           pattern_parm = TREE_CHAIN (pattern_parm);
16126         }
16127       /* Merge any parameters that match with the function parameter
16128          pack.  */
16129       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16130         {
16131           int i, len;
16132           tree expanded_types;
16133           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16134              the parameters in this function parameter pack.  */
16135           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16136                                                  args, tf_error, NULL_TREE);
16137           len = TREE_VEC_LENGTH (expanded_types);
16138           for (i = 0; i < len; i++)
16139             {
16140               tree parm_type;
16141               tree attributes;
16142           
16143               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16144                 /* Rename the parameter to include the index.  */
16145                 DECL_NAME (decl_parm) = 
16146                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16147               parm_type = TREE_VEC_ELT (expanded_types, i);
16148               parm_type = type_decays_to (parm_type);
16149               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16150                 TREE_TYPE (decl_parm) = parm_type;
16151               attributes = DECL_ATTRIBUTES (pattern_parm);
16152               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16153                 {
16154                   DECL_ATTRIBUTES (decl_parm) = attributes;
16155                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16156                 }
16157               decl_parm = TREE_CHAIN (decl_parm);
16158             }
16159         }
16160       /* Merge additional specifiers from the CODE_PATTERN.  */
16161       if (DECL_DECLARED_INLINE_P (code_pattern)
16162           && !DECL_DECLARED_INLINE_P (decl))
16163         DECL_DECLARED_INLINE_P (decl) = 1;
16164     }
16165   else if (TREE_CODE (decl) == VAR_DECL)
16166     DECL_INITIAL (decl) =
16167       tsubst_expr (DECL_INITIAL (code_pattern), args,
16168                    tf_error, DECL_TI_TEMPLATE (decl),
16169                    /*integral_constant_expression_p=*/false);
16170   else
16171     gcc_unreachable ();
16172
16173   pop_access_scope (decl);
16174 }
16175
16176 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16177    substituted to get DECL.  */
16178
16179 tree
16180 template_for_substitution (tree decl)
16181 {
16182   tree tmpl = DECL_TI_TEMPLATE (decl);
16183
16184   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16185      for the instantiation.  This is not always the most general
16186      template.  Consider, for example:
16187
16188         template <class T>
16189         struct S { template <class U> void f();
16190                    template <> void f<int>(); };
16191
16192      and an instantiation of S<double>::f<int>.  We want TD to be the
16193      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16194   while (/* An instantiation cannot have a definition, so we need a
16195             more general template.  */
16196          DECL_TEMPLATE_INSTANTIATION (tmpl)
16197            /* We must also deal with friend templates.  Given:
16198
16199                 template <class T> struct S {
16200                   template <class U> friend void f() {};
16201                 };
16202
16203               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16204               so far as the language is concerned, but that's still
16205               where we get the pattern for the instantiation from.  On
16206               other hand, if the definition comes outside the class, say:
16207
16208                 template <class T> struct S {
16209                   template <class U> friend void f();
16210                 };
16211                 template <class U> friend void f() {}
16212
16213               we don't need to look any further.  That's what the check for
16214               DECL_INITIAL is for.  */
16215           || (TREE_CODE (decl) == FUNCTION_DECL
16216               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16217               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16218     {
16219       /* The present template, TD, should not be a definition.  If it
16220          were a definition, we should be using it!  Note that we
16221          cannot restructure the loop to just keep going until we find
16222          a template with a definition, since that might go too far if
16223          a specialization was declared, but not defined.  */
16224       gcc_assert (TREE_CODE (decl) != VAR_DECL
16225                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16226
16227       /* Fetch the more general template.  */
16228       tmpl = DECL_TI_TEMPLATE (tmpl);
16229     }
16230
16231   return tmpl;
16232 }
16233
16234 /* Returns true if we need to instantiate this template instance even if we
16235    know we aren't going to emit it..  */
16236
16237 bool
16238 always_instantiate_p (tree decl)
16239 {
16240   /* We always instantiate inline functions so that we can inline them.  An
16241      explicit instantiation declaration prohibits implicit instantiation of
16242      non-inline functions.  With high levels of optimization, we would
16243      normally inline non-inline functions -- but we're not allowed to do
16244      that for "extern template" functions.  Therefore, we check
16245      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16246   return ((TREE_CODE (decl) == FUNCTION_DECL
16247            && DECL_DECLARED_INLINE_P (decl))
16248           /* And we need to instantiate static data members so that
16249              their initializers are available in integral constant
16250              expressions.  */
16251           || (TREE_CODE (decl) == VAR_DECL
16252               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16253 }
16254
16255 /* Produce the definition of D, a _DECL generated from a template.  If
16256    DEFER_OK is nonzero, then we don't have to actually do the
16257    instantiation now; we just have to do it sometime.  Normally it is
16258    an error if this is an explicit instantiation but D is undefined.
16259    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16260    explicitly instantiated class template.  */
16261
16262 tree
16263 instantiate_decl (tree d, int defer_ok,
16264                   bool expl_inst_class_mem_p)
16265 {
16266   tree tmpl = DECL_TI_TEMPLATE (d);
16267   tree gen_args;
16268   tree args;
16269   tree td;
16270   tree code_pattern;
16271   tree spec;
16272   tree gen_tmpl;
16273   bool pattern_defined;
16274   int need_push;
16275   location_t saved_loc = input_location;
16276   bool external_p;
16277
16278   /* This function should only be used to instantiate templates for
16279      functions and static member variables.  */
16280   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16281               || TREE_CODE (d) == VAR_DECL);
16282
16283   /* Variables are never deferred; if instantiation is required, they
16284      are instantiated right away.  That allows for better code in the
16285      case that an expression refers to the value of the variable --
16286      if the variable has a constant value the referring expression can
16287      take advantage of that fact.  */
16288   if (TREE_CODE (d) == VAR_DECL)
16289     defer_ok = 0;
16290
16291   /* Don't instantiate cloned functions.  Instead, instantiate the
16292      functions they cloned.  */
16293   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16294     d = DECL_CLONED_FUNCTION (d);
16295
16296   if (DECL_TEMPLATE_INSTANTIATED (d)
16297       || DECL_TEMPLATE_SPECIALIZATION (d))
16298     /* D has already been instantiated or explicitly specialized, so
16299        there's nothing for us to do here.
16300
16301        It might seem reasonable to check whether or not D is an explicit
16302        instantiation, and, if so, stop here.  But when an explicit
16303        instantiation is deferred until the end of the compilation,
16304        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16305        the instantiation.  */
16306     return d;
16307
16308   /* Check to see whether we know that this template will be
16309      instantiated in some other file, as with "extern template"
16310      extension.  */
16311   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16312
16313   /* In general, we do not instantiate such templates.  */
16314   if (external_p && !always_instantiate_p (d))
16315     return d;
16316
16317   gen_tmpl = most_general_template (tmpl);
16318   gen_args = DECL_TI_ARGS (d);
16319
16320   if (tmpl != gen_tmpl)
16321     /* We should already have the extra args.  */
16322     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16323                 == TMPL_ARGS_DEPTH (gen_args));
16324   /* And what's in the hash table should match D.  */
16325   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16326               || spec == NULL_TREE);
16327
16328   /* This needs to happen before any tsubsting.  */
16329   if (! push_tinst_level (d))
16330     return d;
16331
16332   timevar_push (TV_PARSE);
16333
16334   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16335      for the instantiation.  */
16336   td = template_for_substitution (d);
16337   code_pattern = DECL_TEMPLATE_RESULT (td);
16338
16339   /* We should never be trying to instantiate a member of a class
16340      template or partial specialization.  */
16341   gcc_assert (d != code_pattern);
16342
16343   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16344       || DECL_TEMPLATE_SPECIALIZATION (td))
16345     /* In the case of a friend template whose definition is provided
16346        outside the class, we may have too many arguments.  Drop the
16347        ones we don't need.  The same is true for specializations.  */
16348     args = get_innermost_template_args
16349       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16350   else
16351     args = gen_args;
16352
16353   if (TREE_CODE (d) == FUNCTION_DECL)
16354     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16355   else
16356     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16357
16358   /* We may be in the middle of deferred access check.  Disable it now.  */
16359   push_deferring_access_checks (dk_no_deferred);
16360
16361   /* Unless an explicit instantiation directive has already determined
16362      the linkage of D, remember that a definition is available for
16363      this entity.  */
16364   if (pattern_defined
16365       && !DECL_INTERFACE_KNOWN (d)
16366       && !DECL_NOT_REALLY_EXTERN (d))
16367     mark_definable (d);
16368
16369   input_location = DECL_SOURCE_LOCATION (d);
16370
16371   /* If D is a member of an explicitly instantiated class template,
16372      and no definition is available, treat it like an implicit
16373      instantiation.  */
16374   if (!pattern_defined && expl_inst_class_mem_p
16375       && DECL_EXPLICIT_INSTANTIATION (d))
16376     {
16377       DECL_NOT_REALLY_EXTERN (d) = 0;
16378       DECL_INTERFACE_KNOWN (d) = 0;
16379       SET_DECL_IMPLICIT_INSTANTIATION (d);
16380     }
16381
16382   /* Recheck the substitutions to obtain any warning messages
16383      about ignoring cv qualifiers.  Don't do this for artificial decls,
16384      as it breaks the context-sensitive substitution for lambda op(). */
16385   if (!defer_ok && !DECL_ARTIFICIAL (d))
16386     {
16387       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16388       tree type = TREE_TYPE (gen);
16389
16390       /* Make sure that we can see identifiers, and compute access
16391          correctly.  D is already the target FUNCTION_DECL with the
16392          right context.  */
16393       push_access_scope (d);
16394
16395       if (TREE_CODE (gen) == FUNCTION_DECL)
16396         {
16397           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16398           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16399                                           d);
16400           /* Don't simply tsubst the function type, as that will give
16401              duplicate warnings about poor parameter qualifications.
16402              The function arguments are the same as the decl_arguments
16403              without the top level cv qualifiers.  */
16404           type = TREE_TYPE (type);
16405         }
16406       tsubst (type, gen_args, tf_warning_or_error, d);
16407
16408       pop_access_scope (d);
16409     }
16410
16411   /* Defer all other templates, unless we have been explicitly
16412      forbidden from doing so.  */
16413   if (/* If there is no definition, we cannot instantiate the
16414          template.  */
16415       ! pattern_defined
16416       /* If it's OK to postpone instantiation, do so.  */
16417       || defer_ok
16418       /* If this is a static data member that will be defined
16419          elsewhere, we don't want to instantiate the entire data
16420          member, but we do want to instantiate the initializer so that
16421          we can substitute that elsewhere.  */
16422       || (external_p && TREE_CODE (d) == VAR_DECL))
16423     {
16424       /* The definition of the static data member is now required so
16425          we must substitute the initializer.  */
16426       if (TREE_CODE (d) == VAR_DECL
16427           && !DECL_INITIAL (d)
16428           && DECL_INITIAL (code_pattern))
16429         {
16430           tree ns;
16431           tree init;
16432
16433           ns = decl_namespace_context (d);
16434           push_nested_namespace (ns);
16435           push_nested_class (DECL_CONTEXT (d));
16436           init = tsubst_expr (DECL_INITIAL (code_pattern),
16437                               args,
16438                               tf_warning_or_error, NULL_TREE,
16439                               /*integral_constant_expression_p=*/false);
16440           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16441                           /*asmspec_tree=*/NULL_TREE,
16442                           LOOKUP_ONLYCONVERTING);
16443           pop_nested_class ();
16444           pop_nested_namespace (ns);
16445         }
16446
16447       /* We restore the source position here because it's used by
16448          add_pending_template.  */
16449       input_location = saved_loc;
16450
16451       if (at_eof && !pattern_defined
16452           && DECL_EXPLICIT_INSTANTIATION (d)
16453           && DECL_NOT_REALLY_EXTERN (d))
16454         /* [temp.explicit]
16455
16456            The definition of a non-exported function template, a
16457            non-exported member function template, or a non-exported
16458            member function or static data member of a class template
16459            shall be present in every translation unit in which it is
16460            explicitly instantiated.  */
16461         permerror (input_location,  "explicit instantiation of %qD "
16462                    "but no definition available", d);
16463
16464       /* ??? Historically, we have instantiated inline functions, even
16465          when marked as "extern template".  */
16466       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16467         add_pending_template (d);
16468       goto out;
16469     }
16470   /* Tell the repository that D is available in this translation unit
16471      -- and see if it is supposed to be instantiated here.  */
16472   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16473     {
16474       /* In a PCH file, despite the fact that the repository hasn't
16475          requested instantiation in the PCH it is still possible that
16476          an instantiation will be required in a file that includes the
16477          PCH.  */
16478       if (pch_file)
16479         add_pending_template (d);
16480       /* Instantiate inline functions so that the inliner can do its
16481          job, even though we'll not be emitting a copy of this
16482          function.  */
16483       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16484         goto out;
16485     }
16486
16487   need_push = !cfun || !global_bindings_p ();
16488   if (need_push)
16489     push_to_top_level ();
16490
16491   /* Mark D as instantiated so that recursive calls to
16492      instantiate_decl do not try to instantiate it again.  */
16493   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16494
16495   /* Regenerate the declaration in case the template has been modified
16496      by a subsequent redeclaration.  */
16497   regenerate_decl_from_template (d, td);
16498
16499   /* We already set the file and line above.  Reset them now in case
16500      they changed as a result of calling regenerate_decl_from_template.  */
16501   input_location = DECL_SOURCE_LOCATION (d);
16502
16503   if (TREE_CODE (d) == VAR_DECL)
16504     {
16505       tree init;
16506
16507       /* Clear out DECL_RTL; whatever was there before may not be right
16508          since we've reset the type of the declaration.  */
16509       SET_DECL_RTL (d, NULL_RTX);
16510       DECL_IN_AGGR_P (d) = 0;
16511
16512       /* The initializer is placed in DECL_INITIAL by
16513          regenerate_decl_from_template.  Pull it out so that
16514          cp_finish_decl can process it.  */
16515       init = DECL_INITIAL (d);
16516       DECL_INITIAL (d) = NULL_TREE;
16517       DECL_INITIALIZED_P (d) = 0;
16518
16519       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16520          initializer.  That function will defer actual emission until
16521          we have a chance to determine linkage.  */
16522       DECL_EXTERNAL (d) = 0;
16523
16524       /* Enter the scope of D so that access-checking works correctly.  */
16525       push_nested_class (DECL_CONTEXT (d));
16526       cp_finish_decl (d, init, false, NULL_TREE, 0);
16527       pop_nested_class ();
16528     }
16529   else if (TREE_CODE (d) == FUNCTION_DECL)
16530     {
16531       htab_t saved_local_specializations;
16532       tree subst_decl;
16533       tree tmpl_parm;
16534       tree spec_parm;
16535
16536       /* Save away the current list, in case we are instantiating one
16537          template from within the body of another.  */
16538       saved_local_specializations = local_specializations;
16539
16540       /* Set up the list of local specializations.  */
16541       local_specializations = htab_create (37,
16542                                            hash_local_specialization,
16543                                            eq_local_specializations,
16544                                            NULL);
16545
16546       /* Set up context.  */
16547       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16548
16549       /* Create substitution entries for the parameters.  */
16550       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16551       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16552       spec_parm = DECL_ARGUMENTS (d);
16553       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16554         {
16555           register_local_specialization (spec_parm, tmpl_parm);
16556           spec_parm = skip_artificial_parms_for (d, spec_parm);
16557           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16558         }
16559       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16560         {
16561           register_local_specialization (spec_parm, tmpl_parm);
16562           tmpl_parm = TREE_CHAIN (tmpl_parm);
16563           spec_parm = TREE_CHAIN (spec_parm);
16564         }
16565       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16566         {
16567           /* Register the (value) argument pack as a specialization of
16568              TMPL_PARM, then move on.  */
16569           tree argpack = make_fnparm_pack (spec_parm);
16570           register_local_specialization (argpack, tmpl_parm);
16571           tmpl_parm = TREE_CHAIN (tmpl_parm);
16572           spec_parm = NULL_TREE;
16573         }
16574       gcc_assert (!spec_parm);
16575
16576       /* Substitute into the body of the function.  */
16577       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16578                    tf_warning_or_error, tmpl,
16579                    /*integral_constant_expression_p=*/false);
16580
16581       /* Set the current input_location to the end of the function
16582          so that finish_function knows where we are.  */
16583       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16584
16585       /* We don't need the local specializations any more.  */
16586       htab_delete (local_specializations);
16587       local_specializations = saved_local_specializations;
16588
16589       /* Finish the function.  */
16590       d = finish_function (0);
16591       expand_or_defer_fn (d);
16592     }
16593
16594   /* We're not deferring instantiation any more.  */
16595   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16596
16597   if (need_push)
16598     pop_from_top_level ();
16599
16600 out:
16601   input_location = saved_loc;
16602   pop_deferring_access_checks ();
16603   pop_tinst_level ();
16604
16605   timevar_pop (TV_PARSE);
16606
16607   return d;
16608 }
16609
16610 /* Run through the list of templates that we wish we could
16611    instantiate, and instantiate any we can.  RETRIES is the
16612    number of times we retry pending template instantiation.  */
16613
16614 void
16615 instantiate_pending_templates (int retries)
16616 {
16617   int reconsider;
16618   location_t saved_loc = input_location;
16619
16620   /* Instantiating templates may trigger vtable generation.  This in turn
16621      may require further template instantiations.  We place a limit here
16622      to avoid infinite loop.  */
16623   if (pending_templates && retries >= max_tinst_depth)
16624     {
16625       tree decl = pending_templates->tinst->decl;
16626
16627       error ("template instantiation depth exceeds maximum of %d"
16628              " instantiating %q+D, possibly from virtual table generation"
16629              " (use -ftemplate-depth-NN to increase the maximum)",
16630              max_tinst_depth, decl);
16631       if (TREE_CODE (decl) == FUNCTION_DECL)
16632         /* Pretend that we defined it.  */
16633         DECL_INITIAL (decl) = error_mark_node;
16634       return;
16635     }
16636
16637   do
16638     {
16639       struct pending_template **t = &pending_templates;
16640       struct pending_template *last = NULL;
16641       reconsider = 0;
16642       while (*t)
16643         {
16644           tree instantiation = reopen_tinst_level ((*t)->tinst);
16645           bool complete = false;
16646
16647           if (TYPE_P (instantiation))
16648             {
16649               tree fn;
16650
16651               if (!COMPLETE_TYPE_P (instantiation))
16652                 {
16653                   instantiate_class_template (instantiation);
16654                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16655                     for (fn = TYPE_METHODS (instantiation);
16656                          fn;
16657                          fn = TREE_CHAIN (fn))
16658                       if (! DECL_ARTIFICIAL (fn))
16659                         instantiate_decl (fn,
16660                                           /*defer_ok=*/0,
16661                                           /*expl_inst_class_mem_p=*/false);
16662                   if (COMPLETE_TYPE_P (instantiation))
16663                     reconsider = 1;
16664                 }
16665
16666               complete = COMPLETE_TYPE_P (instantiation);
16667             }
16668           else
16669             {
16670               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16671                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16672                 {
16673                   instantiation
16674                     = instantiate_decl (instantiation,
16675                                         /*defer_ok=*/0,
16676                                         /*expl_inst_class_mem_p=*/false);
16677                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16678                     reconsider = 1;
16679                 }
16680
16681               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16682                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16683             }
16684
16685           if (complete)
16686             /* If INSTANTIATION has been instantiated, then we don't
16687                need to consider it again in the future.  */
16688             *t = (*t)->next;
16689           else
16690             {
16691               last = *t;
16692               t = &(*t)->next;
16693             }
16694           tinst_depth = 0;
16695           current_tinst_level = NULL;
16696         }
16697       last_pending_template = last;
16698     }
16699   while (reconsider);
16700
16701   input_location = saved_loc;
16702 }
16703
16704 /* Substitute ARGVEC into T, which is a list of initializers for
16705    either base class or a non-static data member.  The TREE_PURPOSEs
16706    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16707    instantiate_decl.  */
16708
16709 static tree
16710 tsubst_initializer_list (tree t, tree argvec)
16711 {
16712   tree inits = NULL_TREE;
16713
16714   for (; t; t = TREE_CHAIN (t))
16715     {
16716       tree decl;
16717       tree init;
16718       tree expanded_bases = NULL_TREE;
16719       tree expanded_arguments = NULL_TREE;
16720       int i, len = 1;
16721
16722       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16723         {
16724           tree expr;
16725           tree arg;
16726
16727           /* Expand the base class expansion type into separate base
16728              classes.  */
16729           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16730                                                  tf_warning_or_error,
16731                                                  NULL_TREE);
16732           if (expanded_bases == error_mark_node)
16733             continue;
16734           
16735           /* We'll be building separate TREE_LISTs of arguments for
16736              each base.  */
16737           len = TREE_VEC_LENGTH (expanded_bases);
16738           expanded_arguments = make_tree_vec (len);
16739           for (i = 0; i < len; i++)
16740             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16741
16742           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16743              expand each argument in the TREE_VALUE of t.  */
16744           expr = make_node (EXPR_PACK_EXPANSION);
16745           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16746             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16747
16748           if (TREE_VALUE (t) == void_type_node)
16749             /* VOID_TYPE_NODE is used to indicate
16750                value-initialization.  */
16751             {
16752               for (i = 0; i < len; i++)
16753                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16754             }
16755           else
16756             {
16757               /* Substitute parameter packs into each argument in the
16758                  TREE_LIST.  */
16759               in_base_initializer = 1;
16760               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16761                 {
16762                   tree expanded_exprs;
16763
16764                   /* Expand the argument.  */
16765                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16766                   expanded_exprs 
16767                     = tsubst_pack_expansion (expr, argvec,
16768                                              tf_warning_or_error,
16769                                              NULL_TREE);
16770                   if (expanded_exprs == error_mark_node)
16771                     continue;
16772
16773                   /* Prepend each of the expanded expressions to the
16774                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16775                   for (i = 0; i < len; i++)
16776                     {
16777                       TREE_VEC_ELT (expanded_arguments, i) = 
16778                         tree_cons (NULL_TREE, 
16779                                    TREE_VEC_ELT (expanded_exprs, i),
16780                                    TREE_VEC_ELT (expanded_arguments, i));
16781                     }
16782                 }
16783               in_base_initializer = 0;
16784
16785               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16786                  since we built them backwards.  */
16787               for (i = 0; i < len; i++)
16788                 {
16789                   TREE_VEC_ELT (expanded_arguments, i) = 
16790                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16791                 }
16792             }
16793         }
16794
16795       for (i = 0; i < len; ++i)
16796         {
16797           if (expanded_bases)
16798             {
16799               decl = TREE_VEC_ELT (expanded_bases, i);
16800               decl = expand_member_init (decl);
16801               init = TREE_VEC_ELT (expanded_arguments, i);
16802             }
16803           else
16804             {
16805               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16806                                   tf_warning_or_error, NULL_TREE);
16807
16808               decl = expand_member_init (decl);
16809               if (decl && !DECL_P (decl))
16810                 in_base_initializer = 1;
16811
16812               init = tsubst_expr (TREE_VALUE (t), argvec, 
16813                                   tf_warning_or_error, NULL_TREE,
16814                                   /*integral_constant_expression_p=*/false);
16815               in_base_initializer = 0;
16816             }
16817
16818           if (decl)
16819             {
16820               init = build_tree_list (decl, init);
16821               TREE_CHAIN (init) = inits;
16822               inits = init;
16823             }
16824         }
16825     }
16826   return inits;
16827 }
16828
16829 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16830
16831 static void
16832 set_current_access_from_decl (tree decl)
16833 {
16834   if (TREE_PRIVATE (decl))
16835     current_access_specifier = access_private_node;
16836   else if (TREE_PROTECTED (decl))
16837     current_access_specifier = access_protected_node;
16838   else
16839     current_access_specifier = access_public_node;
16840 }
16841
16842 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16843    is the instantiation (which should have been created with
16844    start_enum) and ARGS are the template arguments to use.  */
16845
16846 static void
16847 tsubst_enum (tree tag, tree newtag, tree args)
16848 {
16849   tree e;
16850
16851   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16852     {
16853       tree value;
16854       tree decl;
16855
16856       decl = TREE_VALUE (e);
16857       /* Note that in a template enum, the TREE_VALUE is the
16858          CONST_DECL, not the corresponding INTEGER_CST.  */
16859       value = tsubst_expr (DECL_INITIAL (decl),
16860                            args, tf_warning_or_error, NULL_TREE,
16861                            /*integral_constant_expression_p=*/true);
16862
16863       /* Give this enumeration constant the correct access.  */
16864       set_current_access_from_decl (decl);
16865
16866       /* Actually build the enumerator itself.  */
16867       build_enumerator (DECL_NAME (decl), value, newtag);
16868     }
16869
16870   finish_enum (newtag);
16871   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16872     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16873 }
16874
16875 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16876    its type -- but without substituting the innermost set of template
16877    arguments.  So, innermost set of template parameters will appear in
16878    the type.  */
16879
16880 tree
16881 get_mostly_instantiated_function_type (tree decl)
16882 {
16883   tree fn_type;
16884   tree tmpl;
16885   tree targs;
16886   tree tparms;
16887   int parm_depth;
16888
16889   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16890   targs = DECL_TI_ARGS (decl);
16891   tparms = DECL_TEMPLATE_PARMS (tmpl);
16892   parm_depth = TMPL_PARMS_DEPTH (tparms);
16893
16894   /* There should be as many levels of arguments as there are levels
16895      of parameters.  */
16896   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16897
16898   fn_type = TREE_TYPE (tmpl);
16899
16900   if (parm_depth == 1)
16901     /* No substitution is necessary.  */
16902     ;
16903   else
16904     {
16905       int i, save_access_control;
16906       tree partial_args;
16907
16908       /* Replace the innermost level of the TARGS with NULL_TREEs to
16909          let tsubst know not to substitute for those parameters.  */
16910       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16911       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16912         SET_TMPL_ARGS_LEVEL (partial_args, i,
16913                              TMPL_ARGS_LEVEL (targs, i));
16914       SET_TMPL_ARGS_LEVEL (partial_args,
16915                            TMPL_ARGS_DEPTH (targs),
16916                            make_tree_vec (DECL_NTPARMS (tmpl)));
16917
16918       /* Disable access control as this function is used only during
16919          name-mangling.  */
16920       save_access_control = flag_access_control;
16921       flag_access_control = 0;
16922
16923       ++processing_template_decl;
16924       /* Now, do the (partial) substitution to figure out the
16925          appropriate function type.  */
16926       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16927       --processing_template_decl;
16928
16929       /* Substitute into the template parameters to obtain the real
16930          innermost set of parameters.  This step is important if the
16931          innermost set of template parameters contains value
16932          parameters whose types depend on outer template parameters.  */
16933       TREE_VEC_LENGTH (partial_args)--;
16934       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16935
16936       flag_access_control = save_access_control;
16937     }
16938
16939   return fn_type;
16940 }
16941
16942 /* Return truthvalue if we're processing a template different from
16943    the last one involved in diagnostics.  */
16944 int
16945 problematic_instantiation_changed (void)
16946 {
16947   return last_template_error_tick != tinst_level_tick;
16948 }
16949
16950 /* Remember current template involved in diagnostics.  */
16951 void
16952 record_last_problematic_instantiation (void)
16953 {
16954   last_template_error_tick = tinst_level_tick;
16955 }
16956
16957 struct tinst_level *
16958 current_instantiation (void)
16959 {
16960   return current_tinst_level;
16961 }
16962
16963 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16964    type. Return zero for ok, nonzero for disallowed. Issue error and
16965    warning messages under control of COMPLAIN.  */
16966
16967 static int
16968 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16969 {
16970   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16971     return 0;
16972   else if (POINTER_TYPE_P (type))
16973     return 0;
16974   else if (TYPE_PTR_TO_MEMBER_P (type))
16975     return 0;
16976   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16977     return 0;
16978   else if (TREE_CODE (type) == TYPENAME_TYPE)
16979     return 0;
16980
16981   if (complain & tf_error)
16982     error ("%q#T is not a valid type for a template constant parameter", type);
16983   return 1;
16984 }
16985
16986 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16987    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16988
16989 static bool
16990 dependent_type_p_r (tree type)
16991 {
16992   tree scope;
16993
16994   /* [temp.dep.type]
16995
16996      A type is dependent if it is:
16997
16998      -- a template parameter. Template template parameters are types
16999         for us (since TYPE_P holds true for them) so we handle
17000         them here.  */
17001   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17002       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17003     return true;
17004   /* -- a qualified-id with a nested-name-specifier which contains a
17005         class-name that names a dependent type or whose unqualified-id
17006         names a dependent type.  */
17007   if (TREE_CODE (type) == TYPENAME_TYPE)
17008     return true;
17009   /* -- a cv-qualified type where the cv-unqualified type is
17010         dependent.  */
17011   type = TYPE_MAIN_VARIANT (type);
17012   /* -- a compound type constructed from any dependent type.  */
17013   if (TYPE_PTR_TO_MEMBER_P (type))
17014     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17015             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17016                                            (type)));
17017   else if (TREE_CODE (type) == POINTER_TYPE
17018            || TREE_CODE (type) == REFERENCE_TYPE)
17019     return dependent_type_p (TREE_TYPE (type));
17020   else if (TREE_CODE (type) == FUNCTION_TYPE
17021            || TREE_CODE (type) == METHOD_TYPE)
17022     {
17023       tree arg_type;
17024
17025       if (dependent_type_p (TREE_TYPE (type)))
17026         return true;
17027       for (arg_type = TYPE_ARG_TYPES (type);
17028            arg_type;
17029            arg_type = TREE_CHAIN (arg_type))
17030         if (dependent_type_p (TREE_VALUE (arg_type)))
17031           return true;
17032       return false;
17033     }
17034   /* -- an array type constructed from any dependent type or whose
17035         size is specified by a constant expression that is
17036         value-dependent.  */
17037   if (TREE_CODE (type) == ARRAY_TYPE)
17038     {
17039       if (TYPE_DOMAIN (type)
17040           && dependent_type_p (TYPE_DOMAIN (type)))
17041         return true;
17042       return dependent_type_p (TREE_TYPE (type));
17043     }
17044   else if (TREE_CODE (type) == INTEGER_TYPE
17045            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17046     {
17047       /* If this is the TYPE_DOMAIN of an array type, consider it
17048          dependent.  We already checked for value-dependence in
17049          compute_array_index_type.  */
17050       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17051     }
17052
17053   /* -- a template-id in which either the template name is a template
17054      parameter ...  */
17055   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17056     return true;
17057   /* ... or any of the template arguments is a dependent type or
17058         an expression that is type-dependent or value-dependent.  */
17059   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17060            && (any_dependent_template_arguments_p
17061                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17062     return true;
17063
17064   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17065      argument of the `typeof' expression is not type-dependent, then
17066      it should already been have resolved.  */
17067   if (TREE_CODE (type) == TYPEOF_TYPE
17068       || TREE_CODE (type) == DECLTYPE_TYPE)
17069     return true;
17070
17071   /* A template argument pack is dependent if any of its packed
17072      arguments are.  */
17073   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17074     {
17075       tree args = ARGUMENT_PACK_ARGS (type);
17076       int i, len = TREE_VEC_LENGTH (args);
17077       for (i = 0; i < len; ++i)
17078         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17079           return true;
17080     }
17081
17082   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17083      be template parameters.  */
17084   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17085     return true;
17086
17087   /* The standard does not specifically mention types that are local
17088      to template functions or local classes, but they should be
17089      considered dependent too.  For example:
17090
17091        template <int I> void f() {
17092          enum E { a = I };
17093          S<sizeof (E)> s;
17094        }
17095
17096      The size of `E' cannot be known until the value of `I' has been
17097      determined.  Therefore, `E' must be considered dependent.  */
17098   scope = TYPE_CONTEXT (type);
17099   if (scope && TYPE_P (scope))
17100     return dependent_type_p (scope);
17101   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17102     return type_dependent_expression_p (scope);
17103
17104   /* Other types are non-dependent.  */
17105   return false;
17106 }
17107
17108 /* Returns TRUE if TYPE is dependent, in the sense of
17109    [temp.dep.type].  */
17110
17111 bool
17112 dependent_type_p (tree type)
17113 {
17114   /* If there are no template parameters in scope, then there can't be
17115      any dependent types.  */
17116   if (!processing_template_decl)
17117     {
17118       /* If we are not processing a template, then nobody should be
17119          providing us with a dependent type.  */
17120       gcc_assert (type);
17121       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17122       return false;
17123     }
17124
17125   /* If the type is NULL, we have not computed a type for the entity
17126      in question; in that case, the type is dependent.  */
17127   if (!type)
17128     return true;
17129
17130   /* Erroneous types can be considered non-dependent.  */
17131   if (type == error_mark_node)
17132     return false;
17133
17134   /* If we have not already computed the appropriate value for TYPE,
17135      do so now.  */
17136   if (!TYPE_DEPENDENT_P_VALID (type))
17137     {
17138       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17139       TYPE_DEPENDENT_P_VALID (type) = 1;
17140     }
17141
17142   return TYPE_DEPENDENT_P (type);
17143 }
17144
17145 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17146    lookup.  In other words, a dependent type that is not the current
17147    instantiation.  */
17148
17149 bool
17150 dependent_scope_p (tree scope)
17151 {
17152   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17153           && !currently_open_class (scope));
17154 }
17155
17156 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17157
17158 static bool
17159 dependent_scope_ref_p (tree expression, bool criterion (tree))
17160 {
17161   tree scope;
17162   tree name;
17163
17164   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17165
17166   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17167     return true;
17168
17169   scope = TREE_OPERAND (expression, 0);
17170   name = TREE_OPERAND (expression, 1);
17171
17172   /* [temp.dep.expr]
17173
17174      An id-expression is type-dependent if it contains a
17175      nested-name-specifier that contains a class-name that names a
17176      dependent type.  */
17177   /* The suggested resolution to Core Issue 224 implies that if the
17178      qualifying type is the current class, then we must peek
17179      inside it.  */
17180   if (DECL_P (name)
17181       && currently_open_class (scope)
17182       && !criterion (name))
17183     return false;
17184   if (dependent_type_p (scope))
17185     return true;
17186
17187   return false;
17188 }
17189
17190 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17191    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17192    expression.  */
17193
17194 bool
17195 value_dependent_expression_p (tree expression)
17196 {
17197   if (!processing_template_decl)
17198     return false;
17199
17200   /* A name declared with a dependent type.  */
17201   if (DECL_P (expression) && type_dependent_expression_p (expression))
17202     return true;
17203
17204   switch (TREE_CODE (expression))
17205     {
17206     case IDENTIFIER_NODE:
17207       /* A name that has not been looked up -- must be dependent.  */
17208       return true;
17209
17210     case TEMPLATE_PARM_INDEX:
17211       /* A non-type template parm.  */
17212       return true;
17213
17214     case CONST_DECL:
17215       /* A non-type template parm.  */
17216       if (DECL_TEMPLATE_PARM_P (expression))
17217         return true;
17218       return value_dependent_expression_p (DECL_INITIAL (expression));
17219
17220     case VAR_DECL:
17221        /* A constant with integral or enumeration type and is initialized
17222           with an expression that is value-dependent.  */
17223       if (DECL_INITIAL (expression)
17224           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17225           && value_dependent_expression_p (DECL_INITIAL (expression)))
17226         return true;
17227       return false;
17228
17229     case DYNAMIC_CAST_EXPR:
17230     case STATIC_CAST_EXPR:
17231     case CONST_CAST_EXPR:
17232     case REINTERPRET_CAST_EXPR:
17233     case CAST_EXPR:
17234       /* These expressions are value-dependent if the type to which
17235          the cast occurs is dependent or the expression being casted
17236          is value-dependent.  */
17237       {
17238         tree type = TREE_TYPE (expression);
17239
17240         if (dependent_type_p (type))
17241           return true;
17242
17243         /* A functional cast has a list of operands.  */
17244         expression = TREE_OPERAND (expression, 0);
17245         if (!expression)
17246           {
17247             /* If there are no operands, it must be an expression such
17248                as "int()". This should not happen for aggregate types
17249                because it would form non-constant expressions.  */
17250             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17251
17252             return false;
17253           }
17254
17255         if (TREE_CODE (expression) == TREE_LIST)
17256           return any_value_dependent_elements_p (expression);
17257
17258         return value_dependent_expression_p (expression);
17259       }
17260
17261     case SIZEOF_EXPR:
17262     case ALIGNOF_EXPR:
17263       /* A `sizeof' expression is value-dependent if the operand is
17264          type-dependent or is a pack expansion.  */
17265       expression = TREE_OPERAND (expression, 0);
17266       if (PACK_EXPANSION_P (expression))
17267         return true;
17268       else if (TYPE_P (expression))
17269         return dependent_type_p (expression);
17270       return type_dependent_expression_p (expression);
17271
17272     case SCOPE_REF:
17273       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17274
17275     case COMPONENT_REF:
17276       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17277               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17278
17279     case CALL_EXPR:
17280       /* A CALL_EXPR may appear in a constant expression if it is a
17281          call to a builtin function, e.g., __builtin_constant_p.  All
17282          such calls are value-dependent.  */
17283       return true;
17284
17285     case NONTYPE_ARGUMENT_PACK:
17286       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17287          is value-dependent.  */
17288       {
17289         tree values = ARGUMENT_PACK_ARGS (expression);
17290         int i, len = TREE_VEC_LENGTH (values);
17291         
17292         for (i = 0; i < len; ++i)
17293           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17294             return true;
17295         
17296         return false;
17297       }
17298
17299     case TRAIT_EXPR:
17300       {
17301         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17302         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17303                 || (type2 ? dependent_type_p (type2) : false));
17304       }
17305
17306     case MODOP_EXPR:
17307       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17308               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17309
17310     default:
17311       /* A constant expression is value-dependent if any subexpression is
17312          value-dependent.  */
17313       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17314         {
17315         case tcc_reference:
17316         case tcc_unary:
17317           return (value_dependent_expression_p
17318                   (TREE_OPERAND (expression, 0)));
17319
17320         case tcc_comparison:
17321         case tcc_binary:
17322           return ((value_dependent_expression_p
17323                    (TREE_OPERAND (expression, 0)))
17324                   || (value_dependent_expression_p
17325                       (TREE_OPERAND (expression, 1))));
17326
17327         case tcc_expression:
17328         case tcc_vl_exp:
17329           {
17330             int i;
17331             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17332               /* In some cases, some of the operands may be missing.
17333                  (For example, in the case of PREDECREMENT_EXPR, the
17334                  amount to increment by may be missing.)  That doesn't
17335                  make the expression dependent.  */
17336               if (TREE_OPERAND (expression, i)
17337                   && (value_dependent_expression_p
17338                       (TREE_OPERAND (expression, i))))
17339                 return true;
17340             return false;
17341           }
17342
17343         default:
17344           break;
17345         }
17346     }
17347
17348   /* The expression is not value-dependent.  */
17349   return false;
17350 }
17351
17352 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17353    [temp.dep.expr].  */
17354
17355 bool
17356 type_dependent_expression_p (tree expression)
17357 {
17358   if (!processing_template_decl)
17359     return false;
17360
17361   if (expression == error_mark_node)
17362     return false;
17363
17364   /* An unresolved name is always dependent.  */
17365   if (TREE_CODE (expression) == IDENTIFIER_NODE
17366       || TREE_CODE (expression) == USING_DECL)
17367     return true;
17368
17369   /* Some expression forms are never type-dependent.  */
17370   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17371       || TREE_CODE (expression) == SIZEOF_EXPR
17372       || TREE_CODE (expression) == ALIGNOF_EXPR
17373       || TREE_CODE (expression) == TRAIT_EXPR
17374       || TREE_CODE (expression) == TYPEID_EXPR
17375       || TREE_CODE (expression) == DELETE_EXPR
17376       || TREE_CODE (expression) == VEC_DELETE_EXPR
17377       || TREE_CODE (expression) == THROW_EXPR)
17378     return false;
17379
17380   /* The types of these expressions depends only on the type to which
17381      the cast occurs.  */
17382   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17383       || TREE_CODE (expression) == STATIC_CAST_EXPR
17384       || TREE_CODE (expression) == CONST_CAST_EXPR
17385       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17386       || TREE_CODE (expression) == CAST_EXPR)
17387     return dependent_type_p (TREE_TYPE (expression));
17388
17389   /* The types of these expressions depends only on the type created
17390      by the expression.  */
17391   if (TREE_CODE (expression) == NEW_EXPR
17392       || TREE_CODE (expression) == VEC_NEW_EXPR)
17393     {
17394       /* For NEW_EXPR tree nodes created inside a template, either
17395          the object type itself or a TREE_LIST may appear as the
17396          operand 1.  */
17397       tree type = TREE_OPERAND (expression, 1);
17398       if (TREE_CODE (type) == TREE_LIST)
17399         /* This is an array type.  We need to check array dimensions
17400            as well.  */
17401         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17402                || value_dependent_expression_p
17403                     (TREE_OPERAND (TREE_VALUE (type), 1));
17404       else
17405         return dependent_type_p (type);
17406     }
17407
17408   if (TREE_CODE (expression) == SCOPE_REF
17409       && dependent_scope_ref_p (expression,
17410                                 type_dependent_expression_p))
17411     return true;
17412
17413   if (TREE_CODE (expression) == FUNCTION_DECL
17414       && DECL_LANG_SPECIFIC (expression)
17415       && DECL_TEMPLATE_INFO (expression)
17416       && (any_dependent_template_arguments_p
17417           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17418     return true;
17419
17420   if (TREE_CODE (expression) == TEMPLATE_DECL
17421       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17422     return false;
17423
17424   if (TREE_CODE (expression) == STMT_EXPR)
17425     expression = stmt_expr_value_expr (expression);
17426
17427   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17428     {
17429       tree elt;
17430       unsigned i;
17431
17432       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17433         {
17434           if (type_dependent_expression_p (elt))
17435             return true;
17436         }
17437       return false;
17438     }
17439
17440   if (TREE_TYPE (expression) == unknown_type_node)
17441     {
17442       if (TREE_CODE (expression) == ADDR_EXPR)
17443         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17444       if (TREE_CODE (expression) == COMPONENT_REF
17445           || TREE_CODE (expression) == OFFSET_REF)
17446         {
17447           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17448             return true;
17449           expression = TREE_OPERAND (expression, 1);
17450           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17451             return false;
17452         }
17453       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17454       if (TREE_CODE (expression) == SCOPE_REF)
17455         return false;
17456
17457       if (TREE_CODE (expression) == BASELINK)
17458         expression = BASELINK_FUNCTIONS (expression);
17459
17460       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17461         {
17462           if (any_dependent_template_arguments_p
17463               (TREE_OPERAND (expression, 1)))
17464             return true;
17465           expression = TREE_OPERAND (expression, 0);
17466         }
17467       gcc_assert (TREE_CODE (expression) == OVERLOAD
17468                   || TREE_CODE (expression) == FUNCTION_DECL);
17469
17470       while (expression)
17471         {
17472           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17473             return true;
17474           expression = OVL_NEXT (expression);
17475         }
17476       return false;
17477     }
17478
17479   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17480
17481   return (dependent_type_p (TREE_TYPE (expression)));
17482 }
17483
17484 /* Like type_dependent_expression_p, but it also works while not processing
17485    a template definition, i.e. during substitution or mangling.  */
17486
17487 bool
17488 type_dependent_expression_p_push (tree expr)
17489 {
17490   bool b;
17491   ++processing_template_decl;
17492   b = type_dependent_expression_p (expr);
17493   --processing_template_decl;
17494   return b;
17495 }
17496
17497 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17498
17499 bool
17500 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17501 {
17502   unsigned int i;
17503   tree arg;
17504
17505   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17506     {
17507       if (type_dependent_expression_p (arg))
17508         return true;
17509     }
17510   return false;
17511 }
17512
17513 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17514    expressions) contains any value-dependent expressions.  */
17515
17516 bool
17517 any_value_dependent_elements_p (const_tree list)
17518 {
17519   for (; list; list = TREE_CHAIN (list))
17520     if (value_dependent_expression_p (TREE_VALUE (list)))
17521       return true;
17522
17523   return false;
17524 }
17525
17526 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17527
17528 bool
17529 dependent_template_arg_p (tree arg)
17530 {
17531   if (!processing_template_decl)
17532     return false;
17533
17534   if (TREE_CODE (arg) == TEMPLATE_DECL
17535       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17536     return dependent_template_p (arg);
17537   else if (ARGUMENT_PACK_P (arg))
17538     {
17539       tree args = ARGUMENT_PACK_ARGS (arg);
17540       int i, len = TREE_VEC_LENGTH (args);
17541       for (i = 0; i < len; ++i)
17542         {
17543           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17544             return true;
17545         }
17546
17547       return false;
17548     }
17549   else if (TYPE_P (arg))
17550     return dependent_type_p (arg);
17551   else
17552     return (type_dependent_expression_p (arg)
17553             || value_dependent_expression_p (arg));
17554 }
17555
17556 /* Returns true if ARGS (a collection of template arguments) contains
17557    any types that require structural equality testing.  */
17558
17559 bool
17560 any_template_arguments_need_structural_equality_p (tree args)
17561 {
17562   int i;
17563   int j;
17564
17565   if (!args)
17566     return false;
17567   if (args == error_mark_node)
17568     return true;
17569
17570   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17571     {
17572       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17573       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17574         {
17575           tree arg = TREE_VEC_ELT (level, j);
17576           tree packed_args = NULL_TREE;
17577           int k, len = 1;
17578
17579           if (ARGUMENT_PACK_P (arg))
17580             {
17581               /* Look inside the argument pack.  */
17582               packed_args = ARGUMENT_PACK_ARGS (arg);
17583               len = TREE_VEC_LENGTH (packed_args);
17584             }
17585
17586           for (k = 0; k < len; ++k)
17587             {
17588               if (packed_args)
17589                 arg = TREE_VEC_ELT (packed_args, k);
17590
17591               if (error_operand_p (arg))
17592                 return true;
17593               else if (TREE_CODE (arg) == TEMPLATE_DECL
17594                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17595                 continue;
17596               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17597                 return true;
17598               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17599                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17600                 return true;
17601             }
17602         }
17603     }
17604
17605   return false;
17606 }
17607
17608 /* Returns true if ARGS (a collection of template arguments) contains
17609    any dependent arguments.  */
17610
17611 bool
17612 any_dependent_template_arguments_p (const_tree args)
17613 {
17614   int i;
17615   int j;
17616
17617   if (!args)
17618     return false;
17619   if (args == error_mark_node)
17620     return true;
17621
17622   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17623     {
17624       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17625       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17626         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17627           return true;
17628     }
17629
17630   return false;
17631 }
17632
17633 /* Returns TRUE if the template TMPL is dependent.  */
17634
17635 bool
17636 dependent_template_p (tree tmpl)
17637 {
17638   if (TREE_CODE (tmpl) == OVERLOAD)
17639     {
17640       while (tmpl)
17641         {
17642           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17643             return true;
17644           tmpl = OVL_CHAIN (tmpl);
17645         }
17646       return false;
17647     }
17648
17649   /* Template template parameters are dependent.  */
17650   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17651       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17652     return true;
17653   /* So are names that have not been looked up.  */
17654   if (TREE_CODE (tmpl) == SCOPE_REF
17655       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17656     return true;
17657   /* So are member templates of dependent classes.  */
17658   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17659     return dependent_type_p (DECL_CONTEXT (tmpl));
17660   return false;
17661 }
17662
17663 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17664
17665 bool
17666 dependent_template_id_p (tree tmpl, tree args)
17667 {
17668   return (dependent_template_p (tmpl)
17669           || any_dependent_template_arguments_p (args));
17670 }
17671
17672 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17673    is dependent.  */
17674
17675 bool
17676 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17677 {
17678   int i;
17679
17680   if (!processing_template_decl)
17681     return false;
17682
17683   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17684     {
17685       tree decl = TREE_VEC_ELT (declv, i);
17686       tree init = TREE_VEC_ELT (initv, i);
17687       tree cond = TREE_VEC_ELT (condv, i);
17688       tree incr = TREE_VEC_ELT (incrv, i);
17689
17690       if (type_dependent_expression_p (decl))
17691         return true;
17692
17693       if (init && type_dependent_expression_p (init))
17694         return true;
17695
17696       if (type_dependent_expression_p (cond))
17697         return true;
17698
17699       if (COMPARISON_CLASS_P (cond)
17700           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17701               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17702         return true;
17703
17704       if (TREE_CODE (incr) == MODOP_EXPR)
17705         {
17706           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17707               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17708             return true;
17709         }
17710       else if (type_dependent_expression_p (incr))
17711         return true;
17712       else if (TREE_CODE (incr) == MODIFY_EXPR)
17713         {
17714           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17715             return true;
17716           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17717             {
17718               tree t = TREE_OPERAND (incr, 1);
17719               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17720                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17721                 return true;
17722             }
17723         }
17724     }
17725
17726   return false;
17727 }
17728
17729 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17730    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17731    no such TYPE can be found.  Note that this function peers inside
17732    uninstantiated templates and therefore should be used only in
17733    extremely limited situations.  ONLY_CURRENT_P restricts this
17734    peering to the currently open classes hierarchy (which is required
17735    when comparing types).  */
17736
17737 tree
17738 resolve_typename_type (tree type, bool only_current_p)
17739 {
17740   tree scope;
17741   tree name;
17742   tree decl;
17743   int quals;
17744   tree pushed_scope;
17745   tree result;
17746
17747   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17748
17749   scope = TYPE_CONTEXT (type);
17750   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17751      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17752      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17753      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17754      identifier  of the TYPENAME_TYPE anymore.
17755      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17756      TYPENAME_TYPE instead, we avoid messing up with a possible
17757      typedef variant case.  */
17758   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17759
17760   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17761      it first before we can figure out what NAME refers to.  */
17762   if (TREE_CODE (scope) == TYPENAME_TYPE)
17763     scope = resolve_typename_type (scope, only_current_p);
17764   /* If we don't know what SCOPE refers to, then we cannot resolve the
17765      TYPENAME_TYPE.  */
17766   if (TREE_CODE (scope) == TYPENAME_TYPE)
17767     return type;
17768   /* If the SCOPE is a template type parameter, we have no way of
17769      resolving the name.  */
17770   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17771     return type;
17772   /* If the SCOPE is not the current instantiation, there's no reason
17773      to look inside it.  */
17774   if (only_current_p && !currently_open_class (scope))
17775     return type;
17776   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17777   if (typedef_variant_p (type))
17778     return type;
17779   /* If SCOPE isn't the template itself, it will not have a valid
17780      TYPE_FIELDS list.  */
17781   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17782     /* scope is either the template itself or a compatible instantiation
17783        like X<T>, so look up the name in the original template.  */
17784     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17785   else
17786     /* scope is a partial instantiation, so we can't do the lookup or we
17787        will lose the template arguments.  */
17788     return type;
17789   /* Enter the SCOPE so that name lookup will be resolved as if we
17790      were in the class definition.  In particular, SCOPE will no
17791      longer be considered a dependent type.  */
17792   pushed_scope = push_scope (scope);
17793   /* Look up the declaration.  */
17794   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17795
17796   result = NULL_TREE;
17797   
17798   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17799      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17800   if (!decl)
17801     /*nop*/;
17802   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17803            && TREE_CODE (decl) == TYPE_DECL)
17804     {
17805       result = TREE_TYPE (decl);
17806       if (result == error_mark_node)
17807         result = NULL_TREE;
17808     }
17809   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17810            && DECL_CLASS_TEMPLATE_P (decl))
17811     {
17812       tree tmpl;
17813       tree args;
17814       /* Obtain the template and the arguments.  */
17815       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17816       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17817       /* Instantiate the template.  */
17818       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17819                                       /*entering_scope=*/0,
17820                                       tf_error | tf_user);
17821       if (result == error_mark_node)
17822         result = NULL_TREE;
17823     }
17824   
17825   /* Leave the SCOPE.  */
17826   if (pushed_scope)
17827     pop_scope (pushed_scope);
17828
17829   /* If we failed to resolve it, return the original typename.  */
17830   if (!result)
17831     return type;
17832   
17833   /* If lookup found a typename type, resolve that too.  */
17834   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17835     {
17836       /* Ill-formed programs can cause infinite recursion here, so we
17837          must catch that.  */
17838       TYPENAME_IS_RESOLVING_P (type) = 1;
17839       result = resolve_typename_type (result, only_current_p);
17840       TYPENAME_IS_RESOLVING_P (type) = 0;
17841     }
17842   
17843   /* Qualify the resulting type.  */
17844   quals = cp_type_quals (type);
17845   if (quals)
17846     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17847
17848   return result;
17849 }
17850
17851 /* EXPR is an expression which is not type-dependent.  Return a proxy
17852    for EXPR that can be used to compute the types of larger
17853    expressions containing EXPR.  */
17854
17855 tree
17856 build_non_dependent_expr (tree expr)
17857 {
17858   tree inner_expr;
17859
17860   /* Preserve null pointer constants so that the type of things like
17861      "p == 0" where "p" is a pointer can be determined.  */
17862   if (null_ptr_cst_p (expr))
17863     return expr;
17864   /* Preserve OVERLOADs; the functions must be available to resolve
17865      types.  */
17866   inner_expr = expr;
17867   if (TREE_CODE (inner_expr) == STMT_EXPR)
17868     inner_expr = stmt_expr_value_expr (inner_expr);
17869   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17870     inner_expr = TREE_OPERAND (inner_expr, 0);
17871   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17872     inner_expr = TREE_OPERAND (inner_expr, 1);
17873   if (is_overloaded_fn (inner_expr)
17874       || TREE_CODE (inner_expr) == OFFSET_REF)
17875     return expr;
17876   /* There is no need to return a proxy for a variable.  */
17877   if (TREE_CODE (expr) == VAR_DECL)
17878     return expr;
17879   /* Preserve string constants; conversions from string constants to
17880      "char *" are allowed, even though normally a "const char *"
17881      cannot be used to initialize a "char *".  */
17882   if (TREE_CODE (expr) == STRING_CST)
17883     return expr;
17884   /* Preserve arithmetic constants, as an optimization -- there is no
17885      reason to create a new node.  */
17886   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17887     return expr;
17888   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17889      There is at least one place where we want to know that a
17890      particular expression is a throw-expression: when checking a ?:
17891      expression, there are special rules if the second or third
17892      argument is a throw-expression.  */
17893   if (TREE_CODE (expr) == THROW_EXPR)
17894     return expr;
17895
17896   if (TREE_CODE (expr) == COND_EXPR)
17897     return build3 (COND_EXPR,
17898                    TREE_TYPE (expr),
17899                    TREE_OPERAND (expr, 0),
17900                    (TREE_OPERAND (expr, 1)
17901                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17902                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17903                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17904   if (TREE_CODE (expr) == COMPOUND_EXPR
17905       && !COMPOUND_EXPR_OVERLOADED (expr))
17906     return build2 (COMPOUND_EXPR,
17907                    TREE_TYPE (expr),
17908                    TREE_OPERAND (expr, 0),
17909                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17910
17911   /* If the type is unknown, it can't really be non-dependent */
17912   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17913
17914   /* Otherwise, build a NON_DEPENDENT_EXPR.
17915
17916      REFERENCE_TYPEs are not stripped for expressions in templates
17917      because doing so would play havoc with mangling.  Consider, for
17918      example:
17919
17920        template <typename T> void f<T& g>() { g(); }
17921
17922      In the body of "f", the expression for "g" will have
17923      REFERENCE_TYPE, even though the standard says that it should
17924      not.  The reason is that we must preserve the syntactic form of
17925      the expression so that mangling (say) "f<g>" inside the body of
17926      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17927      stripped here.  */
17928   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17929 }
17930
17931 /* ARGS is a vector of expressions as arguments to a function call.
17932    Replace the arguments with equivalent non-dependent expressions.
17933    This modifies ARGS in place.  */
17934
17935 void
17936 make_args_non_dependent (VEC(tree,gc) *args)
17937 {
17938   unsigned int ix;
17939   tree arg;
17940
17941   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17942     {
17943       tree newarg = build_non_dependent_expr (arg);
17944       if (newarg != arg)
17945         VEC_replace (tree, args, ix, newarg);
17946     }
17947 }
17948
17949 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17950    with a level one deeper than the actual template parms.  */
17951
17952 tree
17953 make_auto (void)
17954 {
17955   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
17956   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17957                                TYPE_DECL, get_identifier ("auto"), au);
17958   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17959   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17960     (0, processing_template_decl + 1, processing_template_decl + 1,
17961      TYPE_NAME (au), NULL_TREE);
17962   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17963   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17964   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17965
17966   return au;
17967 }
17968
17969 /* Given type ARG, return std::initializer_list<ARG>.  */
17970
17971 static tree
17972 listify (tree arg)
17973 {
17974   tree std_init_list = namespace_binding
17975     (get_identifier ("initializer_list"), std_node);
17976   tree argvec;
17977   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17978     {    
17979       error ("deducing from brace-enclosed initializer list requires "
17980              "#include <initializer_list>");
17981       return error_mark_node;
17982     }
17983   argvec = make_tree_vec (1);
17984   TREE_VEC_ELT (argvec, 0) = arg;
17985   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17986                                 NULL_TREE, 0, tf_warning_or_error);
17987 }
17988
17989 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17990
17991 static tree
17992 listify_autos (tree type, tree auto_node)
17993 {
17994   tree init_auto = listify (auto_node);
17995   tree argvec = make_tree_vec (1);
17996   TREE_VEC_ELT (argvec, 0) = init_auto;
17997   if (processing_template_decl)
17998     argvec = add_to_template_args (current_template_args (), argvec);
17999   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18000 }
18001
18002 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18003    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18004
18005 tree
18006 do_auto_deduction (tree type, tree init, tree auto_node)
18007 {
18008   tree parms, tparms, targs;
18009   tree args[1];
18010   int val;
18011
18012   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18013      with either a new invented type template parameter U or, if the
18014      initializer is a braced-init-list (8.5.4), with
18015      std::initializer_list<U>.  */
18016   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18017     type = listify_autos (type, auto_node);
18018
18019   parms = build_tree_list (NULL_TREE, type);
18020   args[0] = init;
18021   tparms = make_tree_vec (1);
18022   targs = make_tree_vec (1);
18023   TREE_VEC_ELT (tparms, 0)
18024     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18025   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18026                                DEDUCE_CALL, LOOKUP_NORMAL);
18027   if (val > 0)
18028     {
18029       error ("unable to deduce %qT from %qE", type, init);
18030       return error_mark_node;
18031     }
18032
18033   /* If the list of declarators contains more than one declarator, the type
18034      of each declared variable is determined as described above. If the
18035      type deduced for the template parameter U is not the same in each
18036      deduction, the program is ill-formed.  */
18037   if (TREE_TYPE (auto_node)
18038       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18039     {
18040       error ("inconsistent deduction for %qT: %qT and then %qT",
18041              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18042       return error_mark_node;
18043     }
18044   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18045
18046   if (processing_template_decl)
18047     targs = add_to_template_args (current_template_args (), targs);
18048   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18049 }
18050
18051 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18052    result.  */
18053
18054 tree
18055 splice_late_return_type (tree type, tree late_return_type)
18056 {
18057   tree argvec;
18058
18059   if (late_return_type == NULL_TREE)
18060     return type;
18061   argvec = make_tree_vec (1);
18062   TREE_VEC_ELT (argvec, 0) = late_return_type;
18063   if (processing_template_decl)
18064     argvec = add_to_template_args (current_template_args (), argvec);
18065   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18066 }
18067
18068 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18069
18070 bool
18071 is_auto (const_tree type)
18072 {
18073   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18074       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18075     return true;
18076   else
18077     return false;
18078 }
18079
18080 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18081    appear as a type-specifier for the declaration in question, we don't
18082    have to look through the whole type.  */
18083
18084 tree
18085 type_uses_auto (tree type)
18086 {
18087   enum tree_code code;
18088   if (is_auto (type))
18089     return type;
18090
18091   code = TREE_CODE (type);
18092
18093   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18094       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18095       || code == METHOD_TYPE || code == ARRAY_TYPE)
18096     return type_uses_auto (TREE_TYPE (type));
18097
18098   if (TYPE_PTRMEMFUNC_P (type))
18099     return type_uses_auto (TREE_TYPE (TREE_TYPE
18100                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18101
18102   return NULL_TREE;
18103 }
18104
18105 /* For a given template T, return the vector of typedefs referenced
18106    in T for which access check is needed at T instantiation time.
18107    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18108    Those typedefs were added to T by the function
18109    append_type_to_template_for_access_check.  */
18110
18111 VEC(qualified_typedef_usage_t,gc)*
18112 get_types_needing_access_check (tree t)
18113 {
18114   tree ti;
18115   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18116
18117   if (!t || t == error_mark_node)
18118     return NULL;
18119
18120   if (!(ti = get_template_info (t)))
18121     return NULL;
18122
18123   if (CLASS_TYPE_P (t)
18124       || TREE_CODE (t) == FUNCTION_DECL)
18125     {
18126       if (!TI_TEMPLATE (ti))
18127         return NULL;
18128
18129       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18130     }
18131
18132   return result;
18133 }
18134
18135 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18136    tied to T. That list of typedefs will be access checked at
18137    T instantiation time.
18138    T is either a FUNCTION_DECL or a RECORD_TYPE.
18139    TYPE_DECL is a TYPE_DECL node representing a typedef.
18140    SCOPE is the scope through which TYPE_DECL is accessed.
18141    LOCATION is the location of the usage point of TYPE_DECL.
18142
18143    This function is a subroutine of
18144    append_type_to_template_for_access_check.  */
18145
18146 static void
18147 append_type_to_template_for_access_check_1 (tree t,
18148                                             tree type_decl,
18149                                             tree scope,
18150                                             location_t location)
18151 {
18152   qualified_typedef_usage_t typedef_usage;
18153   tree ti;
18154
18155   if (!t || t == error_mark_node)
18156     return;
18157
18158   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18159                || CLASS_TYPE_P (t))
18160               && type_decl
18161               && TREE_CODE (type_decl) == TYPE_DECL
18162               && scope);
18163
18164   if (!(ti = get_template_info (t)))
18165     return;
18166
18167   gcc_assert (TI_TEMPLATE (ti));
18168
18169   typedef_usage.typedef_decl = type_decl;
18170   typedef_usage.context = scope;
18171   typedef_usage.locus = location;
18172
18173   VEC_safe_push (qualified_typedef_usage_t, gc,
18174                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18175                  &typedef_usage);
18176 }
18177
18178 /* Append TYPE_DECL to the template TEMPL.
18179    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18180    At TEMPL instanciation time, TYPE_DECL will be checked to see
18181    if it can be accessed through SCOPE.
18182    LOCATION is the location of the usage point of TYPE_DECL.
18183
18184    e.g. consider the following code snippet:
18185
18186      class C
18187      {
18188        typedef int myint;
18189      };
18190
18191      template<class U> struct S
18192      {
18193        C::myint mi; // <-- usage point of the typedef C::myint
18194      };
18195
18196      S<char> s;
18197
18198    At S<char> instantiation time, we need to check the access of C::myint
18199    In other words, we need to check the access of the myint typedef through
18200    the C scope. For that purpose, this function will add the myint typedef
18201    and the scope C through which its being accessed to a list of typedefs
18202    tied to the template S. That list will be walked at template instantiation
18203    time and access check performed on each typedefs it contains.
18204    Note that this particular code snippet should yield an error because
18205    myint is private to C.  */
18206
18207 void
18208 append_type_to_template_for_access_check (tree templ,
18209                                           tree type_decl,
18210                                           tree scope,
18211                                           location_t location)
18212 {
18213   qualified_typedef_usage_t *iter;
18214   int i;
18215
18216   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18217
18218   /* Make sure we don't append the type to the template twice.  */
18219   for (i = 0;
18220        VEC_iterate (qualified_typedef_usage_t,
18221                     get_types_needing_access_check (templ),
18222                     i, iter);
18223        ++i)
18224     if (iter->typedef_decl == type_decl && scope == iter->context)
18225       return;
18226
18227   append_type_to_template_for_access_check_1 (templ, type_decl,
18228                                               scope, location);
18229 }
18230
18231 /* Set up the hash tables for template instantiations.  */
18232
18233 void
18234 init_template_processing (void)
18235 {
18236   decl_specializations = htab_create_ggc (37,
18237                                           hash_specialization,
18238                                           eq_specializations,
18239                                           ggc_free);
18240   type_specializations = htab_create_ggc (37,
18241                                           hash_specialization,
18242                                           eq_specializations,
18243                                           ggc_free);
18244 }
18245
18246 #include "gt-cp-pt.h"