OSDN Git Service

Fix PR c++/43558
[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 "intl.h"
36 #include "pointer-set.h"
37 #include "flags.h"
38 #include "c-common.h"
39 #include "cp-tree.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "except.h"
45 #include "toplev.h"
46 #include "rtl.h"
47 #include "timevar.h"
48 #include "tree-iterator.h"
49 #include "vecprim.h"
50
51 /* The type of functions taking a tree, and some additional data, and
52    returning an int.  */
53 typedef int (*tree_fn_t) (tree, void*);
54
55 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56    instantiations have been deferred, either because their definitions
57    were not yet available, or because we were putting off doing the work.  */
58 struct GTY (()) pending_template {
59   struct pending_template *next;
60   struct tinst_level *tinst;
61 };
62
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
65
66 int processing_template_parmlist;
67 static int template_header_count;
68
69 static GTY(()) tree saved_trees;
70 static VEC(int,heap) *inline_parm_levels;
71
72 static GTY(()) struct tinst_level *current_tinst_level;
73
74 static GTY(()) tree saved_access_scope;
75
76 /* Live only within one (recursive) call to tsubst_expr.  We use
77    this to pass the statement expression node from the STMT_EXPR
78    to the EXPR_STMT that is its result.  */
79 static tree cur_stmt_expr;
80
81 /* A map from local variable declarations in the body of the template
82    presently being instantiated to the corresponding instantiated
83    local variables.  */
84 static htab_t local_specializations;
85
86 typedef struct GTY(()) spec_entry
87 {
88   tree tmpl;
89   tree args;
90   tree spec;
91 } spec_entry;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t decl_specializations;
95
96 static GTY ((param_is (spec_entry)))
97   htab_t type_specializations;
98
99 /* Contains canonical template parameter types. The vector is indexed by
100    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101    TREE_LIST, whose TREE_VALUEs contain the canonical template
102    parameters of various types and levels.  */
103 static GTY(()) VEC(tree,gc) *canonical_template_parms;
104
105 #define UNIFY_ALLOW_NONE 0
106 #define UNIFY_ALLOW_MORE_CV_QUAL 1
107 #define UNIFY_ALLOW_LESS_CV_QUAL 2
108 #define UNIFY_ALLOW_DERIVED 4
109 #define UNIFY_ALLOW_INTEGER 8
110 #define UNIFY_ALLOW_OUTER_LEVEL 16
111 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113
114 static void push_access_scope (tree);
115 static void pop_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126                                    bool, bool);
127 static void tsubst_enum (tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132                                              tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134                                   unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree);
138 static tree convert_template_argument (tree, tree, tree,
139                                        tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141                                    struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174                                            tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192                                                         location_t);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194 static tree listify (tree);
195 static tree listify_autos (tree, tree);
196
197 /* Make the current scope suitable for access checking when we are
198    processing T.  T can be FUNCTION_DECL for instantiated function
199    template, or VAR_DECL for static member variable (need by
200    instantiate_decl).  */
201
202 static void
203 push_access_scope (tree t)
204 {
205   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206               || TREE_CODE (t) == VAR_DECL);
207
208   if (DECL_FRIEND_CONTEXT (t))
209     push_nested_class (DECL_FRIEND_CONTEXT (t));
210   else if (DECL_CLASS_SCOPE_P (t))
211     push_nested_class (DECL_CONTEXT (t));
212   else
213     push_to_top_level ();
214
215   if (TREE_CODE (t) == FUNCTION_DECL)
216     {
217       saved_access_scope = tree_cons
218         (NULL_TREE, current_function_decl, saved_access_scope);
219       current_function_decl = t;
220     }
221 }
222
223 /* Restore the scope set up by push_access_scope.  T is the node we
224    are processing.  */
225
226 static void
227 pop_access_scope (tree t)
228 {
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       current_function_decl = TREE_VALUE (saved_access_scope);
232       saved_access_scope = TREE_CHAIN (saved_access_scope);
233     }
234
235   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236     pop_nested_class ();
237   else
238     pop_from_top_level ();
239 }
240
241 /* Do any processing required when DECL (a member template
242    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243    to DECL, unless it is a specialization, in which case the DECL
244    itself is returned.  */
245
246 tree
247 finish_member_template_decl (tree decl)
248 {
249   if (decl == error_mark_node)
250     return error_mark_node;
251
252   gcc_assert (DECL_P (decl));
253
254   if (TREE_CODE (decl) == TYPE_DECL)
255     {
256       tree type;
257
258       type = TREE_TYPE (decl);
259       if (type == error_mark_node)
260         return error_mark_node;
261       if (MAYBE_CLASS_TYPE_P (type)
262           && CLASSTYPE_TEMPLATE_INFO (type)
263           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264         {
265           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266           check_member_template (tmpl);
267           return tmpl;
268         }
269       return NULL_TREE;
270     }
271   else if (TREE_CODE (decl) == FIELD_DECL)
272     error ("data member %qD cannot be a member template", decl);
273   else if (DECL_TEMPLATE_INFO (decl))
274     {
275       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276         {
277           check_member_template (DECL_TI_TEMPLATE (decl));
278           return DECL_TI_TEMPLATE (decl);
279         }
280       else
281         return decl;
282     }
283   else
284     error ("invalid member template declaration %qD", decl);
285
286   return error_mark_node;
287 }
288
289 /* Create a template info node.  */
290
291 tree
292 build_template_info (tree template_decl, tree template_args)
293 {
294   tree result = make_node (TEMPLATE_INFO);
295   TI_TEMPLATE (result) = template_decl;
296   TI_ARGS (result) = template_args;
297   return result;
298 }
299
300 /* Return the template info node corresponding to T, whatever T is.  */
301
302 tree
303 get_template_info (const_tree t)
304 {
305   tree tinfo = NULL_TREE;
306
307   if (!t || t == error_mark_node)
308     return NULL;
309
310   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
311     tinfo = DECL_TEMPLATE_INFO (t);
312
313   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
314     t = TREE_TYPE (t);
315
316   if (TAGGED_TYPE_P (t))
317     tinfo = TYPE_TEMPLATE_INFO (t);
318   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
319     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
320
321   return tinfo;
322 }
323
324 /* Returns the template nesting level of the indicated class TYPE.
325
326    For example, in:
327      template <class T>
328      struct A
329      {
330        template <class U>
331        struct B {};
332      };
333
334    A<T>::B<U> has depth two, while A<T> has depth one.
335    Both A<T>::B<int> and A<int>::B<U> have depth one, if
336    they are instantiations, not specializations.
337
338    This function is guaranteed to return 0 if passed NULL_TREE so
339    that, for example, `template_class_depth (current_class_type)' is
340    always safe.  */
341
342 int
343 template_class_depth (tree type)
344 {
345   int depth;
346
347   for (depth = 0;
348        type && TREE_CODE (type) != NAMESPACE_DECL;
349        type = (TREE_CODE (type) == FUNCTION_DECL)
350          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351     {
352       tree tinfo = get_template_info (type);
353
354       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356         ++depth;
357     }
358
359   return depth;
360 }
361
362 /* Subroutine of maybe_begin_member_template_processing.
363    Returns true if processing DECL needs us to push template parms.  */
364
365 static bool
366 inline_needs_template_parms (tree decl)
367 {
368   if (! DECL_TEMPLATE_INFO (decl))
369     return false;
370
371   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373 }
374
375 /* Subroutine of maybe_begin_member_template_processing.
376    Push the template parms in PARMS, starting from LEVELS steps into the
377    chain, and ending at the beginning, since template parms are listed
378    innermost first.  */
379
380 static void
381 push_inline_template_parms_recursive (tree parmlist, int levels)
382 {
383   tree parms = TREE_VALUE (parmlist);
384   int i;
385
386   if (levels > 1)
387     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388
389   ++processing_template_decl;
390   current_template_parms
391     = tree_cons (size_int (processing_template_decl),
392                  parms, current_template_parms);
393   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394
395   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396                NULL);
397   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398     {
399       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400
401       if (parm == error_mark_node)
402         continue;
403
404       gcc_assert (DECL_P (parm));
405
406       switch (TREE_CODE (parm))
407         {
408         case TYPE_DECL:
409         case TEMPLATE_DECL:
410           pushdecl (parm);
411           break;
412
413         case PARM_DECL:
414           {
415             /* Make a CONST_DECL as is done in process_template_parm.
416                It is ugly that we recreate this here; the original
417                version built in process_template_parm is no longer
418                available.  */
419             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420                                     CONST_DECL, DECL_NAME (parm),
421                                     TREE_TYPE (parm));
422             DECL_ARTIFICIAL (decl) = 1;
423             TREE_CONSTANT (decl) = 1;
424             TREE_READONLY (decl) = 1;
425             DECL_INITIAL (decl) = DECL_INITIAL (parm);
426             SET_DECL_TEMPLATE_PARM_P (decl);
427             pushdecl (decl);
428           }
429           break;
430
431         default:
432           gcc_unreachable ();
433         }
434     }
435 }
436
437 /* Restore the template parameter context for a member template or
438    a friend template defined in a class definition.  */
439
440 void
441 maybe_begin_member_template_processing (tree decl)
442 {
443   tree parms;
444   int levels = 0;
445
446   if (inline_needs_template_parms (decl))
447     {
448       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450
451       if (DECL_TEMPLATE_SPECIALIZATION (decl))
452         {
453           --levels;
454           parms = TREE_CHAIN (parms);
455         }
456
457       push_inline_template_parms_recursive (parms, levels);
458     }
459
460   /* Remember how many levels of template parameters we pushed so that
461      we can pop them later.  */
462   VEC_safe_push (int, heap, inline_parm_levels, levels);
463 }
464
465 /* Undo the effects of maybe_begin_member_template_processing.  */
466
467 void
468 maybe_end_member_template_processing (void)
469 {
470   int i;
471   int last;
472
473   if (VEC_length (int, inline_parm_levels) == 0)
474     return;
475
476   last = VEC_pop (int, inline_parm_levels);
477   for (i = 0; i < last; ++i)
478     {
479       --processing_template_decl;
480       current_template_parms = TREE_CHAIN (current_template_parms);
481       poplevel (0, 0, 0);
482     }
483 }
484
485 /* Return a new template argument vector which contains all of ARGS,
486    but has as its innermost set of arguments the EXTRA_ARGS.  */
487
488 static tree
489 add_to_template_args (tree args, tree extra_args)
490 {
491   tree new_args;
492   int extra_depth;
493   int i;
494   int j;
495
496   if (args == NULL_TREE)
497     return extra_args;
498
499   extra_depth = TMPL_ARGS_DEPTH (extra_args);
500   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
501
502   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
504
505   for (j = 1; j <= extra_depth; ++j, ++i)
506     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
507
508   return new_args;
509 }
510
511 /* Like add_to_template_args, but only the outermost ARGS are added to
512    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
513    (EXTRA_ARGS) levels are added.  This function is used to combine
514    the template arguments from a partial instantiation with the
515    template arguments used to attain the full instantiation from the
516    partial instantiation.  */
517
518 static tree
519 add_outermost_template_args (tree args, tree extra_args)
520 {
521   tree new_args;
522
523   /* If there are more levels of EXTRA_ARGS than there are ARGS,
524      something very fishy is going on.  */
525   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
526
527   /* If *all* the new arguments will be the EXTRA_ARGS, just return
528      them.  */
529   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
530     return extra_args;
531
532   /* For the moment, we make ARGS look like it contains fewer levels.  */
533   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
534
535   new_args = add_to_template_args (args, extra_args);
536
537   /* Now, we restore ARGS to its full dimensions.  */
538   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
539
540   return new_args;
541 }
542
543 /* Return the N levels of innermost template arguments from the ARGS.  */
544
545 tree
546 get_innermost_template_args (tree args, int n)
547 {
548   tree new_args;
549   int extra_levels;
550   int i;
551
552   gcc_assert (n >= 0);
553
554   /* If N is 1, just return the innermost set of template arguments.  */
555   if (n == 1)
556     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
557
558   /* If we're not removing anything, just return the arguments we were
559      given.  */
560   extra_levels = TMPL_ARGS_DEPTH (args) - n;
561   gcc_assert (extra_levels >= 0);
562   if (extra_levels == 0)
563     return args;
564
565   /* Make a new set of arguments, not containing the outer arguments.  */
566   new_args = make_tree_vec (n);
567   for (i = 1; i <= n; ++i)
568     SET_TMPL_ARGS_LEVEL (new_args, i,
569                          TMPL_ARGS_LEVEL (args, i + extra_levels));
570
571   return new_args;
572 }
573
574 /* The inverse of get_innermost_template_args: Return all but the innermost
575    EXTRA_LEVELS levels of template arguments from the ARGS.  */
576
577 static tree
578 strip_innermost_template_args (tree args, int extra_levels)
579 {
580   tree new_args;
581   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
582   int i;
583
584   gcc_assert (n >= 0);
585
586   /* If N is 1, just return the outermost set of template arguments.  */
587   if (n == 1)
588     return TMPL_ARGS_LEVEL (args, 1);
589
590   /* If we're not removing anything, just return the arguments we were
591      given.  */
592   gcc_assert (extra_levels >= 0);
593   if (extra_levels == 0)
594     return args;
595
596   /* Make a new set of arguments, not containing the inner arguments.  */
597   new_args = make_tree_vec (n);
598   for (i = 1; i <= n; ++i)
599     SET_TMPL_ARGS_LEVEL (new_args, i,
600                          TMPL_ARGS_LEVEL (args, i));
601
602   return new_args;
603 }
604
605 /* We've got a template header coming up; push to a new level for storing
606    the parms.  */
607
608 void
609 begin_template_parm_list (void)
610 {
611   /* We use a non-tag-transparent scope here, which causes pushtag to
612      put tags in this scope, rather than in the enclosing class or
613      namespace scope.  This is the right thing, since we want
614      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
615      global template class, push_template_decl handles putting the
616      TEMPLATE_DECL into top-level scope.  For a nested template class,
617      e.g.:
618
619        template <class T> struct S1 {
620          template <class T> struct S2 {};
621        };
622
623      pushtag contains special code to call pushdecl_with_scope on the
624      TEMPLATE_DECL for S2.  */
625   begin_scope (sk_template_parms, NULL);
626   ++processing_template_decl;
627   ++processing_template_parmlist;
628   note_template_header (0);
629 }
630
631 /* This routine is called when a specialization is declared.  If it is
632    invalid to declare a specialization here, an error is reported and
633    false is returned, otherwise this routine will return true.  */
634
635 static bool
636 check_specialization_scope (void)
637 {
638   tree scope = current_scope ();
639
640   /* [temp.expl.spec]
641
642      An explicit specialization shall be declared in the namespace of
643      which the template is a member, or, for member templates, in the
644      namespace of which the enclosing class or enclosing class
645      template is a member.  An explicit specialization of a member
646      function, member class or static data member of a class template
647      shall be declared in the namespace of which the class template
648      is a member.  */
649   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
650     {
651       error ("explicit specialization in non-namespace scope %qD", scope);
652       return false;
653     }
654
655   /* [temp.expl.spec]
656
657      In an explicit specialization declaration for a member of a class
658      template or a member template that appears in namespace scope,
659      the member template and some of its enclosing class templates may
660      remain unspecialized, except that the declaration shall not
661      explicitly specialize a class member template if its enclosing
662      class templates are not explicitly specialized as well.  */
663   if (current_template_parms)
664     {
665       error ("enclosing class templates are not explicitly specialized");
666       return false;
667     }
668
669   return true;
670 }
671
672 /* We've just seen template <>.  */
673
674 bool
675 begin_specialization (void)
676 {
677   begin_scope (sk_template_spec, NULL);
678   note_template_header (1);
679   return check_specialization_scope ();
680 }
681
682 /* Called at then end of processing a declaration preceded by
683    template<>.  */
684
685 void
686 end_specialization (void)
687 {
688   finish_scope ();
689   reset_specialization ();
690 }
691
692 /* Any template <>'s that we have seen thus far are not referring to a
693    function specialization.  */
694
695 void
696 reset_specialization (void)
697 {
698   processing_specialization = 0;
699   template_header_count = 0;
700 }
701
702 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
703    it was of the form template <>.  */
704
705 static void
706 note_template_header (int specialization)
707 {
708   processing_specialization = specialization;
709   template_header_count++;
710 }
711
712 /* We're beginning an explicit instantiation.  */
713
714 void
715 begin_explicit_instantiation (void)
716 {
717   gcc_assert (!processing_explicit_instantiation);
718   processing_explicit_instantiation = true;
719 }
720
721
722 void
723 end_explicit_instantiation (void)
724 {
725   gcc_assert (processing_explicit_instantiation);
726   processing_explicit_instantiation = false;
727 }
728
729 /* An explicit specialization or partial specialization TMPL is being
730    declared.  Check that the namespace in which the specialization is
731    occurring is permissible.  Returns false iff it is invalid to
732    specialize TMPL in the current namespace.  */
733
734 static bool
735 check_specialization_namespace (tree tmpl)
736 {
737   tree tpl_ns = decl_namespace_context (tmpl);
738
739   /* [tmpl.expl.spec]
740
741      An explicit specialization shall be declared in the namespace of
742      which the template is a member, or, for member templates, in the
743      namespace of which the enclosing class or enclosing class
744      template is a member.  An explicit specialization of a member
745      function, member class or static data member of a class template
746      shall be declared in the namespace of which the class template is
747      a member.  */
748   if (current_scope() != DECL_CONTEXT (tmpl)
749       && !at_namespace_scope_p ())
750     {
751       error ("specialization of %qD must appear at namespace scope", tmpl);
752       return false;
753     }
754   if (is_associated_namespace (current_namespace, tpl_ns))
755     /* Same or super-using namespace.  */
756     return true;
757   else
758     {
759       permerror (input_location, "specialization of %qD in different namespace", tmpl);
760       permerror (input_location, "  from definition of %q+#D", tmpl);
761       return false;
762     }
763 }
764
765 /* SPEC is an explicit instantiation.  Check that it is valid to
766    perform this explicit instantiation in the current namespace.  */
767
768 static void
769 check_explicit_instantiation_namespace (tree spec)
770 {
771   tree ns;
772
773   /* DR 275: An explicit instantiation shall appear in an enclosing
774      namespace of its template.  */
775   ns = decl_namespace_context (spec);
776   if (!is_ancestor (current_namespace, ns))
777     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
778                "(which does not enclose namespace %qD)",
779                spec, current_namespace, ns);
780 }
781
782 /* The TYPE is being declared.  If it is a template type, that means it
783    is a partial specialization.  Do appropriate error-checking.  */
784
785 tree
786 maybe_process_partial_specialization (tree type)
787 {
788   tree context;
789
790   if (type == error_mark_node)
791     return error_mark_node;
792
793   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
794     {
795       error ("name of class shadows template template parameter %qD",
796              TYPE_NAME (type));
797       return error_mark_node;
798     }
799
800   context = TYPE_CONTEXT (type);
801
802   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
803     {
804       /* This is for ordinary explicit specialization and partial
805          specialization of a template class such as:
806
807            template <> class C<int>;
808
809          or:
810
811            template <class T> class C<T*>;
812
813          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
814
815       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
816           && !COMPLETE_TYPE_P (type))
817         {
818           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
819           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
820           if (processing_template_decl)
821             {
822               if (push_template_decl (TYPE_MAIN_DECL (type))
823                   == error_mark_node)
824                 return error_mark_node;
825             }
826         }
827       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
828         error ("specialization of %qT after instantiation", type);
829     }
830   else if (CLASS_TYPE_P (type)
831            && !CLASSTYPE_USE_TEMPLATE (type)
832            && CLASSTYPE_TEMPLATE_INFO (type)
833            && context && CLASS_TYPE_P (context)
834            && CLASSTYPE_TEMPLATE_INFO (context))
835     {
836       /* This is for an explicit specialization of member class
837          template according to [temp.expl.spec/18]:
838
839            template <> template <class U> class C<int>::D;
840
841          The context `C<int>' must be an implicit instantiation.
842          Otherwise this is just a member class template declared
843          earlier like:
844
845            template <> class C<int> { template <class U> class D; };
846            template <> template <class U> class C<int>::D;
847
848          In the first case, `C<int>::D' is a specialization of `C<T>::D'
849          while in the second case, `C<int>::D' is a primary template
850          and `C<T>::D' may not exist.  */
851
852       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
853           && !COMPLETE_TYPE_P (type))
854         {
855           tree t;
856           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
857
858           if (current_namespace
859               != decl_namespace_context (tmpl))
860             {
861               permerror (input_location, "specializing %q#T in different namespace", type);
862               permerror (input_location, "  from definition of %q+#D", tmpl);
863             }
864
865           /* Check for invalid specialization after instantiation:
866
867                template <> template <> class C<int>::D<int>;
868                template <> template <class U> class C<int>::D;  */
869
870           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
871                t; t = TREE_CHAIN (t))
872             {
873               tree inst = TREE_VALUE (t);
874               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
875                 {
876                   /* We already have a full specialization of this partial
877                      instantiation.  Reassign it to the new member
878                      specialization template.  */
879                   spec_entry elt;
880                   spec_entry **slot;
881
882                   elt.tmpl = most_general_template (tmpl);
883                   elt.args = CLASSTYPE_TI_ARGS (inst);
884                   elt.spec = inst;
885
886                   htab_remove_elt (type_specializations, &elt);
887
888                   elt.tmpl = tmpl;
889                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
890
891                   slot = (spec_entry **)
892                     htab_find_slot (type_specializations, &elt, INSERT);
893                   *slot = GGC_NEW (spec_entry);
894                   **slot = elt;
895                 }
896               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
897                 /* But if we've had an implicit instantiation, that's a
898                    problem ([temp.expl.spec]/6).  */
899                 error ("specialization %qT after instantiation %qT",
900                        type, inst);
901             }
902
903           /* Mark TYPE as a specialization.  And as a result, we only
904              have one level of template argument for the innermost
905              class template.  */
906           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
907           CLASSTYPE_TI_ARGS (type)
908             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
909         }
910     }
911   else if (processing_specialization)
912     {
913       error ("explicit specialization of non-template %qT", type);
914       return error_mark_node;
915     }
916
917   return type;
918 }
919
920 /* Returns nonzero if we can optimize the retrieval of specializations
921    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
922    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
923
924 static inline bool
925 optimize_specialization_lookup_p (tree tmpl)
926 {
927   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
928           && DECL_CLASS_SCOPE_P (tmpl)
929           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
930              parameter.  */
931           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
932           /* The optimized lookup depends on the fact that the
933              template arguments for the member function template apply
934              purely to the containing class, which is not true if the
935              containing class is an explicit or partial
936              specialization.  */
937           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
938           && !DECL_MEMBER_TEMPLATE_P (tmpl)
939           && !DECL_CONV_FN_P (tmpl)
940           /* It is possible to have a template that is not a member
941              template and is not a member of a template class:
942
943              template <typename T>
944              struct S { friend A::f(); };
945
946              Here, the friend function is a template, but the context does
947              not have template information.  The optimized lookup relies
948              on having ARGS be the template arguments for both the class
949              and the function template.  */
950           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
951 }
952
953 /* Retrieve the specialization (in the sense of [temp.spec] - a
954    specialization is either an instantiation or an explicit
955    specialization) of TMPL for the given template ARGS.  If there is
956    no such specialization, return NULL_TREE.  The ARGS are a vector of
957    arguments, or a vector of vectors of arguments, in the case of
958    templates with more than one level of parameters.
959
960    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
961    then we search for a partial specialization matching ARGS.  This
962    parameter is ignored if TMPL is not a class template.  */
963
964 static tree
965 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
966 {
967   if (args == error_mark_node)
968     return NULL_TREE;
969
970   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
971
972   /* There should be as many levels of arguments as there are
973      levels of parameters.  */
974   gcc_assert (TMPL_ARGS_DEPTH (args)
975               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
976
977   if (optimize_specialization_lookup_p (tmpl))
978     {
979       tree class_template;
980       tree class_specialization;
981       VEC(tree,gc) *methods;
982       tree fns;
983       int idx;
984
985       /* The template arguments actually apply to the containing
986          class.  Find the class specialization with those
987          arguments.  */
988       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
989       class_specialization
990         = retrieve_specialization (class_template, args, 0);
991       if (!class_specialization)
992         return NULL_TREE;
993       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
994          for the specialization.  */
995       idx = class_method_index_for_fn (class_specialization, tmpl);
996       if (idx == -1)
997         return NULL_TREE;
998       /* Iterate through the methods with the indicated name, looking
999          for the one that has an instance of TMPL.  */
1000       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1001       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1002         {
1003           tree fn = OVL_CURRENT (fns);
1004           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1005               /* using-declarations can add base methods to the method vec,
1006                  and we don't want those here.  */
1007               && DECL_CONTEXT (fn) == class_specialization)
1008             return fn;
1009         }
1010       return NULL_TREE;
1011     }
1012   else
1013     {
1014       spec_entry *found;
1015       spec_entry elt;
1016       htab_t specializations;
1017
1018       elt.tmpl = tmpl;
1019       elt.args = args;
1020       elt.spec = NULL_TREE;
1021
1022       if (DECL_CLASS_TEMPLATE_P (tmpl))
1023         specializations = type_specializations;
1024       else
1025         specializations = decl_specializations;
1026
1027       if (hash == 0)
1028         hash = hash_specialization (&elt);
1029       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1030       if (found)
1031         return found->spec;
1032     }
1033
1034   return NULL_TREE;
1035 }
1036
1037 /* Like retrieve_specialization, but for local declarations.  */
1038
1039 static tree
1040 retrieve_local_specialization (tree tmpl)
1041 {
1042   tree spec;
1043
1044   if (local_specializations == NULL)
1045     return NULL_TREE;
1046
1047   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1048                                      htab_hash_pointer (tmpl));
1049   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1050 }
1051
1052 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1053
1054 int
1055 is_specialization_of (tree decl, tree tmpl)
1056 {
1057   tree t;
1058
1059   if (TREE_CODE (decl) == FUNCTION_DECL)
1060     {
1061       for (t = decl;
1062            t != NULL_TREE;
1063            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1064         if (t == tmpl)
1065           return 1;
1066     }
1067   else
1068     {
1069       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1070
1071       for (t = TREE_TYPE (decl);
1072            t != NULL_TREE;
1073            t = CLASSTYPE_USE_TEMPLATE (t)
1074              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1075         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1076           return 1;
1077     }
1078
1079   return 0;
1080 }
1081
1082 /* Returns nonzero iff DECL is a specialization of friend declaration
1083    FRIEND_DECL according to [temp.friend].  */
1084
1085 bool
1086 is_specialization_of_friend (tree decl, tree friend_decl)
1087 {
1088   bool need_template = true;
1089   int template_depth;
1090
1091   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1092               || TREE_CODE (decl) == TYPE_DECL);
1093
1094   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1095      of a template class, we want to check if DECL is a specialization
1096      if this.  */
1097   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1098       && DECL_TEMPLATE_INFO (friend_decl)
1099       && !DECL_USE_TEMPLATE (friend_decl))
1100     {
1101       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1102       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1103       need_template = false;
1104     }
1105   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1106            && !PRIMARY_TEMPLATE_P (friend_decl))
1107     need_template = false;
1108
1109   /* There is nothing to do if this is not a template friend.  */
1110   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1111     return false;
1112
1113   if (is_specialization_of (decl, friend_decl))
1114     return true;
1115
1116   /* [temp.friend/6]
1117      A member of a class template may be declared to be a friend of a
1118      non-template class.  In this case, the corresponding member of
1119      every specialization of the class template is a friend of the
1120      class granting friendship.
1121
1122      For example, given a template friend declaration
1123
1124        template <class T> friend void A<T>::f();
1125
1126      the member function below is considered a friend
1127
1128        template <> struct A<int> {
1129          void f();
1130        };
1131
1132      For this type of template friend, TEMPLATE_DEPTH below will be
1133      nonzero.  To determine if DECL is a friend of FRIEND, we first
1134      check if the enclosing class is a specialization of another.  */
1135
1136   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1137   if (template_depth
1138       && DECL_CLASS_SCOPE_P (decl)
1139       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1140                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1141     {
1142       /* Next, we check the members themselves.  In order to handle
1143          a few tricky cases, such as when FRIEND_DECL's are
1144
1145            template <class T> friend void A<T>::g(T t);
1146            template <class T> template <T t> friend void A<T>::h();
1147
1148          and DECL's are
1149
1150            void A<int>::g(int);
1151            template <int> void A<int>::h();
1152
1153          we need to figure out ARGS, the template arguments from
1154          the context of DECL.  This is required for template substitution
1155          of `T' in the function parameter of `g' and template parameter
1156          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1157
1158       tree context = DECL_CONTEXT (decl);
1159       tree args = NULL_TREE;
1160       int current_depth = 0;
1161
1162       while (current_depth < template_depth)
1163         {
1164           if (CLASSTYPE_TEMPLATE_INFO (context))
1165             {
1166               if (current_depth == 0)
1167                 args = TYPE_TI_ARGS (context);
1168               else
1169                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1170               current_depth++;
1171             }
1172           context = TYPE_CONTEXT (context);
1173         }
1174
1175       if (TREE_CODE (decl) == FUNCTION_DECL)
1176         {
1177           bool is_template;
1178           tree friend_type;
1179           tree decl_type;
1180           tree friend_args_type;
1181           tree decl_args_type;
1182
1183           /* Make sure that both DECL and FRIEND_DECL are templates or
1184              non-templates.  */
1185           is_template = DECL_TEMPLATE_INFO (decl)
1186                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1187           if (need_template ^ is_template)
1188             return false;
1189           else if (is_template)
1190             {
1191               /* If both are templates, check template parameter list.  */
1192               tree friend_parms
1193                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194                                          args, tf_none);
1195               if (!comp_template_parms
1196                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1197                       friend_parms))
1198                 return false;
1199
1200               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1201             }
1202           else
1203             decl_type = TREE_TYPE (decl);
1204
1205           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1206                                               tf_none, NULL_TREE);
1207           if (friend_type == error_mark_node)
1208             return false;
1209
1210           /* Check if return types match.  */
1211           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1212             return false;
1213
1214           /* Check if function parameter types match, ignoring the
1215              `this' parameter.  */
1216           friend_args_type = TYPE_ARG_TYPES (friend_type);
1217           decl_args_type = TYPE_ARG_TYPES (decl_type);
1218           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1219             friend_args_type = TREE_CHAIN (friend_args_type);
1220           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1221             decl_args_type = TREE_CHAIN (decl_args_type);
1222
1223           return compparms (decl_args_type, friend_args_type);
1224         }
1225       else
1226         {
1227           /* DECL is a TYPE_DECL */
1228           bool is_template;
1229           tree decl_type = TREE_TYPE (decl);
1230
1231           /* Make sure that both DECL and FRIEND_DECL are templates or
1232              non-templates.  */
1233           is_template
1234             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1235               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1236
1237           if (need_template ^ is_template)
1238             return false;
1239           else if (is_template)
1240             {
1241               tree friend_parms;
1242               /* If both are templates, check the name of the two
1243                  TEMPLATE_DECL's first because is_friend didn't.  */
1244               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1245                   != DECL_NAME (friend_decl))
1246                 return false;
1247
1248               /* Now check template parameter list.  */
1249               friend_parms
1250                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1251                                          args, tf_none);
1252               return comp_template_parms
1253                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1254                  friend_parms);
1255             }
1256           else
1257             return (DECL_NAME (decl)
1258                     == DECL_NAME (friend_decl));
1259         }
1260     }
1261   return false;
1262 }
1263
1264 /* Register the specialization SPEC as a specialization of TMPL with
1265    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1266    is actually just a friend declaration.  Returns SPEC, or an
1267    equivalent prior declaration, if available.  */
1268
1269 static tree
1270 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1271                          hashval_t hash)
1272 {
1273   tree fn;
1274   spec_entry **slot = NULL;
1275   spec_entry elt;
1276
1277   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1278
1279   if (TREE_CODE (spec) == FUNCTION_DECL
1280       && uses_template_parms (DECL_TI_ARGS (spec)))
1281     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1282        register it; we want the corresponding TEMPLATE_DECL instead.
1283        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1284        the more obvious `uses_template_parms (spec)' to avoid problems
1285        with default function arguments.  In particular, given
1286        something like this:
1287
1288           template <class T> void f(T t1, T t = T())
1289
1290        the default argument expression is not substituted for in an
1291        instantiation unless and until it is actually needed.  */
1292     return spec;
1293
1294   if (optimize_specialization_lookup_p (tmpl))
1295     /* We don't put these specializations in the hash table, but we might
1296        want to give an error about a mismatch.  */
1297     fn = retrieve_specialization (tmpl, args, 0);
1298   else
1299     {
1300       elt.tmpl = tmpl;
1301       elt.args = args;
1302       elt.spec = spec;
1303
1304       if (hash == 0)
1305         hash = hash_specialization (&elt);
1306
1307       slot = (spec_entry **)
1308         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1309       if (*slot)
1310         fn = (*slot)->spec;
1311       else
1312         fn = NULL_TREE;
1313     }
1314
1315   /* We can sometimes try to re-register a specialization that we've
1316      already got.  In particular, regenerate_decl_from_template calls
1317      duplicate_decls which will update the specialization list.  But,
1318      we'll still get called again here anyhow.  It's more convenient
1319      to simply allow this than to try to prevent it.  */
1320   if (fn == spec)
1321     return spec;
1322   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1323     {
1324       if (DECL_TEMPLATE_INSTANTIATION (fn))
1325         {
1326           if (DECL_ODR_USED (fn)
1327               || DECL_EXPLICIT_INSTANTIATION (fn))
1328             {
1329               error ("specialization of %qD after instantiation",
1330                      fn);
1331               return error_mark_node;
1332             }
1333           else
1334             {
1335               tree clone;
1336               /* This situation should occur only if the first
1337                  specialization is an implicit instantiation, the
1338                  second is an explicit specialization, and the
1339                  implicit instantiation has not yet been used.  That
1340                  situation can occur if we have implicitly
1341                  instantiated a member function and then specialized
1342                  it later.
1343
1344                  We can also wind up here if a friend declaration that
1345                  looked like an instantiation turns out to be a
1346                  specialization:
1347
1348                    template <class T> void foo(T);
1349                    class S { friend void foo<>(int) };
1350                    template <> void foo(int);
1351
1352                  We transform the existing DECL in place so that any
1353                  pointers to it become pointers to the updated
1354                  declaration.
1355
1356                  If there was a definition for the template, but not
1357                  for the specialization, we want this to look as if
1358                  there were no definition, and vice versa.  */
1359               DECL_INITIAL (fn) = NULL_TREE;
1360               duplicate_decls (spec, fn, is_friend);
1361               /* The call to duplicate_decls will have applied
1362                  [temp.expl.spec]:
1363
1364                    An explicit specialization of a function template
1365                    is inline only if it is explicitly declared to be,
1366                    and independently of whether its function template
1367                    is.
1368
1369                 to the primary function; now copy the inline bits to
1370                 the various clones.  */
1371               FOR_EACH_CLONE (clone, fn)
1372                 {
1373                   DECL_DECLARED_INLINE_P (clone)
1374                     = DECL_DECLARED_INLINE_P (fn);
1375                   DECL_SOURCE_LOCATION (clone)
1376                     = DECL_SOURCE_LOCATION (fn);
1377                 }
1378               check_specialization_namespace (fn);
1379
1380               return fn;
1381             }
1382         }
1383       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1384         {
1385           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1386             /* Dup decl failed, but this is a new definition. Set the
1387                line number so any errors match this new
1388                definition.  */
1389             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1390
1391           return fn;
1392         }
1393     }
1394   else if (fn)
1395     return duplicate_decls (spec, fn, is_friend);
1396
1397   /* A specialization must be declared in the same namespace as the
1398      template it is specializing.  */
1399   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1400       && !check_specialization_namespace (tmpl))
1401     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1402
1403   if (!optimize_specialization_lookup_p (tmpl))
1404     {
1405       gcc_assert (tmpl && args && spec);
1406       *slot = GGC_NEW (spec_entry);
1407       **slot = elt;
1408       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1409           && PRIMARY_TEMPLATE_P (tmpl)
1410           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1411         /* TMPL is a forward declaration of a template function; keep a list
1412            of all specializations in case we need to reassign them to a friend
1413            template later in tsubst_friend_function.  */
1414         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1415           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1416     }
1417
1418   return spec;
1419 }
1420
1421 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1422    TMPL and ARGS members, ignores SPEC.  */
1423
1424 static int
1425 eq_specializations (const void *p1, const void *p2)
1426 {
1427   const spec_entry *e1 = (const spec_entry *)p1;
1428   const spec_entry *e2 = (const spec_entry *)p2;
1429
1430   return (e1->tmpl == e2->tmpl
1431           && comp_template_args (e1->args, e2->args));
1432 }
1433
1434 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1435
1436 static hashval_t
1437 hash_tmpl_and_args (tree tmpl, tree args)
1438 {
1439   hashval_t val = DECL_UID (tmpl);
1440   return iterative_hash_template_arg (args, val);
1441 }
1442
1443 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1444    ignoring SPEC.  */
1445
1446 static hashval_t
1447 hash_specialization (const void *p)
1448 {
1449   const spec_entry *e = (const spec_entry *)p;
1450   return hash_tmpl_and_args (e->tmpl, e->args);
1451 }
1452
1453 /* Recursively calculate a hash value for a template argument ARG, for use
1454    in the hash tables of template specializations.  */
1455
1456 static hashval_t
1457 iterative_hash_template_arg (tree arg, hashval_t val)
1458 {
1459   unsigned HOST_WIDE_INT i;
1460   enum tree_code code;
1461   char tclass;
1462
1463   if (arg == NULL_TREE)
1464     return iterative_hash_object (arg, val);
1465
1466   if (!TYPE_P (arg))
1467     STRIP_NOPS (arg);
1468
1469   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1470     /* We can get one of these when re-hashing a previous entry in the middle
1471        of substituting into a pack expansion.  Just look through it.  */
1472     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1473
1474   code = TREE_CODE (arg);
1475   tclass = TREE_CODE_CLASS (code);
1476
1477   val = iterative_hash_object (code, val);
1478
1479   switch (code)
1480     {
1481     case ERROR_MARK:
1482       return val;
1483
1484     case IDENTIFIER_NODE:
1485       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1486
1487     case TREE_VEC:
1488       {
1489         int i, len = TREE_VEC_LENGTH (arg);
1490         for (i = 0; i < len; ++i)
1491           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1492         return val;
1493       }
1494
1495     case TYPE_PACK_EXPANSION:
1496     case EXPR_PACK_EXPANSION:
1497       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1498
1499     case TYPE_ARGUMENT_PACK:
1500     case NONTYPE_ARGUMENT_PACK:
1501       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1502
1503     case TREE_LIST:
1504       for (; arg; arg = TREE_CHAIN (arg))
1505         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1506       return val;
1507
1508     case OVERLOAD:
1509       for (; arg; arg = OVL_CHAIN (arg))
1510         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1511       return val;
1512
1513     case CONSTRUCTOR:
1514       {
1515         tree field, value;
1516         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1517           {
1518             val = iterative_hash_template_arg (field, val);
1519             val = iterative_hash_template_arg (value, val);
1520           }
1521         return val;
1522       }
1523
1524     case PARM_DECL:
1525       if (!DECL_ARTIFICIAL (arg))
1526         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1527       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1528
1529     case TARGET_EXPR:
1530       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1531
1532     case PTRMEM_CST:
1533       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1534       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1535
1536     case TEMPLATE_PARM_INDEX:
1537       val = iterative_hash_template_arg
1538         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1539       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1540       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1541
1542     case TRAIT_EXPR:
1543       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1544       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1545       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1546
1547     case BASELINK:
1548       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1549                                          val);
1550       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1551                                           val);
1552
1553     case MODOP_EXPR:
1554       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1555       code = TREE_CODE (TREE_OPERAND (arg, 1));
1556       val = iterative_hash_object (code, val);
1557       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1558
1559     case ARRAY_TYPE:
1560       /* layout_type sets structural equality for arrays of
1561          incomplete type, so we can't rely on the canonical type
1562          for hashing.  */
1563       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1564       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1565
1566     default:
1567       switch (tclass)
1568         {
1569         case tcc_type:
1570           if (TYPE_CANONICAL (arg))
1571             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1572                                           val);
1573           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1574             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1575           /* Otherwise just compare the types during lookup.  */
1576           return val;
1577
1578         case tcc_declaration:
1579         case tcc_constant:
1580           return iterative_hash_expr (arg, val);
1581
1582         default:
1583           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1584           {
1585             unsigned n = TREE_OPERAND_LENGTH (arg);
1586             for (i = 0; i < n; ++i)
1587               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1588             return val;
1589           }
1590         }
1591     }
1592   gcc_unreachable ();
1593   return 0;
1594 }
1595
1596 /* Unregister the specialization SPEC as a specialization of TMPL.
1597    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1598    if the SPEC was listed as a specialization of TMPL.
1599
1600    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1601
1602 bool
1603 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1604 {
1605   spec_entry **slot;
1606   spec_entry elt;
1607
1608   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1609   elt.args = TI_ARGS (tinfo);
1610   elt.spec = NULL_TREE;
1611
1612   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1613   if (*slot)
1614     {
1615       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1616       gcc_assert (new_spec != NULL_TREE);
1617       (*slot)->spec = new_spec;
1618       return 1;
1619     }
1620
1621   return 0;
1622 }
1623
1624 /* Compare an entry in the local specializations hash table P1 (which
1625    is really a pointer to a TREE_LIST) with P2 (which is really a
1626    DECL).  */
1627
1628 static int
1629 eq_local_specializations (const void *p1, const void *p2)
1630 {
1631   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1632 }
1633
1634 /* Hash P1, an entry in the local specializations table.  */
1635
1636 static hashval_t
1637 hash_local_specialization (const void* p1)
1638 {
1639   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1640 }
1641
1642 /* Like register_specialization, but for local declarations.  We are
1643    registering SPEC, an instantiation of TMPL.  */
1644
1645 static void
1646 register_local_specialization (tree spec, tree tmpl)
1647 {
1648   void **slot;
1649
1650   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1651                                    htab_hash_pointer (tmpl), INSERT);
1652   *slot = build_tree_list (spec, tmpl);
1653 }
1654
1655 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1656    specialized class.  */
1657
1658 bool
1659 explicit_class_specialization_p (tree type)
1660 {
1661   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1662     return false;
1663   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1664 }
1665
1666 /* Print the list of functions at FNS, going through all the overloads
1667    for each element of the list.  Alternatively, FNS can not be a
1668    TREE_LIST, in which case it will be printed together with all the
1669    overloads.
1670
1671    MORE and *STR should respectively be FALSE and NULL when the function
1672    is called from the outside.  They are used internally on recursive
1673    calls.  print_candidates manages the two parameters and leaves NULL
1674    in *STR when it ends.  */
1675
1676 static void
1677 print_candidates_1 (tree fns, bool more, const char **str)
1678 {
1679   tree fn, fn2;
1680   char *spaces = NULL;
1681
1682   for (fn = fns; fn; fn = OVL_NEXT (fn))
1683     if (TREE_CODE (fn) == TREE_LIST)
1684       {
1685         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1686         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1687           print_candidates_1 (TREE_VALUE (fn2),
1688                               TREE_CHAIN (fn2) || more, str);
1689       }
1690     else
1691       {
1692         if (!*str)
1693           {
1694             /* Pick the prefix string.  */
1695             if (!more && !OVL_NEXT (fns))
1696               {
1697                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1698                 continue;
1699               }
1700
1701             *str = _("candidates are:");
1702             spaces = get_spaces (*str);
1703           }
1704         error ("%s %+#D", *str, OVL_CURRENT (fn));
1705         *str = spaces ? spaces : *str;
1706       }
1707
1708   if (!more)
1709     {
1710       free (spaces);
1711       *str = NULL;
1712     }
1713 }
1714
1715 /* Print the list of candidate FNS in an error message.  */
1716
1717 void
1718 print_candidates (tree fns)
1719 {
1720   const char *str = NULL;
1721   print_candidates_1 (fns, false, &str);
1722   gcc_assert (str == NULL);
1723 }
1724
1725 /* Returns the template (one of the functions given by TEMPLATE_ID)
1726    which can be specialized to match the indicated DECL with the
1727    explicit template args given in TEMPLATE_ID.  The DECL may be
1728    NULL_TREE if none is available.  In that case, the functions in
1729    TEMPLATE_ID are non-members.
1730
1731    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1732    specialization of a member template.
1733
1734    The TEMPLATE_COUNT is the number of references to qualifying
1735    template classes that appeared in the name of the function. See
1736    check_explicit_specialization for a more accurate description.
1737
1738    TSK indicates what kind of template declaration (if any) is being
1739    declared.  TSK_TEMPLATE indicates that the declaration given by
1740    DECL, though a FUNCTION_DECL, has template parameters, and is
1741    therefore a template function.
1742
1743    The template args (those explicitly specified and those deduced)
1744    are output in a newly created vector *TARGS_OUT.
1745
1746    If it is impossible to determine the result, an error message is
1747    issued.  The error_mark_node is returned to indicate failure.  */
1748
1749 static tree
1750 determine_specialization (tree template_id,
1751                           tree decl,
1752                           tree* targs_out,
1753                           int need_member_template,
1754                           int template_count,
1755                           tmpl_spec_kind tsk)
1756 {
1757   tree fns;
1758   tree targs;
1759   tree explicit_targs;
1760   tree candidates = NULL_TREE;
1761   /* A TREE_LIST of templates of which DECL may be a specialization.
1762      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1763      corresponding TREE_PURPOSE is the set of template arguments that,
1764      when used to instantiate the template, would produce a function
1765      with the signature of DECL.  */
1766   tree templates = NULL_TREE;
1767   int header_count;
1768   struct cp_binding_level *b;
1769
1770   *targs_out = NULL_TREE;
1771
1772   if (template_id == error_mark_node || decl == error_mark_node)
1773     return error_mark_node;
1774
1775   fns = TREE_OPERAND (template_id, 0);
1776   explicit_targs = TREE_OPERAND (template_id, 1);
1777
1778   if (fns == error_mark_node)
1779     return error_mark_node;
1780
1781   /* Check for baselinks.  */
1782   if (BASELINK_P (fns))
1783     fns = BASELINK_FUNCTIONS (fns);
1784
1785   if (!is_overloaded_fn (fns))
1786     {
1787       error ("%qD is not a function template", fns);
1788       return error_mark_node;
1789     }
1790
1791   /* Count the number of template headers specified for this
1792      specialization.  */
1793   header_count = 0;
1794   for (b = current_binding_level;
1795        b->kind == sk_template_parms;
1796        b = b->level_chain)
1797     ++header_count;
1798
1799   for (; fns; fns = OVL_NEXT (fns))
1800     {
1801       tree fn = OVL_CURRENT (fns);
1802
1803       if (TREE_CODE (fn) == TEMPLATE_DECL)
1804         {
1805           tree decl_arg_types;
1806           tree fn_arg_types;
1807
1808           /* In case of explicit specialization, we need to check if
1809              the number of template headers appearing in the specialization
1810              is correct. This is usually done in check_explicit_specialization,
1811              but the check done there cannot be exhaustive when specializing
1812              member functions. Consider the following code:
1813
1814              template <> void A<int>::f(int);
1815              template <> template <> void A<int>::f(int);
1816
1817              Assuming that A<int> is not itself an explicit specialization
1818              already, the first line specializes "f" which is a non-template
1819              member function, whilst the second line specializes "f" which
1820              is a template member function. So both lines are syntactically
1821              correct, and check_explicit_specialization does not reject
1822              them.
1823
1824              Here, we can do better, as we are matching the specialization
1825              against the declarations. We count the number of template
1826              headers, and we check if they match TEMPLATE_COUNT + 1
1827              (TEMPLATE_COUNT is the number of qualifying template classes,
1828              plus there must be another header for the member template
1829              itself).
1830
1831              Notice that if header_count is zero, this is not a
1832              specialization but rather a template instantiation, so there
1833              is no check we can perform here.  */
1834           if (header_count && header_count != template_count + 1)
1835             continue;
1836
1837           /* Check that the number of template arguments at the
1838              innermost level for DECL is the same as for FN.  */
1839           if (current_binding_level->kind == sk_template_parms
1840               && !current_binding_level->explicit_spec_p
1841               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1842                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1843                                       (current_template_parms))))
1844             continue;
1845
1846           /* DECL might be a specialization of FN.  */
1847           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1848           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1849
1850           /* For a non-static member function, we need to make sure
1851              that the const qualification is the same.  Since
1852              get_bindings does not try to merge the "this" parameter,
1853              we must do the comparison explicitly.  */
1854           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1855               && !same_type_p (TREE_VALUE (fn_arg_types),
1856                                TREE_VALUE (decl_arg_types)))
1857             continue;
1858
1859           /* Skip the "this" parameter and, for constructors of
1860              classes with virtual bases, the VTT parameter.  A
1861              full specialization of a constructor will have a VTT
1862              parameter, but a template never will.  */ 
1863           decl_arg_types 
1864             = skip_artificial_parms_for (decl, decl_arg_types);
1865           fn_arg_types 
1866             = skip_artificial_parms_for (fn, fn_arg_types);
1867
1868           /* Check that the number of function parameters matches.
1869              For example,
1870                template <class T> void f(int i = 0);
1871                template <> void f<int>();
1872              The specialization f<int> is invalid but is not caught
1873              by get_bindings below.  */
1874           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1875             continue;
1876
1877           /* Function templates cannot be specializations; there are
1878              no partial specializations of functions.  Therefore, if
1879              the type of DECL does not match FN, there is no
1880              match.  */
1881           if (tsk == tsk_template)
1882             {
1883               if (compparms (fn_arg_types, decl_arg_types))
1884                 candidates = tree_cons (NULL_TREE, fn, candidates);
1885               continue;
1886             }
1887
1888           /* See whether this function might be a specialization of this
1889              template.  */
1890           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1891
1892           if (!targs)
1893             /* We cannot deduce template arguments that when used to
1894                specialize TMPL will produce DECL.  */
1895             continue;
1896
1897           /* Save this template, and the arguments deduced.  */
1898           templates = tree_cons (targs, fn, templates);
1899         }
1900       else if (need_member_template)
1901         /* FN is an ordinary member function, and we need a
1902            specialization of a member template.  */
1903         ;
1904       else if (TREE_CODE (fn) != FUNCTION_DECL)
1905         /* We can get IDENTIFIER_NODEs here in certain erroneous
1906            cases.  */
1907         ;
1908       else if (!DECL_FUNCTION_MEMBER_P (fn))
1909         /* This is just an ordinary non-member function.  Nothing can
1910            be a specialization of that.  */
1911         ;
1912       else if (DECL_ARTIFICIAL (fn))
1913         /* Cannot specialize functions that are created implicitly.  */
1914         ;
1915       else
1916         {
1917           tree decl_arg_types;
1918
1919           /* This is an ordinary member function.  However, since
1920              we're here, we can assume it's enclosing class is a
1921              template class.  For example,
1922
1923                template <typename T> struct S { void f(); };
1924                template <> void S<int>::f() {}
1925
1926              Here, S<int>::f is a non-template, but S<int> is a
1927              template class.  If FN has the same type as DECL, we
1928              might be in business.  */
1929
1930           if (!DECL_TEMPLATE_INFO (fn))
1931             /* Its enclosing class is an explicit specialization
1932                of a template class.  This is not a candidate.  */
1933             continue;
1934
1935           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1936                             TREE_TYPE (TREE_TYPE (fn))))
1937             /* The return types differ.  */
1938             continue;
1939
1940           /* Adjust the type of DECL in case FN is a static member.  */
1941           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1942           if (DECL_STATIC_FUNCTION_P (fn)
1943               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1944             decl_arg_types = TREE_CHAIN (decl_arg_types);
1945
1946           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1947                          decl_arg_types))
1948             /* They match!  */
1949             candidates = tree_cons (NULL_TREE, fn, candidates);
1950         }
1951     }
1952
1953   if (templates && TREE_CHAIN (templates))
1954     {
1955       /* We have:
1956
1957            [temp.expl.spec]
1958
1959            It is possible for a specialization with a given function
1960            signature to be instantiated from more than one function
1961            template.  In such cases, explicit specification of the
1962            template arguments must be used to uniquely identify the
1963            function template specialization being specialized.
1964
1965          Note that here, there's no suggestion that we're supposed to
1966          determine which of the candidate templates is most
1967          specialized.  However, we, also have:
1968
1969            [temp.func.order]
1970
1971            Partial ordering of overloaded function template
1972            declarations is used in the following contexts to select
1973            the function template to which a function template
1974            specialization refers:
1975
1976            -- when an explicit specialization refers to a function
1977               template.
1978
1979          So, we do use the partial ordering rules, at least for now.
1980          This extension can only serve to make invalid programs valid,
1981          so it's safe.  And, there is strong anecdotal evidence that
1982          the committee intended the partial ordering rules to apply;
1983          the EDG front end has that behavior, and John Spicer claims
1984          that the committee simply forgot to delete the wording in
1985          [temp.expl.spec].  */
1986       tree tmpl = most_specialized_instantiation (templates);
1987       if (tmpl != error_mark_node)
1988         {
1989           templates = tmpl;
1990           TREE_CHAIN (templates) = NULL_TREE;
1991         }
1992     }
1993
1994   if (templates == NULL_TREE && candidates == NULL_TREE)
1995     {
1996       error ("template-id %qD for %q+D does not match any template "
1997              "declaration", template_id, decl);
1998       if (header_count && header_count != template_count + 1)
1999         inform (input_location, "saw %d %<template<>%>, need %d for "
2000                 "specializing a member function template",
2001                 header_count, template_count + 1);
2002       return error_mark_node;
2003     }
2004   else if ((templates && TREE_CHAIN (templates))
2005            || (candidates && TREE_CHAIN (candidates))
2006            || (templates && candidates))
2007     {
2008       error ("ambiguous template specialization %qD for %q+D",
2009              template_id, decl);
2010       candidates = chainon (candidates, templates);
2011       print_candidates (candidates);
2012       return error_mark_node;
2013     }
2014
2015   /* We have one, and exactly one, match.  */
2016   if (candidates)
2017     {
2018       tree fn = TREE_VALUE (candidates);
2019       *targs_out = copy_node (DECL_TI_ARGS (fn));
2020       /* DECL is a re-declaration or partial instantiation of a template
2021          function.  */
2022       if (TREE_CODE (fn) == TEMPLATE_DECL)
2023         return fn;
2024       /* It was a specialization of an ordinary member function in a
2025          template class.  */
2026       return DECL_TI_TEMPLATE (fn);
2027     }
2028
2029   /* It was a specialization of a template.  */
2030   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2031   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2032     {
2033       *targs_out = copy_node (targs);
2034       SET_TMPL_ARGS_LEVEL (*targs_out,
2035                            TMPL_ARGS_DEPTH (*targs_out),
2036                            TREE_PURPOSE (templates));
2037     }
2038   else
2039     *targs_out = TREE_PURPOSE (templates);
2040   return TREE_VALUE (templates);
2041 }
2042
2043 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2044    but with the default argument values filled in from those in the
2045    TMPL_TYPES.  */
2046
2047 static tree
2048 copy_default_args_to_explicit_spec_1 (tree spec_types,
2049                                       tree tmpl_types)
2050 {
2051   tree new_spec_types;
2052
2053   if (!spec_types)
2054     return NULL_TREE;
2055
2056   if (spec_types == void_list_node)
2057     return void_list_node;
2058
2059   /* Substitute into the rest of the list.  */
2060   new_spec_types =
2061     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2062                                           TREE_CHAIN (tmpl_types));
2063
2064   /* Add the default argument for this parameter.  */
2065   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2066                          TREE_VALUE (spec_types),
2067                          new_spec_types);
2068 }
2069
2070 /* DECL is an explicit specialization.  Replicate default arguments
2071    from the template it specializes.  (That way, code like:
2072
2073      template <class T> void f(T = 3);
2074      template <> void f(double);
2075      void g () { f (); }
2076
2077    works, as required.)  An alternative approach would be to look up
2078    the correct default arguments at the call-site, but this approach
2079    is consistent with how implicit instantiations are handled.  */
2080
2081 static void
2082 copy_default_args_to_explicit_spec (tree decl)
2083 {
2084   tree tmpl;
2085   tree spec_types;
2086   tree tmpl_types;
2087   tree new_spec_types;
2088   tree old_type;
2089   tree new_type;
2090   tree t;
2091   tree object_type = NULL_TREE;
2092   tree in_charge = NULL_TREE;
2093   tree vtt = NULL_TREE;
2094
2095   /* See if there's anything we need to do.  */
2096   tmpl = DECL_TI_TEMPLATE (decl);
2097   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2098   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2099     if (TREE_PURPOSE (t))
2100       break;
2101   if (!t)
2102     return;
2103
2104   old_type = TREE_TYPE (decl);
2105   spec_types = TYPE_ARG_TYPES (old_type);
2106
2107   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2108     {
2109       /* Remove the this pointer, but remember the object's type for
2110          CV quals.  */
2111       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2112       spec_types = TREE_CHAIN (spec_types);
2113       tmpl_types = TREE_CHAIN (tmpl_types);
2114
2115       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2116         {
2117           /* DECL may contain more parameters than TMPL due to the extra
2118              in-charge parameter in constructors and destructors.  */
2119           in_charge = spec_types;
2120           spec_types = TREE_CHAIN (spec_types);
2121         }
2122       if (DECL_HAS_VTT_PARM_P (decl))
2123         {
2124           vtt = spec_types;
2125           spec_types = TREE_CHAIN (spec_types);
2126         }
2127     }
2128
2129   /* Compute the merged default arguments.  */
2130   new_spec_types =
2131     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2132
2133   /* Compute the new FUNCTION_TYPE.  */
2134   if (object_type)
2135     {
2136       if (vtt)
2137         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2138                                          TREE_VALUE (vtt),
2139                                          new_spec_types);
2140
2141       if (in_charge)
2142         /* Put the in-charge parameter back.  */
2143         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2144                                          TREE_VALUE (in_charge),
2145                                          new_spec_types);
2146
2147       new_type = build_method_type_directly (object_type,
2148                                              TREE_TYPE (old_type),
2149                                              new_spec_types);
2150     }
2151   else
2152     new_type = build_function_type (TREE_TYPE (old_type),
2153                                     new_spec_types);
2154   new_type = cp_build_type_attribute_variant (new_type,
2155                                               TYPE_ATTRIBUTES (old_type));
2156   new_type = build_exception_variant (new_type,
2157                                       TYPE_RAISES_EXCEPTIONS (old_type));
2158   TREE_TYPE (decl) = new_type;
2159 }
2160
2161 /* Check to see if the function just declared, as indicated in
2162    DECLARATOR, and in DECL, is a specialization of a function
2163    template.  We may also discover that the declaration is an explicit
2164    instantiation at this point.
2165
2166    Returns DECL, or an equivalent declaration that should be used
2167    instead if all goes well.  Issues an error message if something is
2168    amiss.  Returns error_mark_node if the error is not easily
2169    recoverable.
2170
2171    FLAGS is a bitmask consisting of the following flags:
2172
2173    2: The function has a definition.
2174    4: The function is a friend.
2175
2176    The TEMPLATE_COUNT is the number of references to qualifying
2177    template classes that appeared in the name of the function.  For
2178    example, in
2179
2180      template <class T> struct S { void f(); };
2181      void S<int>::f();
2182
2183    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2184    classes are not counted in the TEMPLATE_COUNT, so that in
2185
2186      template <class T> struct S {};
2187      template <> struct S<int> { void f(); }
2188      template <> void S<int>::f();
2189
2190    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2191    invalid; there should be no template <>.)
2192
2193    If the function is a specialization, it is marked as such via
2194    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2195    is set up correctly, and it is added to the list of specializations
2196    for that template.  */
2197
2198 tree
2199 check_explicit_specialization (tree declarator,
2200                                tree decl,
2201                                int template_count,
2202                                int flags)
2203 {
2204   int have_def = flags & 2;
2205   int is_friend = flags & 4;
2206   int specialization = 0;
2207   int explicit_instantiation = 0;
2208   int member_specialization = 0;
2209   tree ctype = DECL_CLASS_CONTEXT (decl);
2210   tree dname = DECL_NAME (decl);
2211   tmpl_spec_kind tsk;
2212
2213   if (is_friend)
2214     {
2215       if (!processing_specialization)
2216         tsk = tsk_none;
2217       else
2218         tsk = tsk_excessive_parms;
2219     }
2220   else
2221     tsk = current_tmpl_spec_kind (template_count);
2222
2223   switch (tsk)
2224     {
2225     case tsk_none:
2226       if (processing_specialization)
2227         {
2228           specialization = 1;
2229           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2230         }
2231       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2232         {
2233           if (is_friend)
2234             /* This could be something like:
2235
2236                template <class T> void f(T);
2237                class S { friend void f<>(int); }  */
2238             specialization = 1;
2239           else
2240             {
2241               /* This case handles bogus declarations like template <>
2242                  template <class T> void f<int>(); */
2243
2244               error ("template-id %qD in declaration of primary template",
2245                      declarator);
2246               return decl;
2247             }
2248         }
2249       break;
2250
2251     case tsk_invalid_member_spec:
2252       /* The error has already been reported in
2253          check_specialization_scope.  */
2254       return error_mark_node;
2255
2256     case tsk_invalid_expl_inst:
2257       error ("template parameter list used in explicit instantiation");
2258
2259       /* Fall through.  */
2260
2261     case tsk_expl_inst:
2262       if (have_def)
2263         error ("definition provided for explicit instantiation");
2264
2265       explicit_instantiation = 1;
2266       break;
2267
2268     case tsk_excessive_parms:
2269     case tsk_insufficient_parms:
2270       if (tsk == tsk_excessive_parms)
2271         error ("too many template parameter lists in declaration of %qD",
2272                decl);
2273       else if (template_header_count)
2274         error("too few template parameter lists in declaration of %qD", decl);
2275       else
2276         error("explicit specialization of %qD must be introduced by "
2277               "%<template <>%>", decl);
2278
2279       /* Fall through.  */
2280     case tsk_expl_spec:
2281       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2282       if (ctype)
2283         member_specialization = 1;
2284       else
2285         specialization = 1;
2286       break;
2287
2288     case tsk_template:
2289       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2290         {
2291           /* This case handles bogus declarations like template <>
2292              template <class T> void f<int>(); */
2293
2294           if (uses_template_parms (declarator))
2295             error ("function template partial specialization %qD "
2296                    "is not allowed", declarator);
2297           else
2298             error ("template-id %qD in declaration of primary template",
2299                    declarator);
2300           return decl;
2301         }
2302
2303       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2304         /* This is a specialization of a member template, without
2305            specialization the containing class.  Something like:
2306
2307              template <class T> struct S {
2308                template <class U> void f (U);
2309              };
2310              template <> template <class U> void S<int>::f(U) {}
2311
2312            That's a specialization -- but of the entire template.  */
2313         specialization = 1;
2314       break;
2315
2316     default:
2317       gcc_unreachable ();
2318     }
2319
2320   if (specialization || member_specialization)
2321     {
2322       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2323       for (; t; t = TREE_CHAIN (t))
2324         if (TREE_PURPOSE (t))
2325           {
2326             permerror (input_location, 
2327                        "default argument specified in explicit specialization");
2328             break;
2329           }
2330     }
2331
2332   if (specialization || member_specialization || explicit_instantiation)
2333     {
2334       tree tmpl = NULL_TREE;
2335       tree targs = NULL_TREE;
2336
2337       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2338       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2339         {
2340           tree fns;
2341
2342           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2343           if (ctype)
2344             fns = dname;
2345           else
2346             {
2347               /* If there is no class context, the explicit instantiation
2348                  must be at namespace scope.  */
2349               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2350
2351               /* Find the namespace binding, using the declaration
2352                  context.  */
2353               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2354                                            false, true);
2355               if (fns == error_mark_node || !is_overloaded_fn (fns))
2356                 {
2357                   error ("%qD is not a template function", dname);
2358                   fns = error_mark_node;
2359                 }
2360               else
2361                 {
2362                   tree fn = OVL_CURRENT (fns);
2363                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2364                                                 CP_DECL_CONTEXT (fn)))
2365                     error ("%qD is not declared in %qD",
2366                            decl, current_namespace);
2367                 }
2368             }
2369
2370           declarator = lookup_template_function (fns, NULL_TREE);
2371         }
2372
2373       if (declarator == error_mark_node)
2374         return error_mark_node;
2375
2376       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2377         {
2378           if (!explicit_instantiation)
2379             /* A specialization in class scope.  This is invalid,
2380                but the error will already have been flagged by
2381                check_specialization_scope.  */
2382             return error_mark_node;
2383           else
2384             {
2385               /* It's not valid to write an explicit instantiation in
2386                  class scope, e.g.:
2387
2388                    class C { template void f(); }
2389
2390                    This case is caught by the parser.  However, on
2391                    something like:
2392
2393                    template class C { void f(); };
2394
2395                    (which is invalid) we can get here.  The error will be
2396                    issued later.  */
2397               ;
2398             }
2399
2400           return decl;
2401         }
2402       else if (ctype != NULL_TREE
2403                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2404                    IDENTIFIER_NODE))
2405         {
2406           /* Find the list of functions in ctype that have the same
2407              name as the declared function.  */
2408           tree name = TREE_OPERAND (declarator, 0);
2409           tree fns = NULL_TREE;
2410           int idx;
2411
2412           if (constructor_name_p (name, ctype))
2413             {
2414               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2415
2416               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2417                   : !CLASSTYPE_DESTRUCTORS (ctype))
2418                 {
2419                   /* From [temp.expl.spec]:
2420
2421                      If such an explicit specialization for the member
2422                      of a class template names an implicitly-declared
2423                      special member function (clause _special_), the
2424                      program is ill-formed.
2425
2426                      Similar language is found in [temp.explicit].  */
2427                   error ("specialization of implicitly-declared special member function");
2428                   return error_mark_node;
2429                 }
2430
2431               name = is_constructor ? ctor_identifier : dtor_identifier;
2432             }
2433
2434           if (!DECL_CONV_FN_P (decl))
2435             {
2436               idx = lookup_fnfields_1 (ctype, name);
2437               if (idx >= 0)
2438                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2439             }
2440           else
2441             {
2442               VEC(tree,gc) *methods;
2443               tree ovl;
2444
2445               /* For a type-conversion operator, we cannot do a
2446                  name-based lookup.  We might be looking for `operator
2447                  int' which will be a specialization of `operator T'.
2448                  So, we find *all* the conversion operators, and then
2449                  select from them.  */
2450               fns = NULL_TREE;
2451
2452               methods = CLASSTYPE_METHOD_VEC (ctype);
2453               if (methods)
2454                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2455                      VEC_iterate (tree, methods, idx, ovl);
2456                      ++idx)
2457                   {
2458                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2459                       /* There are no more conversion functions.  */
2460                       break;
2461
2462                     /* Glue all these conversion functions together
2463                        with those we already have.  */
2464                     for (; ovl; ovl = OVL_NEXT (ovl))
2465                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2466                   }
2467             }
2468
2469           if (fns == NULL_TREE)
2470             {
2471               error ("no member function %qD declared in %qT", name, ctype);
2472               return error_mark_node;
2473             }
2474           else
2475             TREE_OPERAND (declarator, 0) = fns;
2476         }
2477
2478       /* Figure out what exactly is being specialized at this point.
2479          Note that for an explicit instantiation, even one for a
2480          member function, we cannot tell apriori whether the
2481          instantiation is for a member template, or just a member
2482          function of a template class.  Even if a member template is
2483          being instantiated, the member template arguments may be
2484          elided if they can be deduced from the rest of the
2485          declaration.  */
2486       tmpl = determine_specialization (declarator, decl,
2487                                        &targs,
2488                                        member_specialization,
2489                                        template_count,
2490                                        tsk);
2491
2492       if (!tmpl || tmpl == error_mark_node)
2493         /* We couldn't figure out what this declaration was
2494            specializing.  */
2495         return error_mark_node;
2496       else
2497         {
2498           tree gen_tmpl = most_general_template (tmpl);
2499
2500           if (explicit_instantiation)
2501             {
2502               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2503                  is done by do_decl_instantiation later.  */
2504
2505               int arg_depth = TMPL_ARGS_DEPTH (targs);
2506               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2507
2508               if (arg_depth > parm_depth)
2509                 {
2510                   /* If TMPL is not the most general template (for
2511                      example, if TMPL is a friend template that is
2512                      injected into namespace scope), then there will
2513                      be too many levels of TARGS.  Remove some of them
2514                      here.  */
2515                   int i;
2516                   tree new_targs;
2517
2518                   new_targs = make_tree_vec (parm_depth);
2519                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2520                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2521                       = TREE_VEC_ELT (targs, i);
2522                   targs = new_targs;
2523                 }
2524
2525               return instantiate_template (tmpl, targs, tf_error);
2526             }
2527
2528           /* If we thought that the DECL was a member function, but it
2529              turns out to be specializing a static member function,
2530              make DECL a static member function as well.  */
2531           if (DECL_STATIC_FUNCTION_P (tmpl)
2532               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2533             revert_static_member_fn (decl);
2534
2535           /* If this is a specialization of a member template of a
2536              template class, we want to return the TEMPLATE_DECL, not
2537              the specialization of it.  */
2538           if (tsk == tsk_template)
2539             {
2540               tree result = DECL_TEMPLATE_RESULT (tmpl);
2541               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2542               DECL_INITIAL (result) = NULL_TREE;
2543               if (have_def)
2544                 {
2545                   tree parm;
2546                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2547                   DECL_SOURCE_LOCATION (result)
2548                     = DECL_SOURCE_LOCATION (decl);
2549                   /* We want to use the argument list specified in the
2550                      definition, not in the original declaration.  */
2551                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2552                   for (parm = DECL_ARGUMENTS (result); parm;
2553                        parm = TREE_CHAIN (parm))
2554                     DECL_CONTEXT (parm) = result;
2555                 }
2556               return register_specialization (tmpl, gen_tmpl, targs,
2557                                               is_friend, 0);
2558             }
2559
2560           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2561           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2562
2563           /* Inherit default function arguments from the template
2564              DECL is specializing.  */
2565           copy_default_args_to_explicit_spec (decl);
2566
2567           /* This specialization has the same protection as the
2568              template it specializes.  */
2569           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2570           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2571
2572           /* 7.1.1-1 [dcl.stc]
2573
2574              A storage-class-specifier shall not be specified in an
2575              explicit specialization...
2576
2577              The parser rejects these, so unless action is taken here,
2578              explicit function specializations will always appear with
2579              global linkage.
2580
2581              The action recommended by the C++ CWG in response to C++
2582              defect report 605 is to make the storage class and linkage
2583              of the explicit specialization match the templated function:
2584
2585              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2586            */
2587           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2588             {
2589               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2590               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2591
2592               /* This specialization has the same linkage and visibility as
2593                  the function template it specializes.  */
2594               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2595               if (! TREE_PUBLIC (decl))
2596                 {
2597                   DECL_INTERFACE_KNOWN (decl) = 1;
2598                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2599                 }
2600               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2601               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2602                 {
2603                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2604                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2605                 }
2606             }
2607
2608           /* If DECL is a friend declaration, declared using an
2609              unqualified name, the namespace associated with DECL may
2610              have been set incorrectly.  For example, in:
2611
2612                template <typename T> void f(T);
2613                namespace N {
2614                  struct S { friend void f<int>(int); }
2615                }
2616
2617              we will have set the DECL_CONTEXT for the friend
2618              declaration to N, rather than to the global namespace.  */
2619           if (DECL_NAMESPACE_SCOPE_P (decl))
2620             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2621
2622           if (is_friend && !have_def)
2623             /* This is not really a declaration of a specialization.
2624                It's just the name of an instantiation.  But, it's not
2625                a request for an instantiation, either.  */
2626             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2627           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2628             /* This is indeed a specialization.  In case of constructors
2629                and destructors, we need in-charge and not-in-charge
2630                versions in V3 ABI.  */
2631             clone_function_decl (decl, /*update_method_vec_p=*/0);
2632
2633           /* Register this specialization so that we can find it
2634              again.  */
2635           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2636         }
2637     }
2638
2639   return decl;
2640 }
2641
2642 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2643    parameters.  These are represented in the same format used for
2644    DECL_TEMPLATE_PARMS.  */
2645
2646 int
2647 comp_template_parms (const_tree parms1, const_tree parms2)
2648 {
2649   const_tree p1;
2650   const_tree p2;
2651
2652   if (parms1 == parms2)
2653     return 1;
2654
2655   for (p1 = parms1, p2 = parms2;
2656        p1 != NULL_TREE && p2 != NULL_TREE;
2657        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2658     {
2659       tree t1 = TREE_VALUE (p1);
2660       tree t2 = TREE_VALUE (p2);
2661       int i;
2662
2663       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2664       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2665
2666       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2667         return 0;
2668
2669       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2670         {
2671           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2672           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2673
2674           /* If either of the template parameters are invalid, assume
2675              they match for the sake of error recovery. */
2676           if (parm1 == error_mark_node || parm2 == error_mark_node)
2677             return 1;
2678
2679           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2680             return 0;
2681
2682           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2683               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2684                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2685             continue;
2686           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2687             return 0;
2688         }
2689     }
2690
2691   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2692     /* One set of parameters has more parameters lists than the
2693        other.  */
2694     return 0;
2695
2696   return 1;
2697 }
2698
2699 /* Determine whether PARM is a parameter pack.  */
2700
2701 bool 
2702 template_parameter_pack_p (const_tree parm)
2703 {
2704   /* Determine if we have a non-type template parameter pack.  */
2705   if (TREE_CODE (parm) == PARM_DECL)
2706     return (DECL_TEMPLATE_PARM_P (parm) 
2707             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2708
2709   /* If this is a list of template parameters, we could get a
2710      TYPE_DECL or a TEMPLATE_DECL.  */ 
2711   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2712     parm = TREE_TYPE (parm);
2713
2714   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2715            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2716           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2717 }
2718
2719 /* Determine if T is a function parameter pack.  */
2720
2721 bool
2722 function_parameter_pack_p (const_tree t)
2723 {
2724   if (t && TREE_CODE (t) == PARM_DECL)
2725     return FUNCTION_PARAMETER_PACK_P (t);
2726   return false;
2727 }
2728
2729 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2730    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2731
2732 tree
2733 get_function_template_decl (const_tree primary_func_tmpl_inst)
2734 {
2735   if (! primary_func_tmpl_inst
2736       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2737       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2738     return NULL;
2739
2740   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2741 }
2742
2743 /* Return true iff the function parameter PARAM_DECL was expanded
2744    from the function parameter pack PACK.  */
2745
2746 bool
2747 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2748 {
2749   if (DECL_ARTIFICIAL (param_decl)
2750       || !function_parameter_pack_p (pack))
2751     return false;
2752
2753   /* The parameter pack and its pack arguments have the same
2754      DECL_PARM_INDEX.  */
2755   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2756 }
2757
2758 /* Determine whether ARGS describes a variadic template args list,
2759    i.e., one that is terminated by a template argument pack.  */
2760
2761 static bool 
2762 template_args_variadic_p (tree args)
2763 {
2764   int nargs;
2765   tree last_parm;
2766
2767   if (args == NULL_TREE)
2768     return false;
2769
2770   args = INNERMOST_TEMPLATE_ARGS (args);
2771   nargs = TREE_VEC_LENGTH (args);
2772
2773   if (nargs == 0)
2774     return false;
2775
2776   last_parm = TREE_VEC_ELT (args, nargs - 1);
2777
2778   return ARGUMENT_PACK_P (last_parm);
2779 }
2780
2781 /* Generate a new name for the parameter pack name NAME (an
2782    IDENTIFIER_NODE) that incorporates its */
2783
2784 static tree
2785 make_ith_pack_parameter_name (tree name, int i)
2786 {
2787   /* Munge the name to include the parameter index.  */
2788 #define NUMBUF_LEN 128
2789   char numbuf[NUMBUF_LEN];
2790   char* newname;
2791   int newname_len;
2792
2793   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2794   newname_len = IDENTIFIER_LENGTH (name)
2795                 + strlen (numbuf) + 2;
2796   newname = (char*)alloca (newname_len);
2797   snprintf (newname, newname_len,
2798             "%s#%i", IDENTIFIER_POINTER (name), i);
2799   return get_identifier (newname);
2800 }
2801
2802 /* Return true if T is a primary function
2803    or class template instantiation.  */
2804
2805 bool
2806 primary_template_instantiation_p (const_tree t)
2807 {
2808   if (!t)
2809     return false;
2810
2811   if (TREE_CODE (t) == FUNCTION_DECL)
2812     return DECL_LANG_SPECIFIC (t)
2813            && DECL_TEMPLATE_INSTANTIATION (t)
2814            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2815   else if (CLASS_TYPE_P (t))
2816     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2817            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2818   return false;
2819 }
2820
2821 /* Return true if PARM is a template template parameter.  */
2822
2823 bool
2824 template_template_parameter_p (const_tree parm)
2825 {
2826   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2827 }
2828
2829 /* Return the template parameters of T if T is a
2830    primary template instantiation, NULL otherwise.  */
2831
2832 tree
2833 get_primary_template_innermost_parameters (const_tree t)
2834 {
2835   tree parms = NULL, template_info = NULL;
2836
2837   if ((template_info = get_template_info (t))
2838       && primary_template_instantiation_p (t))
2839     parms = INNERMOST_TEMPLATE_PARMS
2840         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2841
2842   return parms;
2843 }
2844
2845 /* Return the template parameters of the LEVELth level from the full list
2846    of template parameters PARMS.  */
2847
2848 tree
2849 get_template_parms_at_level (tree parms, int level)
2850 {
2851   tree p;
2852   if (!parms
2853       || TREE_CODE (parms) != TREE_LIST
2854       || level > TMPL_PARMS_DEPTH (parms))
2855     return NULL_TREE;
2856
2857   for (p = parms; p; p = TREE_CHAIN (p))
2858     if (TMPL_PARMS_DEPTH (p) == level)
2859       return p;
2860
2861   return NULL_TREE;
2862 }
2863
2864 /* Returns the template arguments of T if T is a template instantiation,
2865    NULL otherwise.  */
2866
2867 tree
2868 get_template_innermost_arguments (const_tree t)
2869 {
2870   tree args = NULL, template_info = NULL;
2871
2872   if ((template_info = get_template_info (t))
2873       && TI_ARGS (template_info))
2874     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2875
2876   return args;
2877 }
2878
2879 /* Return the argument pack elements of T if T is a template argument pack,
2880    NULL otherwise.  */
2881
2882 tree
2883 get_template_argument_pack_elems (const_tree t)
2884 {
2885   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2886       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2887     return NULL;
2888
2889   return ARGUMENT_PACK_ARGS (t);
2890 }
2891
2892 /* Structure used to track the progress of find_parameter_packs_r.  */
2893 struct find_parameter_pack_data 
2894 {
2895   /* TREE_LIST that will contain all of the parameter packs found by
2896      the traversal.  */
2897   tree* parameter_packs;
2898
2899   /* Set of AST nodes that have been visited by the traversal.  */
2900   struct pointer_set_t *visited;
2901 };
2902
2903 /* Identifies all of the argument packs that occur in a template
2904    argument and appends them to the TREE_LIST inside DATA, which is a
2905    find_parameter_pack_data structure. This is a subroutine of
2906    make_pack_expansion and uses_parameter_packs.  */
2907 static tree
2908 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2909 {
2910   tree t = *tp;
2911   struct find_parameter_pack_data* ppd = 
2912     (struct find_parameter_pack_data*)data;
2913   bool parameter_pack_p = false;
2914
2915   /* Identify whether this is a parameter pack or not.  */
2916   switch (TREE_CODE (t))
2917     {
2918     case TEMPLATE_PARM_INDEX:
2919       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2920         parameter_pack_p = true;
2921       break;
2922
2923     case TEMPLATE_TYPE_PARM:
2924     case TEMPLATE_TEMPLATE_PARM:
2925       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2926         parameter_pack_p = true;
2927       break;
2928
2929     case PARM_DECL:
2930       if (FUNCTION_PARAMETER_PACK_P (t))
2931         {
2932           /* We don't want to walk into the type of a PARM_DECL,
2933              because we don't want to see the type parameter pack.  */
2934           *walk_subtrees = 0;
2935           parameter_pack_p = true;
2936         }
2937       break;
2938
2939     default:
2940       /* Not a parameter pack.  */
2941       break;
2942     }
2943
2944   if (parameter_pack_p)
2945     {
2946       /* Add this parameter pack to the list.  */
2947       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2948     }
2949
2950   if (TYPE_P (t))
2951     cp_walk_tree (&TYPE_CONTEXT (t), 
2952                   &find_parameter_packs_r, ppd, ppd->visited);
2953
2954   /* This switch statement will return immediately if we don't find a
2955      parameter pack.  */
2956   switch (TREE_CODE (t)) 
2957     {
2958     case TEMPLATE_PARM_INDEX:
2959       return NULL_TREE;
2960
2961     case BOUND_TEMPLATE_TEMPLATE_PARM:
2962       /* Check the template itself.  */
2963       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2964                     &find_parameter_packs_r, ppd, ppd->visited);
2965       /* Check the template arguments.  */
2966       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2967                     ppd->visited);
2968       *walk_subtrees = 0;
2969       return NULL_TREE;
2970
2971     case TEMPLATE_TYPE_PARM:
2972     case TEMPLATE_TEMPLATE_PARM:
2973       return NULL_TREE;
2974
2975     case PARM_DECL:
2976       return NULL_TREE;
2977
2978     case RECORD_TYPE:
2979       if (TYPE_PTRMEMFUNC_P (t))
2980         return NULL_TREE;
2981       /* Fall through.  */
2982
2983     case UNION_TYPE:
2984     case ENUMERAL_TYPE:
2985       if (TYPE_TEMPLATE_INFO (t))
2986         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2987                       &find_parameter_packs_r, ppd, ppd->visited);
2988
2989       *walk_subtrees = 0;
2990       return NULL_TREE;
2991
2992     case TEMPLATE_DECL:
2993       cp_walk_tree (&TREE_TYPE (t),
2994                     &find_parameter_packs_r, ppd, ppd->visited);
2995       return NULL_TREE;
2996  
2997     case TYPENAME_TYPE:
2998       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2999                    ppd, ppd->visited);
3000       *walk_subtrees = 0;
3001       return NULL_TREE;
3002       
3003     case TYPE_PACK_EXPANSION:
3004     case EXPR_PACK_EXPANSION:
3005       *walk_subtrees = 0;
3006       return NULL_TREE;
3007
3008     case INTEGER_TYPE:
3009       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3010                     ppd, ppd->visited);
3011       *walk_subtrees = 0;
3012       return NULL_TREE;
3013
3014     case IDENTIFIER_NODE:
3015       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3016                     ppd->visited);
3017       *walk_subtrees = 0;
3018       return NULL_TREE;
3019
3020     default:
3021       return NULL_TREE;
3022     }
3023
3024   return NULL_TREE;
3025 }
3026
3027 /* Determines if the expression or type T uses any parameter packs.  */
3028 bool
3029 uses_parameter_packs (tree t)
3030 {
3031   tree parameter_packs = NULL_TREE;
3032   struct find_parameter_pack_data ppd;
3033   ppd.parameter_packs = &parameter_packs;
3034   ppd.visited = pointer_set_create ();
3035   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3036   pointer_set_destroy (ppd.visited);
3037   return parameter_packs != NULL_TREE;
3038 }
3039
3040 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3041    representation a base-class initializer into a parameter pack
3042    expansion. If all goes well, the resulting node will be an
3043    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3044    respectively.  */
3045 tree 
3046 make_pack_expansion (tree arg)
3047 {
3048   tree result;
3049   tree parameter_packs = NULL_TREE;
3050   bool for_types = false;
3051   struct find_parameter_pack_data ppd;
3052
3053   if (!arg || arg == error_mark_node)
3054     return arg;
3055
3056   if (TREE_CODE (arg) == TREE_LIST)
3057     {
3058       /* The only time we will see a TREE_LIST here is for a base
3059          class initializer.  In this case, the TREE_PURPOSE will be a
3060          _TYPE node (representing the base class expansion we're
3061          initializing) and the TREE_VALUE will be a TREE_LIST
3062          containing the initialization arguments. 
3063
3064          The resulting expansion looks somewhat different from most
3065          expansions. Rather than returning just one _EXPANSION, we
3066          return a TREE_LIST whose TREE_PURPOSE is a
3067          TYPE_PACK_EXPANSION containing the bases that will be
3068          initialized.  The TREE_VALUE will be identical to the
3069          original TREE_VALUE, which is a list of arguments that will
3070          be passed to each base.  We do not introduce any new pack
3071          expansion nodes into the TREE_VALUE (although it is possible
3072          that some already exist), because the TREE_PURPOSE and
3073          TREE_VALUE all need to be expanded together with the same
3074          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3075          resulting TREE_PURPOSE will mention the parameter packs in
3076          both the bases and the arguments to the bases.  */
3077       tree purpose;
3078       tree value;
3079       tree parameter_packs = NULL_TREE;
3080
3081       /* Determine which parameter packs will be used by the base
3082          class expansion.  */
3083       ppd.visited = pointer_set_create ();
3084       ppd.parameter_packs = &parameter_packs;
3085       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3086                     &ppd, ppd.visited);
3087
3088       if (parameter_packs == NULL_TREE)
3089         {
3090           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3091           pointer_set_destroy (ppd.visited);
3092           return error_mark_node;
3093         }
3094
3095       if (TREE_VALUE (arg) != void_type_node)
3096         {
3097           /* Collect the sets of parameter packs used in each of the
3098              initialization arguments.  */
3099           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3100             {
3101               /* Determine which parameter packs will be expanded in this
3102                  argument.  */
3103               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3104                             &ppd, ppd.visited);
3105             }
3106         }
3107
3108       pointer_set_destroy (ppd.visited);
3109
3110       /* Create the pack expansion type for the base type.  */
3111       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3112       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3113       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3114
3115       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3116          they will rarely be compared to anything.  */
3117       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3118
3119       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3120     }
3121
3122   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3123     for_types = true;
3124
3125   /* Build the PACK_EXPANSION_* node.  */
3126   result = for_types
3127      ? cxx_make_type (TYPE_PACK_EXPANSION)
3128      : make_node (EXPR_PACK_EXPANSION);
3129   SET_PACK_EXPANSION_PATTERN (result, arg);
3130   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3131     {
3132       /* Propagate type and const-expression information.  */
3133       TREE_TYPE (result) = TREE_TYPE (arg);
3134       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3135     }
3136   else
3137     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3138        they will rarely be compared to anything.  */
3139     SET_TYPE_STRUCTURAL_EQUALITY (result);
3140
3141   /* Determine which parameter packs will be expanded.  */
3142   ppd.parameter_packs = &parameter_packs;
3143   ppd.visited = pointer_set_create ();
3144   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3145   pointer_set_destroy (ppd.visited);
3146
3147   /* Make sure we found some parameter packs.  */
3148   if (parameter_packs == NULL_TREE)
3149     {
3150       if (TYPE_P (arg))
3151         error ("expansion pattern %<%T%> contains no argument packs", arg);
3152       else
3153         error ("expansion pattern %<%E%> contains no argument packs", arg);
3154       return error_mark_node;
3155     }
3156   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3157
3158   return result;
3159 }
3160
3161 /* Checks T for any "bare" parameter packs, which have not yet been
3162    expanded, and issues an error if any are found. This operation can
3163    only be done on full expressions or types (e.g., an expression
3164    statement, "if" condition, etc.), because we could have expressions like:
3165
3166      foo(f(g(h(args)))...)
3167
3168    where "args" is a parameter pack. check_for_bare_parameter_packs
3169    should not be called for the subexpressions args, h(args),
3170    g(h(args)), or f(g(h(args))), because we would produce erroneous
3171    error messages. 
3172
3173    Returns TRUE and emits an error if there were bare parameter packs,
3174    returns FALSE otherwise.  */
3175 bool 
3176 check_for_bare_parameter_packs (tree t)
3177 {
3178   tree parameter_packs = NULL_TREE;
3179   struct find_parameter_pack_data ppd;
3180
3181   if (!processing_template_decl || !t || t == error_mark_node)
3182     return false;
3183
3184   if (TREE_CODE (t) == TYPE_DECL)
3185     t = TREE_TYPE (t);
3186
3187   ppd.parameter_packs = &parameter_packs;
3188   ppd.visited = pointer_set_create ();
3189   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3190   pointer_set_destroy (ppd.visited);
3191
3192   if (parameter_packs) 
3193     {
3194       error ("parameter packs not expanded with %<...%>:");
3195       while (parameter_packs)
3196         {
3197           tree pack = TREE_VALUE (parameter_packs);
3198           tree name = NULL_TREE;
3199
3200           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3201               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3202             name = TYPE_NAME (pack);
3203           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3204             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3205           else
3206             name = DECL_NAME (pack);
3207
3208           if (name)
3209             inform (input_location, "        %qD", name);
3210           else
3211             inform (input_location, "        <anonymous>");
3212
3213           parameter_packs = TREE_CHAIN (parameter_packs);
3214         }
3215
3216       return true;
3217     }
3218
3219   return false;
3220 }
3221
3222 /* Expand any parameter packs that occur in the template arguments in
3223    ARGS.  */
3224 tree
3225 expand_template_argument_pack (tree args)
3226 {
3227   tree result_args = NULL_TREE;
3228   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3229   int num_result_args = -1;
3230   int non_default_args_count = -1;
3231
3232   /* First, determine if we need to expand anything, and the number of
3233      slots we'll need.  */
3234   for (in_arg = 0; in_arg < nargs; ++in_arg)
3235     {
3236       tree arg = TREE_VEC_ELT (args, in_arg);
3237       if (arg == NULL_TREE)
3238         return args;
3239       if (ARGUMENT_PACK_P (arg))
3240         {
3241           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3242           if (num_result_args < 0)
3243             num_result_args = in_arg + num_packed;
3244           else
3245             num_result_args += num_packed;
3246         }
3247       else
3248         {
3249           if (num_result_args >= 0)
3250             num_result_args++;
3251         }
3252     }
3253
3254   /* If no expansion is necessary, we're done.  */
3255   if (num_result_args < 0)
3256     return args;
3257
3258   /* Expand arguments.  */
3259   result_args = make_tree_vec (num_result_args);
3260   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3261     non_default_args_count =
3262       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3263   for (in_arg = 0; in_arg < nargs; ++in_arg)
3264     {
3265       tree arg = TREE_VEC_ELT (args, in_arg);
3266       if (ARGUMENT_PACK_P (arg))
3267         {
3268           tree packed = ARGUMENT_PACK_ARGS (arg);
3269           int i, num_packed = TREE_VEC_LENGTH (packed);
3270           for (i = 0; i < num_packed; ++i, ++out_arg)
3271             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3272           if (non_default_args_count > 0)
3273             non_default_args_count += num_packed;
3274         }
3275       else
3276         {
3277           TREE_VEC_ELT (result_args, out_arg) = arg;
3278           ++out_arg;
3279         }
3280     }
3281   if (non_default_args_count >= 0)
3282     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3283   return result_args;
3284 }
3285
3286 /* Checks if DECL shadows a template parameter.
3287
3288    [temp.local]: A template-parameter shall not be redeclared within its
3289    scope (including nested scopes).
3290
3291    Emits an error and returns TRUE if the DECL shadows a parameter,
3292    returns FALSE otherwise.  */
3293
3294 bool
3295 check_template_shadow (tree decl)
3296 {
3297   tree olddecl;
3298
3299   /* If we're not in a template, we can't possibly shadow a template
3300      parameter.  */
3301   if (!current_template_parms)
3302     return true;
3303
3304   /* Figure out what we're shadowing.  */
3305   if (TREE_CODE (decl) == OVERLOAD)
3306     decl = OVL_CURRENT (decl);
3307   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3308
3309   /* If there's no previous binding for this name, we're not shadowing
3310      anything, let alone a template parameter.  */
3311   if (!olddecl)
3312     return true;
3313
3314   /* If we're not shadowing a template parameter, we're done.  Note
3315      that OLDDECL might be an OVERLOAD (or perhaps even an
3316      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3317      node.  */
3318   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3319     return true;
3320
3321   /* We check for decl != olddecl to avoid bogus errors for using a
3322      name inside a class.  We check TPFI to avoid duplicate errors for
3323      inline member templates.  */
3324   if (decl == olddecl
3325       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3326     return true;
3327
3328   error ("declaration of %q+#D", decl);
3329   error (" shadows template parm %q+#D", olddecl);
3330   return false;
3331 }
3332
3333 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3334    ORIG_LEVEL, DECL, and TYPE.  */
3335
3336 static tree
3337 build_template_parm_index (int index,
3338                            int level,
3339                            int orig_level,
3340                            tree decl,
3341                            tree type)
3342 {
3343   tree t = make_node (TEMPLATE_PARM_INDEX);
3344   TEMPLATE_PARM_IDX (t) = index;
3345   TEMPLATE_PARM_LEVEL (t) = level;
3346   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3347   TEMPLATE_PARM_DECL (t) = decl;
3348   TREE_TYPE (t) = type;
3349   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3350   TREE_READONLY (t) = TREE_READONLY (decl);
3351
3352   return t;
3353 }
3354
3355 /* Find the canonical type parameter for the given template type
3356    parameter.  Returns the canonical type parameter, which may be TYPE
3357    if no such parameter existed.  */
3358 static tree
3359 canonical_type_parameter (tree type)
3360 {
3361   tree list;
3362   int idx = TEMPLATE_TYPE_IDX (type);
3363   if (!canonical_template_parms)
3364     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3365
3366   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3367     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3368
3369   list = VEC_index (tree, canonical_template_parms, idx);
3370   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3371     list = TREE_CHAIN (list);
3372
3373   if (list)
3374     return TREE_VALUE (list);
3375   else
3376     {
3377       VEC_replace(tree, canonical_template_parms, idx,
3378                   tree_cons (NULL_TREE, type, 
3379                              VEC_index (tree, canonical_template_parms, idx)));
3380       return type;
3381     }
3382 }
3383
3384 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3385    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3386    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3387    new one is created.  */
3388
3389 static tree
3390 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3391                             tsubst_flags_t complain)
3392 {
3393   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3394       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3395           != TEMPLATE_PARM_LEVEL (index) - levels)
3396       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3397     {
3398       tree orig_decl = TEMPLATE_PARM_DECL (index);
3399       tree decl, t;
3400
3401       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3402                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3403       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3404       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3405       DECL_ARTIFICIAL (decl) = 1;
3406       SET_DECL_TEMPLATE_PARM_P (decl);
3407
3408       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3409                                      TEMPLATE_PARM_LEVEL (index) - levels,
3410                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3411                                      decl, type);
3412       TEMPLATE_PARM_DESCENDANTS (index) = t;
3413       TEMPLATE_PARM_PARAMETER_PACK (t) 
3414         = TEMPLATE_PARM_PARAMETER_PACK (index);
3415
3416         /* Template template parameters need this.  */
3417       if (TREE_CODE (decl) == TEMPLATE_DECL)
3418         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3419           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3420            args, complain);
3421     }
3422
3423   return TEMPLATE_PARM_DESCENDANTS (index);
3424 }
3425
3426 /* Process information from new template parameter PARM and append it to the
3427    LIST being built.  This new parameter is a non-type parameter iff
3428    IS_NON_TYPE is true. This new parameter is a parameter
3429    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3430    PARM_LOC.  */
3431
3432 tree
3433 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3434                        bool is_parameter_pack)
3435 {
3436   tree decl = 0;
3437   tree defval;
3438   tree err_parm_list;
3439   int idx = 0;
3440
3441   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3442   defval = TREE_PURPOSE (parm);
3443
3444   if (list)
3445     {
3446       tree p = tree_last (list);
3447
3448       if (p && TREE_VALUE (p) != error_mark_node)
3449         {
3450           p = TREE_VALUE (p);
3451           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3452             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3453           else
3454             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3455         }
3456
3457       ++idx;
3458     }
3459   else
3460     idx = 0;
3461
3462   if (is_non_type)
3463     {
3464       parm = TREE_VALUE (parm);
3465
3466       SET_DECL_TEMPLATE_PARM_P (parm);
3467
3468       if (TREE_TYPE (parm) == error_mark_node)
3469         {
3470           err_parm_list = build_tree_list (defval, parm);
3471           TREE_VALUE (err_parm_list) = error_mark_node;
3472            return chainon (list, err_parm_list);
3473         }
3474       else
3475       {
3476         /* [temp.param]
3477
3478            The top-level cv-qualifiers on the template-parameter are
3479            ignored when determining its type.  */
3480         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3481         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3482           {
3483             err_parm_list = build_tree_list (defval, parm);
3484             TREE_VALUE (err_parm_list) = error_mark_node;
3485              return chainon (list, err_parm_list);
3486           }
3487
3488         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3489           {
3490             /* This template parameter is not a parameter pack, but it
3491                should be. Complain about "bare" parameter packs.  */
3492             check_for_bare_parameter_packs (TREE_TYPE (parm));
3493             
3494             /* Recover by calling this a parameter pack.  */
3495             is_parameter_pack = true;
3496           }
3497       }
3498
3499       /* A template parameter is not modifiable.  */
3500       TREE_CONSTANT (parm) = 1;
3501       TREE_READONLY (parm) = 1;
3502       decl = build_decl (parm_loc,
3503                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3504       TREE_CONSTANT (decl) = 1;
3505       TREE_READONLY (decl) = 1;
3506       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3507         = build_template_parm_index (idx, processing_template_decl,
3508                                      processing_template_decl,
3509                                      decl, TREE_TYPE (parm));
3510
3511       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3512         = is_parameter_pack;
3513     }
3514   else
3515     {
3516       tree t;
3517       parm = TREE_VALUE (TREE_VALUE (parm));
3518
3519       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3520         {
3521           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3522           /* This is for distinguishing between real templates and template
3523              template parameters */
3524           TREE_TYPE (parm) = t;
3525           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3526           decl = parm;
3527         }
3528       else
3529         {
3530           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3531           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3532           decl = build_decl (parm_loc,
3533                              TYPE_DECL, parm, t);
3534         }
3535
3536       TYPE_NAME (t) = decl;
3537       TYPE_STUB_DECL (t) = decl;
3538       parm = decl;
3539       TEMPLATE_TYPE_PARM_INDEX (t)
3540         = build_template_parm_index (idx, processing_template_decl,
3541                                      processing_template_decl,
3542                                      decl, TREE_TYPE (parm));
3543       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3544       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3545     }
3546   DECL_ARTIFICIAL (decl) = 1;
3547   SET_DECL_TEMPLATE_PARM_P (decl);
3548   pushdecl (decl);
3549   parm = build_tree_list (defval, parm);
3550   return chainon (list, parm);
3551 }
3552
3553 /* The end of a template parameter list has been reached.  Process the
3554    tree list into a parameter vector, converting each parameter into a more
3555    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3556    as PARM_DECLs.  */
3557
3558 tree
3559 end_template_parm_list (tree parms)
3560 {
3561   int nparms;
3562   tree parm, next;
3563   tree saved_parmlist = make_tree_vec (list_length (parms));
3564
3565   current_template_parms
3566     = tree_cons (size_int (processing_template_decl),
3567                  saved_parmlist, current_template_parms);
3568
3569   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3570     {
3571       next = TREE_CHAIN (parm);
3572       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3573       TREE_CHAIN (parm) = NULL_TREE;
3574       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3575         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3576               current_template_parms;
3577     }
3578
3579   --processing_template_parmlist;
3580
3581   return saved_parmlist;
3582 }
3583
3584 /* end_template_decl is called after a template declaration is seen.  */
3585
3586 void
3587 end_template_decl (void)
3588 {
3589   reset_specialization ();
3590
3591   if (! processing_template_decl)
3592     return;
3593
3594   /* This matches the pushlevel in begin_template_parm_list.  */
3595   finish_scope ();
3596
3597   --processing_template_decl;
3598   current_template_parms = TREE_CHAIN (current_template_parms);
3599 }
3600
3601 /* Within the declaration of a template, return all levels of template
3602    parameters that apply.  The template parameters are represented as
3603    a TREE_VEC, in the form documented in cp-tree.h for template
3604    arguments.  */
3605
3606 static tree
3607 current_template_args (void)
3608 {
3609   tree header;
3610   tree args = NULL_TREE;
3611   int length = TMPL_PARMS_DEPTH (current_template_parms);
3612   int l = length;
3613
3614   /* If there is only one level of template parameters, we do not
3615      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3616      TREE_VEC containing the arguments.  */
3617   if (length > 1)
3618     args = make_tree_vec (length);
3619
3620   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3621     {
3622       tree a = copy_node (TREE_VALUE (header));
3623       int i;
3624
3625       TREE_TYPE (a) = NULL_TREE;
3626       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3627         {
3628           tree t = TREE_VEC_ELT (a, i);
3629
3630           /* T will be a list if we are called from within a
3631              begin/end_template_parm_list pair, but a vector directly
3632              if within a begin/end_member_template_processing pair.  */
3633           if (TREE_CODE (t) == TREE_LIST)
3634             {
3635               t = TREE_VALUE (t);
3636
3637               if (!error_operand_p (t))
3638                 {
3639                   if (TREE_CODE (t) == TYPE_DECL
3640                       || TREE_CODE (t) == TEMPLATE_DECL)
3641                     {
3642                       t = TREE_TYPE (t);
3643                       
3644                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3645                         {
3646                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3647                              with a single element, which expands T.  */
3648                           tree vec = make_tree_vec (1);
3649 #ifdef ENABLE_CHECKING
3650                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3651                                 (vec, TREE_VEC_LENGTH (vec));
3652 #endif
3653                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3654                           
3655                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3656                           SET_ARGUMENT_PACK_ARGS (t, vec);
3657                         }
3658                     }
3659                   else
3660                     {
3661                       t = DECL_INITIAL (t);
3662                       
3663                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3664                         {
3665                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3666                              with a single element, which expands T.  */
3667                           tree vec = make_tree_vec (1);
3668                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3669 #ifdef ENABLE_CHECKING
3670                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3671                                 (vec, TREE_VEC_LENGTH (vec));
3672 #endif
3673                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3674                           
3675                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3676                           SET_ARGUMENT_PACK_ARGS (t, vec);
3677                           TREE_TYPE (t) = type;
3678                         }
3679                     }
3680                   TREE_VEC_ELT (a, i) = t;
3681                 }
3682             }
3683         }
3684
3685 #ifdef ENABLE_CHECKING
3686       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3687 #endif
3688
3689       if (length > 1)
3690         TREE_VEC_ELT (args, --l) = a;
3691       else
3692         args = a;
3693     }
3694
3695   return args;
3696 }
3697
3698 /* Update the declared TYPE by doing any lookups which were thought to be
3699    dependent, but are not now that we know the SCOPE of the declarator.  */
3700
3701 tree
3702 maybe_update_decl_type (tree orig_type, tree scope)
3703 {
3704   tree type = orig_type;
3705
3706   if (type == NULL_TREE)
3707     return type;
3708
3709   if (TREE_CODE (orig_type) == TYPE_DECL)
3710     type = TREE_TYPE (type);
3711
3712   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3713       && dependent_type_p (type)
3714       /* Don't bother building up the args in this case.  */
3715       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3716     {
3717       /* tsubst in the args corresponding to the template parameters,
3718          including auto if present.  Most things will be unchanged, but
3719          make_typename_type and tsubst_qualified_id will resolve
3720          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3721       tree args = current_template_args ();
3722       tree auto_node = type_uses_auto (type);
3723       if (auto_node)
3724         {
3725           tree auto_vec = make_tree_vec (1);
3726           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3727           args = add_to_template_args (args, auto_vec);
3728         }
3729       push_scope (scope);
3730       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3731       pop_scope (scope);
3732     }
3733
3734   if (type == error_mark_node)
3735     return orig_type;
3736
3737   if (TREE_CODE (orig_type) == TYPE_DECL)
3738     {
3739       if (same_type_p (type, TREE_TYPE (orig_type)))
3740         type = orig_type;
3741       else
3742         type = TYPE_NAME (type);
3743     }
3744   return type;
3745 }
3746
3747 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3748    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3749    a member template.  Used by push_template_decl below.  */
3750
3751 static tree
3752 build_template_decl (tree decl, tree parms, bool member_template_p)
3753 {
3754   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3755   DECL_TEMPLATE_PARMS (tmpl) = parms;
3756   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3757   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3758
3759   return tmpl;
3760 }
3761
3762 struct template_parm_data
3763 {
3764   /* The level of the template parameters we are currently
3765      processing.  */
3766   int level;
3767
3768   /* The index of the specialization argument we are currently
3769      processing.  */
3770   int current_arg;
3771
3772   /* An array whose size is the number of template parameters.  The
3773      elements are nonzero if the parameter has been used in any one
3774      of the arguments processed so far.  */
3775   int* parms;
3776
3777   /* An array whose size is the number of template arguments.  The
3778      elements are nonzero if the argument makes use of template
3779      parameters of this level.  */
3780   int* arg_uses_template_parms;
3781 };
3782
3783 /* Subroutine of push_template_decl used to see if each template
3784    parameter in a partial specialization is used in the explicit
3785    argument list.  If T is of the LEVEL given in DATA (which is
3786    treated as a template_parm_data*), then DATA->PARMS is marked
3787    appropriately.  */
3788
3789 static int
3790 mark_template_parm (tree t, void* data)
3791 {
3792   int level;
3793   int idx;
3794   struct template_parm_data* tpd = (struct template_parm_data*) data;
3795
3796   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3797     {
3798       level = TEMPLATE_PARM_LEVEL (t);
3799       idx = TEMPLATE_PARM_IDX (t);
3800     }
3801   else
3802     {
3803       level = TEMPLATE_TYPE_LEVEL (t);
3804       idx = TEMPLATE_TYPE_IDX (t);
3805     }
3806
3807   if (level == tpd->level)
3808     {
3809       tpd->parms[idx] = 1;
3810       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3811     }
3812
3813   /* Return zero so that for_each_template_parm will continue the
3814      traversal of the tree; we want to mark *every* template parm.  */
3815   return 0;
3816 }
3817
3818 /* Process the partial specialization DECL.  */
3819
3820 static tree
3821 process_partial_specialization (tree decl)
3822 {
3823   tree type = TREE_TYPE (decl);
3824   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3825   tree specargs = CLASSTYPE_TI_ARGS (type);
3826   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3827   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3828   tree inner_parms;
3829   int nargs = TREE_VEC_LENGTH (inner_args);
3830   int ntparms;
3831   int  i;
3832   int did_error_intro = 0;
3833   struct template_parm_data tpd;
3834   struct template_parm_data tpd2;
3835
3836   gcc_assert (current_template_parms);
3837
3838   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3839   ntparms = TREE_VEC_LENGTH (inner_parms);
3840
3841   /* We check that each of the template parameters given in the
3842      partial specialization is used in the argument list to the
3843      specialization.  For example:
3844
3845        template <class T> struct S;
3846        template <class T> struct S<T*>;
3847
3848      The second declaration is OK because `T*' uses the template
3849      parameter T, whereas
3850
3851        template <class T> struct S<int>;
3852
3853      is no good.  Even trickier is:
3854
3855        template <class T>
3856        struct S1
3857        {
3858           template <class U>
3859           struct S2;
3860           template <class U>
3861           struct S2<T>;
3862        };
3863
3864      The S2<T> declaration is actually invalid; it is a
3865      full-specialization.  Of course,
3866
3867           template <class U>
3868           struct S2<T (*)(U)>;
3869
3870      or some such would have been OK.  */
3871   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3872   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3873   memset (tpd.parms, 0, sizeof (int) * ntparms);
3874
3875   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3876   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3877   for (i = 0; i < nargs; ++i)
3878     {
3879       tpd.current_arg = i;
3880       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3881                               &mark_template_parm,
3882                               &tpd,
3883                               NULL,
3884                               /*include_nondeduced_p=*/false);
3885     }
3886   for (i = 0; i < ntparms; ++i)
3887     if (tpd.parms[i] == 0)
3888       {
3889         /* One of the template parms was not used in the
3890            specialization.  */
3891         if (!did_error_intro)
3892           {
3893             error ("template parameters not used in partial specialization:");
3894             did_error_intro = 1;
3895           }
3896
3897         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3898       }
3899
3900   /* [temp.class.spec]
3901
3902      The argument list of the specialization shall not be identical to
3903      the implicit argument list of the primary template.  */
3904   if (comp_template_args
3905       (inner_args,
3906        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3907                                                    (maintmpl)))))
3908     error ("partial specialization %qT does not specialize any template arguments", type);
3909
3910   /* [temp.class.spec]
3911
3912      A partially specialized non-type argument expression shall not
3913      involve template parameters of the partial specialization except
3914      when the argument expression is a simple identifier.
3915
3916      The type of a template parameter corresponding to a specialized
3917      non-type argument shall not be dependent on a parameter of the
3918      specialization. 
3919
3920      Also, we verify that pack expansions only occur at the
3921      end of the argument list.  */
3922   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3923   tpd2.parms = 0;
3924   for (i = 0; i < nargs; ++i)
3925     {
3926       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3927       tree arg = TREE_VEC_ELT (inner_args, i);
3928       tree packed_args = NULL_TREE;
3929       int j, len = 1;
3930
3931       if (ARGUMENT_PACK_P (arg))
3932         {
3933           /* Extract the arguments from the argument pack. We'll be
3934              iterating over these in the following loop.  */
3935           packed_args = ARGUMENT_PACK_ARGS (arg);
3936           len = TREE_VEC_LENGTH (packed_args);
3937         }
3938
3939       for (j = 0; j < len; j++)
3940         {
3941           if (packed_args)
3942             /* Get the Jth argument in the parameter pack.  */
3943             arg = TREE_VEC_ELT (packed_args, j);
3944
3945           if (PACK_EXPANSION_P (arg))
3946             {
3947               /* Pack expansions must come at the end of the
3948                  argument list.  */
3949               if ((packed_args && j < len - 1)
3950                   || (!packed_args && i < nargs - 1))
3951                 {
3952                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3953                     error ("parameter pack argument %qE must be at the "
3954                            "end of the template argument list", arg);
3955                   else
3956                     error ("parameter pack argument %qT must be at the "
3957                            "end of the template argument list", arg);
3958                 }
3959             }
3960
3961           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3962             /* We only care about the pattern.  */
3963             arg = PACK_EXPANSION_PATTERN (arg);
3964
3965           if (/* These first two lines are the `non-type' bit.  */
3966               !TYPE_P (arg)
3967               && TREE_CODE (arg) != TEMPLATE_DECL
3968               /* This next line is the `argument expression is not just a
3969                  simple identifier' condition and also the `specialized
3970                  non-type argument' bit.  */
3971               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3972             {
3973               if ((!packed_args && tpd.arg_uses_template_parms[i])
3974                   || (packed_args && uses_template_parms (arg)))
3975                 error ("template argument %qE involves template parameter(s)",
3976                        arg);
3977               else 
3978                 {
3979                   /* Look at the corresponding template parameter,
3980                      marking which template parameters its type depends
3981                      upon.  */
3982                   tree type = TREE_TYPE (parm);
3983
3984                   if (!tpd2.parms)
3985                     {
3986                       /* We haven't yet initialized TPD2.  Do so now.  */
3987                       tpd2.arg_uses_template_parms 
3988                         = (int *) alloca (sizeof (int) * nargs);
3989                       /* The number of parameters here is the number in the
3990                          main template, which, as checked in the assertion
3991                          above, is NARGS.  */
3992                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3993                       tpd2.level = 
3994                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3995                     }
3996
3997                   /* Mark the template parameters.  But this time, we're
3998                      looking for the template parameters of the main
3999                      template, not in the specialization.  */
4000                   tpd2.current_arg = i;
4001                   tpd2.arg_uses_template_parms[i] = 0;
4002                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4003                   for_each_template_parm (type,
4004                                           &mark_template_parm,
4005                                           &tpd2,
4006                                           NULL,
4007                                           /*include_nondeduced_p=*/false);
4008
4009                   if (tpd2.arg_uses_template_parms [i])
4010                     {
4011                       /* The type depended on some template parameters.
4012                          If they are fully specialized in the
4013                          specialization, that's OK.  */
4014                       int j;
4015                       int count = 0;
4016                       for (j = 0; j < nargs; ++j)
4017                         if (tpd2.parms[j] != 0
4018                             && tpd.arg_uses_template_parms [j])
4019                           ++count;
4020                       if (count != 0)
4021                         error_n (input_location, count,
4022                                  "type %qT of template argument %qE depends "
4023                                  "on a template parameter",
4024                                  "type %qT of template argument %qE depends "
4025                                  "on template parameters",
4026                                  type,
4027                                  arg);
4028                     }
4029                 }
4030             }
4031         }
4032     }
4033
4034   /* We should only get here once.  */
4035   gcc_assert (!COMPLETE_TYPE_P (type));
4036
4037   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4038     = tree_cons (specargs, inner_parms,
4039                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4040   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4041   return decl;
4042 }
4043
4044 /* Check that a template declaration's use of default arguments and
4045    parameter packs is not invalid.  Here, PARMS are the template
4046    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4047    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4048    specialization.
4049    
4050
4051    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4052    declaration (but not a definition); 1 indicates a declaration, 2
4053    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4054    emitted for extraneous default arguments.
4055
4056    Returns TRUE if there were no errors found, FALSE otherwise. */
4057
4058 bool
4059 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4060                          int is_partial, int is_friend_decl)
4061 {
4062   const char *msg;
4063   int last_level_to_check;
4064   tree parm_level;
4065   bool no_errors = true;
4066
4067   /* [temp.param]
4068
4069      A default template-argument shall not be specified in a
4070      function template declaration or a function template definition, nor
4071      in the template-parameter-list of the definition of a member of a
4072      class template.  */
4073
4074   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4075     /* You can't have a function template declaration in a local
4076        scope, nor you can you define a member of a class template in a
4077        local scope.  */
4078     return true;
4079
4080   if (current_class_type
4081       && !TYPE_BEING_DEFINED (current_class_type)
4082       && DECL_LANG_SPECIFIC (decl)
4083       && DECL_DECLARES_FUNCTION_P (decl)
4084       /* If this is either a friend defined in the scope of the class
4085          or a member function.  */
4086       && (DECL_FUNCTION_MEMBER_P (decl)
4087           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4088           : DECL_FRIEND_CONTEXT (decl)
4089           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4090           : false)
4091       /* And, if it was a member function, it really was defined in
4092          the scope of the class.  */
4093       && (!DECL_FUNCTION_MEMBER_P (decl)
4094           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4095     /* We already checked these parameters when the template was
4096        declared, so there's no need to do it again now.  This function
4097        was defined in class scope, but we're processing it's body now
4098        that the class is complete.  */
4099     return true;
4100
4101   /* Core issue 226 (C++0x only): the following only applies to class
4102      templates.  */
4103   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4104     {
4105       /* [temp.param]
4106
4107          If a template-parameter has a default template-argument, all
4108          subsequent template-parameters shall have a default
4109          template-argument supplied.  */
4110       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4111         {
4112           tree inner_parms = TREE_VALUE (parm_level);
4113           int ntparms = TREE_VEC_LENGTH (inner_parms);
4114           int seen_def_arg_p = 0;
4115           int i;
4116
4117           for (i = 0; i < ntparms; ++i)
4118             {
4119               tree parm = TREE_VEC_ELT (inner_parms, i);
4120
4121               if (parm == error_mark_node)
4122                 continue;
4123
4124               if (TREE_PURPOSE (parm))
4125                 seen_def_arg_p = 1;
4126               else if (seen_def_arg_p
4127                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4128                 {
4129                   error ("no default argument for %qD", TREE_VALUE (parm));
4130                   /* For better subsequent error-recovery, we indicate that
4131                      there should have been a default argument.  */
4132                   TREE_PURPOSE (parm) = error_mark_node;
4133                   no_errors = false;
4134                 }
4135               else if (is_primary
4136                        && !is_partial
4137                        && !is_friend_decl
4138                        /* Don't complain about an enclosing partial
4139                           specialization.  */
4140                        && parm_level == parms
4141                        && TREE_CODE (decl) == TYPE_DECL
4142                        && i < ntparms - 1
4143                        && template_parameter_pack_p (TREE_VALUE (parm)))
4144                 {
4145                   /* A primary class template can only have one
4146                      parameter pack, at the end of the template
4147                      parameter list.  */
4148
4149                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4150                     error ("parameter pack %qE must be at the end of the"
4151                            " template parameter list", TREE_VALUE (parm));
4152                   else
4153                     error ("parameter pack %qT must be at the end of the"
4154                            " template parameter list", 
4155                            TREE_TYPE (TREE_VALUE (parm)));
4156
4157                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4158                     = error_mark_node;
4159                   no_errors = false;
4160                 }
4161             }
4162         }
4163     }
4164
4165   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4166       || is_partial 
4167       || !is_primary
4168       || is_friend_decl)
4169     /* For an ordinary class template, default template arguments are
4170        allowed at the innermost level, e.g.:
4171          template <class T = int>
4172          struct S {};
4173        but, in a partial specialization, they're not allowed even
4174        there, as we have in [temp.class.spec]:
4175
4176          The template parameter list of a specialization shall not
4177          contain default template argument values.
4178
4179        So, for a partial specialization, or for a function template
4180        (in C++98/C++03), we look at all of them.  */
4181     ;
4182   else
4183     /* But, for a primary class template that is not a partial
4184        specialization we look at all template parameters except the
4185        innermost ones.  */
4186     parms = TREE_CHAIN (parms);
4187
4188   /* Figure out what error message to issue.  */
4189   if (is_friend_decl == 2)
4190     msg = G_("default template arguments may not be used in function template "
4191              "friend re-declaration");
4192   else if (is_friend_decl)
4193     msg = G_("default template arguments may not be used in function template "
4194              "friend declarations");
4195   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4196     msg = G_("default template arguments may not be used in function templates "
4197              "without -std=c++0x or -std=gnu++0x");
4198   else if (is_partial)
4199     msg = G_("default template arguments may not be used in "
4200              "partial specializations");
4201   else
4202     msg = G_("default argument for template parameter for class enclosing %qD");
4203
4204   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4205     /* If we're inside a class definition, there's no need to
4206        examine the parameters to the class itself.  On the one
4207        hand, they will be checked when the class is defined, and,
4208        on the other, default arguments are valid in things like:
4209          template <class T = double>
4210          struct S { template <class U> void f(U); };
4211        Here the default argument for `S' has no bearing on the
4212        declaration of `f'.  */
4213     last_level_to_check = template_class_depth (current_class_type) + 1;
4214   else
4215     /* Check everything.  */
4216     last_level_to_check = 0;
4217
4218   for (parm_level = parms;
4219        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4220        parm_level = TREE_CHAIN (parm_level))
4221     {
4222       tree inner_parms = TREE_VALUE (parm_level);
4223       int i;
4224       int ntparms;
4225
4226       ntparms = TREE_VEC_LENGTH (inner_parms);
4227       for (i = 0; i < ntparms; ++i)
4228         {
4229           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4230             continue;
4231
4232           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4233             {
4234               if (msg)
4235                 {
4236                   no_errors = false;
4237                   if (is_friend_decl == 2)
4238                     return no_errors;
4239
4240                   error (msg, decl);
4241                   msg = 0;
4242                 }
4243
4244               /* Clear out the default argument so that we are not
4245                  confused later.  */
4246               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4247             }
4248         }
4249
4250       /* At this point, if we're still interested in issuing messages,
4251          they must apply to classes surrounding the object declared.  */
4252       if (msg)
4253         msg = G_("default argument for template parameter for class "
4254                  "enclosing %qD");
4255     }
4256
4257   return no_errors;
4258 }
4259
4260 /* Worker for push_template_decl_real, called via
4261    for_each_template_parm.  DATA is really an int, indicating the
4262    level of the parameters we are interested in.  If T is a template
4263    parameter of that level, return nonzero.  */
4264
4265 static int
4266 template_parm_this_level_p (tree t, void* data)
4267 {
4268   int this_level = *(int *)data;
4269   int level;
4270
4271   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4272     level = TEMPLATE_PARM_LEVEL (t);
4273   else
4274     level = TEMPLATE_TYPE_LEVEL (t);
4275   return level == this_level;
4276 }
4277
4278 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4279    parameters given by current_template_args, or reuses a
4280    previously existing one, if appropriate.  Returns the DECL, or an
4281    equivalent one, if it is replaced via a call to duplicate_decls.
4282
4283    If IS_FRIEND is true, DECL is a friend declaration.  */
4284
4285 tree
4286 push_template_decl_real (tree decl, bool is_friend)
4287 {
4288   tree tmpl;
4289   tree args;
4290   tree info;
4291   tree ctx;
4292   int primary;
4293   int is_partial;
4294   int new_template_p = 0;
4295   /* True if the template is a member template, in the sense of
4296      [temp.mem].  */
4297   bool member_template_p = false;
4298
4299   if (decl == error_mark_node || !current_template_parms)
4300     return error_mark_node;
4301
4302   /* See if this is a partial specialization.  */
4303   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4304                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4305                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4306
4307   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4308     is_friend = true;
4309
4310   if (is_friend)
4311     /* For a friend, we want the context of the friend function, not
4312        the type of which it is a friend.  */
4313     ctx = DECL_CONTEXT (decl);
4314   else if (CP_DECL_CONTEXT (decl)
4315            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4316     /* In the case of a virtual function, we want the class in which
4317        it is defined.  */
4318     ctx = CP_DECL_CONTEXT (decl);
4319   else
4320     /* Otherwise, if we're currently defining some class, the DECL
4321        is assumed to be a member of the class.  */
4322     ctx = current_scope ();
4323
4324   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4325     ctx = NULL_TREE;
4326
4327   if (!DECL_CONTEXT (decl))
4328     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4329
4330   /* See if this is a primary template.  */
4331   if (is_friend && ctx)
4332     /* A friend template that specifies a class context, i.e.
4333          template <typename T> friend void A<T>::f();
4334        is not primary.  */
4335     primary = 0;
4336   else
4337     primary = template_parm_scope_p ();
4338
4339   if (primary)
4340     {
4341       if (DECL_CLASS_SCOPE_P (decl))
4342         member_template_p = true;
4343       if (TREE_CODE (decl) == TYPE_DECL
4344           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4345         {
4346           error ("template class without a name");
4347           return error_mark_node;
4348         }
4349       else if (TREE_CODE (decl) == FUNCTION_DECL)
4350         {
4351           if (DECL_DESTRUCTOR_P (decl))
4352             {
4353               /* [temp.mem]
4354
4355                  A destructor shall not be a member template.  */
4356               error ("destructor %qD declared as member template", decl);
4357               return error_mark_node;
4358             }
4359           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4360               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4361                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4362                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4363                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4364                       == void_list_node)))
4365             {
4366               /* [basic.stc.dynamic.allocation]
4367
4368                  An allocation function can be a function
4369                  template. ... Template allocation functions shall
4370                  have two or more parameters.  */
4371               error ("invalid template declaration of %qD", decl);
4372               return error_mark_node;
4373             }
4374         }
4375       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4376                && CLASS_TYPE_P (TREE_TYPE (decl)))
4377         /* OK */;
4378       else
4379         {
4380           error ("template declaration of %q#D", decl);
4381           return error_mark_node;
4382         }
4383     }
4384
4385   /* Check to see that the rules regarding the use of default
4386      arguments are not being violated.  */
4387   check_default_tmpl_args (decl, current_template_parms,
4388                            primary, is_partial, /*is_friend_decl=*/0);
4389
4390   /* Ensure that there are no parameter packs in the type of this
4391      declaration that have not been expanded.  */
4392   if (TREE_CODE (decl) == FUNCTION_DECL)
4393     {
4394       /* Check each of the arguments individually to see if there are
4395          any bare parameter packs.  */
4396       tree type = TREE_TYPE (decl);
4397       tree arg = DECL_ARGUMENTS (decl);
4398       tree argtype = TYPE_ARG_TYPES (type);
4399
4400       while (arg && argtype)
4401         {
4402           if (!FUNCTION_PARAMETER_PACK_P (arg)
4403               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4404             {
4405             /* This is a PARM_DECL that contains unexpanded parameter
4406                packs. We have already complained about this in the
4407                check_for_bare_parameter_packs call, so just replace
4408                these types with ERROR_MARK_NODE.  */
4409               TREE_TYPE (arg) = error_mark_node;
4410               TREE_VALUE (argtype) = error_mark_node;
4411             }
4412
4413           arg = TREE_CHAIN (arg);
4414           argtype = TREE_CHAIN (argtype);
4415         }
4416
4417       /* Check for bare parameter packs in the return type and the
4418          exception specifiers.  */
4419       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4420         /* Errors were already issued, set return type to int
4421            as the frontend doesn't expect error_mark_node as
4422            the return type.  */
4423         TREE_TYPE (type) = integer_type_node;
4424       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4425         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4426     }
4427   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4428     {
4429       TREE_TYPE (decl) = error_mark_node;
4430       return error_mark_node;
4431     }
4432
4433   if (is_partial)
4434     return process_partial_specialization (decl);
4435
4436   args = current_template_args ();
4437
4438   if (!ctx
4439       || TREE_CODE (ctx) == FUNCTION_DECL
4440       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4441       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4442     {
4443       if (DECL_LANG_SPECIFIC (decl)
4444           && DECL_TEMPLATE_INFO (decl)
4445           && DECL_TI_TEMPLATE (decl))
4446         tmpl = DECL_TI_TEMPLATE (decl);
4447       /* If DECL is a TYPE_DECL for a class-template, then there won't
4448          be DECL_LANG_SPECIFIC.  The information equivalent to
4449          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4450       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4451                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4452                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4453         {
4454           /* Since a template declaration already existed for this
4455              class-type, we must be redeclaring it here.  Make sure
4456              that the redeclaration is valid.  */
4457           redeclare_class_template (TREE_TYPE (decl),
4458                                     current_template_parms);
4459           /* We don't need to create a new TEMPLATE_DECL; just use the
4460              one we already had.  */
4461           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4462         }
4463       else
4464         {
4465           tmpl = build_template_decl (decl, current_template_parms,
4466                                       member_template_p);
4467           new_template_p = 1;
4468
4469           if (DECL_LANG_SPECIFIC (decl)
4470               && DECL_TEMPLATE_SPECIALIZATION (decl))
4471             {
4472               /* A specialization of a member template of a template
4473                  class.  */
4474               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4475               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4476               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4477             }
4478         }
4479     }
4480   else
4481     {
4482       tree a, t, current, parms;
4483       int i;
4484       tree tinfo = get_template_info (decl);
4485
4486       if (!tinfo)
4487         {
4488           error ("template definition of non-template %q#D", decl);
4489           return error_mark_node;
4490         }
4491
4492       tmpl = TI_TEMPLATE (tinfo);
4493
4494       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4495           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4496           && DECL_TEMPLATE_SPECIALIZATION (decl)
4497           && DECL_MEMBER_TEMPLATE_P (tmpl))
4498         {
4499           tree new_tmpl;
4500
4501           /* The declaration is a specialization of a member
4502              template, declared outside the class.  Therefore, the
4503              innermost template arguments will be NULL, so we
4504              replace them with the arguments determined by the
4505              earlier call to check_explicit_specialization.  */
4506           args = DECL_TI_ARGS (decl);
4507
4508           new_tmpl
4509             = build_template_decl (decl, current_template_parms,
4510                                    member_template_p);
4511           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4512           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4513           DECL_TI_TEMPLATE (decl) = new_tmpl;
4514           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4515           DECL_TEMPLATE_INFO (new_tmpl)
4516             = build_template_info (tmpl, args);
4517
4518           register_specialization (new_tmpl,
4519                                    most_general_template (tmpl),
4520                                    args,
4521                                    is_friend, 0);
4522           return decl;
4523         }
4524
4525       /* Make sure the template headers we got make sense.  */
4526
4527       parms = DECL_TEMPLATE_PARMS (tmpl);
4528       i = TMPL_PARMS_DEPTH (parms);
4529       if (TMPL_ARGS_DEPTH (args) != i)
4530         {
4531           error ("expected %d levels of template parms for %q#D, got %d",
4532                  i, decl, TMPL_ARGS_DEPTH (args));
4533         }
4534       else
4535         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4536           {
4537             a = TMPL_ARGS_LEVEL (args, i);
4538             t = INNERMOST_TEMPLATE_PARMS (parms);
4539
4540             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4541               {
4542                 if (current == decl)
4543                   error ("got %d template parameters for %q#D",
4544                          TREE_VEC_LENGTH (a), decl);
4545                 else
4546                   error ("got %d template parameters for %q#T",
4547                          TREE_VEC_LENGTH (a), current);
4548                 error ("  but %d required", TREE_VEC_LENGTH (t));
4549                 return error_mark_node;
4550               }
4551
4552             if (current == decl)
4553               current = ctx;
4554             else if (current == NULL_TREE)
4555               /* Can happen in erroneous input.  */
4556               break;
4557             else
4558               current = (TYPE_P (current)
4559                          ? TYPE_CONTEXT (current)
4560                          : DECL_CONTEXT (current));
4561           }
4562
4563       /* Check that the parms are used in the appropriate qualifying scopes
4564          in the declarator.  */
4565       if (!comp_template_args
4566           (TI_ARGS (tinfo),
4567            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4568         {
4569           error ("\
4570 template arguments to %qD do not match original template %qD",
4571                  decl, DECL_TEMPLATE_RESULT (tmpl));
4572           if (!uses_template_parms (TI_ARGS (tinfo)))
4573             inform (input_location, "use template<> for an explicit specialization");
4574           /* Avoid crash in import_export_decl.  */
4575           DECL_INTERFACE_KNOWN (decl) = 1;
4576           return error_mark_node;
4577         }
4578     }
4579
4580   DECL_TEMPLATE_RESULT (tmpl) = decl;
4581   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4582
4583   /* Push template declarations for global functions and types.  Note
4584      that we do not try to push a global template friend declared in a
4585      template class; such a thing may well depend on the template
4586      parameters of the class.  */
4587   if (new_template_p && !ctx
4588       && !(is_friend && template_class_depth (current_class_type) > 0))
4589     {
4590       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4591       if (tmpl == error_mark_node)
4592         return error_mark_node;
4593
4594       /* Hide template friend classes that haven't been declared yet.  */
4595       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4596         {
4597           DECL_ANTICIPATED (tmpl) = 1;
4598           DECL_FRIEND_P (tmpl) = 1;
4599         }
4600     }
4601
4602   if (primary)
4603     {
4604       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4605       int i;
4606
4607       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4608       if (DECL_CONV_FN_P (tmpl))
4609         {
4610           int depth = TMPL_PARMS_DEPTH (parms);
4611
4612           /* It is a conversion operator. See if the type converted to
4613              depends on innermost template operands.  */
4614
4615           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4616                                          depth))
4617             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4618         }
4619
4620       /* Give template template parms a DECL_CONTEXT of the template
4621          for which they are a parameter.  */
4622       parms = INNERMOST_TEMPLATE_PARMS (parms);
4623       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4624         {
4625           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4626           if (TREE_CODE (parm) == TEMPLATE_DECL)
4627             DECL_CONTEXT (parm) = tmpl;
4628         }
4629     }
4630
4631   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4632      back to its most general template.  If TMPL is a specialization,
4633      ARGS may only have the innermost set of arguments.  Add the missing
4634      argument levels if necessary.  */
4635   if (DECL_TEMPLATE_INFO (tmpl))
4636     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4637
4638   info = build_template_info (tmpl, args);
4639
4640   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4641     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4642   else if (DECL_LANG_SPECIFIC (decl))
4643     DECL_TEMPLATE_INFO (decl) = info;
4644
4645   return DECL_TEMPLATE_RESULT (tmpl);
4646 }
4647
4648 tree
4649 push_template_decl (tree decl)
4650 {
4651   return push_template_decl_real (decl, false);
4652 }
4653
4654 /* Called when a class template TYPE is redeclared with the indicated
4655    template PARMS, e.g.:
4656
4657      template <class T> struct S;
4658      template <class T> struct S {};  */
4659
4660 bool
4661 redeclare_class_template (tree type, tree parms)
4662 {
4663   tree tmpl;
4664   tree tmpl_parms;
4665   int i;
4666
4667   if (!TYPE_TEMPLATE_INFO (type))
4668     {
4669       error ("%qT is not a template type", type);
4670       return false;
4671     }
4672
4673   tmpl = TYPE_TI_TEMPLATE (type);
4674   if (!PRIMARY_TEMPLATE_P (tmpl))
4675     /* The type is nested in some template class.  Nothing to worry
4676        about here; there are no new template parameters for the nested
4677        type.  */
4678     return true;
4679
4680   if (!parms)
4681     {
4682       error ("template specifiers not specified in declaration of %qD",
4683              tmpl);
4684       return false;
4685     }
4686
4687   parms = INNERMOST_TEMPLATE_PARMS (parms);
4688   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4689
4690   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4691     {
4692       error_n (input_location, TREE_VEC_LENGTH (parms),
4693                "redeclared with %d template parameter",
4694                "redeclared with %d template parameters",
4695                TREE_VEC_LENGTH (parms));
4696       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4697                 "previous declaration %q+D used %d template parameter",
4698                 "previous declaration %q+D used %d template parameters",
4699                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4700       return false;
4701     }
4702
4703   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4704     {
4705       tree tmpl_parm;
4706       tree parm;
4707       tree tmpl_default;
4708       tree parm_default;
4709
4710       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4711           || TREE_VEC_ELT (parms, i) == error_mark_node)
4712         continue;
4713
4714       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4715       if (tmpl_parm == error_mark_node)
4716         return false;
4717
4718       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4719       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4720       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4721
4722       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4723          TEMPLATE_DECL.  */
4724       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4725           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4726               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4727           || (TREE_CODE (tmpl_parm) != PARM_DECL
4728               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4729                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4730           || (TREE_CODE (tmpl_parm) == PARM_DECL
4731               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4732                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4733         {
4734           error ("template parameter %q+#D", tmpl_parm);
4735           error ("redeclared here as %q#D", parm);
4736           return false;
4737         }
4738
4739       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4740         {
4741           /* We have in [temp.param]:
4742
4743              A template-parameter may not be given default arguments
4744              by two different declarations in the same scope.  */
4745           error_at (input_location, "redefinition of default argument for %q#D", parm);
4746           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4747                   "original definition appeared here");
4748           return false;
4749         }
4750
4751       if (parm_default != NULL_TREE)
4752         /* Update the previous template parameters (which are the ones
4753            that will really count) with the new default value.  */
4754         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4755       else if (tmpl_default != NULL_TREE)
4756         /* Update the new parameters, too; they'll be used as the
4757            parameters for any members.  */
4758         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4759     }
4760
4761     return true;
4762 }
4763
4764 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4765    (possibly simplified) expression.  */
4766
4767 tree
4768 fold_non_dependent_expr (tree expr)
4769 {
4770   if (expr == NULL_TREE)
4771     return NULL_TREE;
4772
4773   /* If we're in a template, but EXPR isn't value dependent, simplify
4774      it.  We're supposed to treat:
4775
4776        template <typename T> void f(T[1 + 1]);
4777        template <typename T> void f(T[2]);
4778
4779      as two declarations of the same function, for example.  */
4780   if (processing_template_decl
4781       && !type_dependent_expression_p (expr)
4782       && !value_dependent_expression_p (expr))
4783     {
4784       HOST_WIDE_INT saved_processing_template_decl;
4785
4786       saved_processing_template_decl = processing_template_decl;
4787       processing_template_decl = 0;
4788       expr = tsubst_copy_and_build (expr,
4789                                     /*args=*/NULL_TREE,
4790                                     tf_error,
4791                                     /*in_decl=*/NULL_TREE,
4792                                     /*function_p=*/false,
4793                                     /*integral_constant_expression_p=*/true);
4794       processing_template_decl = saved_processing_template_decl;
4795     }
4796   return expr;
4797 }
4798
4799 /* EXPR is an expression which is used in a constant-expression context.
4800    For instance, it could be a VAR_DECL with a constant initializer.
4801    Extract the innermost constant expression.
4802
4803    This is basically a more powerful version of
4804    integral_constant_value, which can be used also in templates where
4805    initializers can maintain a syntactic rather than semantic form
4806    (even if they are non-dependent, for access-checking purposes).  */
4807
4808 static tree
4809 fold_decl_constant_value (tree expr)
4810 {
4811   tree const_expr = expr;
4812   do
4813     {
4814       expr = fold_non_dependent_expr (const_expr);
4815       const_expr = integral_constant_value (expr);
4816     }
4817   while (expr != const_expr);
4818
4819   return expr;
4820 }
4821
4822 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4823    must be a function or a pointer-to-function type, as specified
4824    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4825    and check that the resulting function has external linkage.  */
4826
4827 static tree
4828 convert_nontype_argument_function (tree type, tree expr)
4829 {
4830   tree fns = expr;
4831   tree fn, fn_no_ptr;
4832
4833   fn = instantiate_type (type, fns, tf_none);
4834   if (fn == error_mark_node)
4835     return error_mark_node;
4836
4837   fn_no_ptr = fn;
4838   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4839     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4840   if (TREE_CODE (fn_no_ptr) == BASELINK)
4841     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4842  
4843   /* [temp.arg.nontype]/1
4844
4845      A template-argument for a non-type, non-template template-parameter
4846      shall be one of:
4847      [...]
4848      -- the address of an object or function with external linkage.  */
4849   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4850     {
4851       error ("%qE is not a valid template argument for type %qT "
4852              "because function %qD has not external linkage",
4853              expr, type, fn_no_ptr);
4854       return NULL_TREE;
4855     }
4856
4857   return fn;
4858 }
4859
4860 /* Subroutine of convert_nontype_argument.
4861    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4862    Emit an error otherwise.  */
4863
4864 static bool
4865 check_valid_ptrmem_cst_expr (tree type, tree expr)
4866 {
4867   STRIP_NOPS (expr);
4868   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4869     return true;
4870   error ("%qE is not a valid template argument for type %qT",
4871          expr, type);
4872   error ("it must be a pointer-to-member of the form `&X::Y'");
4873   return false;
4874 }
4875
4876 /* Attempt to convert the non-type template parameter EXPR to the
4877    indicated TYPE.  If the conversion is successful, return the
4878    converted value.  If the conversion is unsuccessful, return
4879    NULL_TREE if we issued an error message, or error_mark_node if we
4880    did not.  We issue error messages for out-and-out bad template
4881    parameters, but not simply because the conversion failed, since we
4882    might be just trying to do argument deduction.  Both TYPE and EXPR
4883    must be non-dependent.
4884
4885    The conversion follows the special rules described in
4886    [temp.arg.nontype], and it is much more strict than an implicit
4887    conversion.
4888
4889    This function is called twice for each template argument (see
4890    lookup_template_class for a more accurate description of this
4891    problem). This means that we need to handle expressions which
4892    are not valid in a C++ source, but can be created from the
4893    first call (for instance, casts to perform conversions). These
4894    hacks can go away after we fix the double coercion problem.  */
4895
4896 static tree
4897 convert_nontype_argument (tree type, tree expr)
4898 {
4899   tree expr_type;
4900
4901   /* Detect immediately string literals as invalid non-type argument.
4902      This special-case is not needed for correctness (we would easily
4903      catch this later), but only to provide better diagnostic for this
4904      common user mistake. As suggested by DR 100, we do not mention
4905      linkage issues in the diagnostic as this is not the point.  */
4906   if (TREE_CODE (expr) == STRING_CST)
4907     {
4908       error ("%qE is not a valid template argument for type %qT "
4909              "because string literals can never be used in this context",
4910              expr, type);
4911       return NULL_TREE;
4912     }
4913
4914   /* If we are in a template, EXPR may be non-dependent, but still
4915      have a syntactic, rather than semantic, form.  For example, EXPR
4916      might be a SCOPE_REF, rather than the VAR_DECL to which the
4917      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4918      so that access checking can be performed when the template is
4919      instantiated -- but here we need the resolved form so that we can
4920      convert the argument.  */
4921   expr = fold_non_dependent_expr (expr);
4922   if (error_operand_p (expr))
4923     return error_mark_node;
4924   expr_type = TREE_TYPE (expr);
4925
4926   /* HACK: Due to double coercion, we can get a
4927      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4928      which is the tree that we built on the first call (see
4929      below when coercing to reference to object or to reference to
4930      function). We just strip everything and get to the arg.
4931      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4932      for examples.  */
4933   if (TREE_CODE (expr) == NOP_EXPR)
4934     {
4935       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4936         {
4937           /* ??? Maybe we could use convert_from_reference here, but we
4938              would need to relax its constraints because the NOP_EXPR
4939              could actually change the type to something more cv-qualified,
4940              and this is not folded by convert_from_reference.  */
4941           tree addr = TREE_OPERAND (expr, 0);
4942           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4943           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4944           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4945           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4946                       (TREE_TYPE (expr_type),
4947                        TREE_TYPE (TREE_TYPE (addr))));
4948
4949           expr = TREE_OPERAND (addr, 0);
4950           expr_type = TREE_TYPE (expr);
4951         }
4952
4953       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4954          parameter is a pointer to object, through decay and
4955          qualification conversion. Let's strip everything.  */
4956       else if (TYPE_PTROBV_P (type))
4957         {
4958           STRIP_NOPS (expr);
4959           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4960           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4961           /* Skip the ADDR_EXPR only if it is part of the decay for
4962              an array. Otherwise, it is part of the original argument
4963              in the source code.  */
4964           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4965             expr = TREE_OPERAND (expr, 0);
4966           expr_type = TREE_TYPE (expr);
4967         }
4968     }
4969
4970   /* [temp.arg.nontype]/5, bullet 1
4971
4972      For a non-type template-parameter of integral or enumeration type,
4973      integral promotions (_conv.prom_) and integral conversions
4974      (_conv.integral_) are applied.  */
4975   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4976     {
4977       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4978         return error_mark_node;
4979
4980       expr = fold_decl_constant_value (expr);
4981       /* Notice that there are constant expressions like '4 % 0' which
4982          do not fold into integer constants.  */
4983       if (TREE_CODE (expr) != INTEGER_CST)
4984         {
4985           error ("%qE is not a valid template argument for type %qT "
4986                  "because it is a non-constant expression", expr, type);
4987           return NULL_TREE;
4988         }
4989
4990       /* At this point, an implicit conversion does what we want,
4991          because we already know that the expression is of integral
4992          type.  */
4993       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4994       if (expr == error_mark_node)
4995         return error_mark_node;
4996
4997       /* Conversion was allowed: fold it to a bare integer constant.  */
4998       expr = fold (expr);
4999     }
5000   /* [temp.arg.nontype]/5, bullet 2
5001
5002      For a non-type template-parameter of type pointer to object,
5003      qualification conversions (_conv.qual_) and the array-to-pointer
5004      conversion (_conv.array_) are applied.  */
5005   else if (TYPE_PTROBV_P (type))
5006     {
5007       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5008
5009          A template-argument for a non-type, non-template template-parameter
5010          shall be one of: [...]
5011
5012          -- the name of a non-type template-parameter;
5013          -- the address of an object or function with external linkage, [...]
5014             expressed as "& id-expression" where the & is optional if the name
5015             refers to a function or array, or if the corresponding
5016             template-parameter is a reference.
5017
5018         Here, we do not care about functions, as they are invalid anyway
5019         for a parameter of type pointer-to-object.  */
5020
5021       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5022         /* Non-type template parameters are OK.  */
5023         ;
5024       else if (TREE_CODE (expr) != ADDR_EXPR
5025                && TREE_CODE (expr_type) != ARRAY_TYPE)
5026         {
5027           if (TREE_CODE (expr) == VAR_DECL)
5028             {
5029               error ("%qD is not a valid template argument "
5030                      "because %qD is a variable, not the address of "
5031                      "a variable",
5032                      expr, expr);
5033               return NULL_TREE;
5034             }
5035           /* Other values, like integer constants, might be valid
5036              non-type arguments of some other type.  */
5037           return error_mark_node;
5038         }
5039       else
5040         {
5041           tree decl;
5042
5043           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5044                   ? TREE_OPERAND (expr, 0) : expr);
5045           if (TREE_CODE (decl) != VAR_DECL)
5046             {
5047               error ("%qE is not a valid template argument of type %qT "
5048                      "because %qE is not a variable",
5049                      expr, type, decl);
5050               return NULL_TREE;
5051             }
5052           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5053             {
5054               error ("%qE is not a valid template argument of type %qT "
5055                      "because %qD does not have external linkage",
5056                      expr, type, decl);
5057               return NULL_TREE;
5058             }
5059         }
5060
5061       expr = decay_conversion (expr);
5062       if (expr == error_mark_node)
5063         return error_mark_node;
5064
5065       expr = perform_qualification_conversions (type, expr);
5066       if (expr == error_mark_node)
5067         return error_mark_node;
5068     }
5069   /* [temp.arg.nontype]/5, bullet 3
5070
5071      For a non-type template-parameter of type reference to object, no
5072      conversions apply. The type referred to by the reference may be more
5073      cv-qualified than the (otherwise identical) type of the
5074      template-argument. The template-parameter is bound directly to the
5075      template-argument, which must be an lvalue.  */
5076   else if (TYPE_REF_OBJ_P (type))
5077     {
5078       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5079                                                       expr_type))
5080         return error_mark_node;
5081
5082       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5083         {
5084           error ("%qE is not a valid template argument for type %qT "
5085                  "because of conflicts in cv-qualification", expr, type);
5086           return NULL_TREE;
5087         }
5088
5089       if (!real_lvalue_p (expr))
5090         {
5091           error ("%qE is not a valid template argument for type %qT "
5092                  "because it is not an lvalue", expr, type);
5093           return NULL_TREE;
5094         }
5095
5096       /* [temp.arg.nontype]/1
5097
5098          A template-argument for a non-type, non-template template-parameter
5099          shall be one of: [...]
5100
5101          -- the address of an object or function with external linkage.  */
5102       if (TREE_CODE (expr) == INDIRECT_REF
5103           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5104         {
5105           expr = TREE_OPERAND (expr, 0);
5106           if (DECL_P (expr))
5107             {
5108               error ("%q#D is not a valid template argument for type %qT "
5109                      "because a reference variable does not have a constant "
5110                      "address", expr, type);
5111               return NULL_TREE;
5112             }
5113         }
5114
5115       if (!DECL_P (expr))
5116         {
5117           error ("%qE is not a valid template argument for type %qT "
5118                  "because it is not an object with external linkage",
5119                  expr, type);
5120           return NULL_TREE;
5121         }
5122
5123       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5124         {
5125           error ("%qE is not a valid template argument for type %qT "
5126                  "because object %qD has not external linkage",
5127                  expr, type, expr);
5128           return NULL_TREE;
5129         }
5130
5131       expr = build_nop (type, build_address (expr));
5132     }
5133   /* [temp.arg.nontype]/5, bullet 4
5134
5135      For a non-type template-parameter of type pointer to function, only
5136      the function-to-pointer conversion (_conv.func_) is applied. If the
5137      template-argument represents a set of overloaded functions (or a
5138      pointer to such), the matching function is selected from the set
5139      (_over.over_).  */
5140   else if (TYPE_PTRFN_P (type))
5141     {
5142       /* If the argument is a template-id, we might not have enough
5143          context information to decay the pointer.  */
5144       if (!type_unknown_p (expr_type))
5145         {
5146           expr = decay_conversion (expr);
5147           if (expr == error_mark_node)
5148             return error_mark_node;
5149         }
5150
5151       expr = convert_nontype_argument_function (type, expr);
5152       if (!expr || expr == error_mark_node)
5153         return expr;
5154
5155       if (TREE_CODE (expr) != ADDR_EXPR)
5156         {
5157           error ("%qE is not a valid template argument for type %qT", expr, type);
5158           error ("it must be the address of a function with external linkage");
5159           return NULL_TREE;
5160         }
5161     }
5162   /* [temp.arg.nontype]/5, bullet 5
5163
5164      For a non-type template-parameter of type reference to function, no
5165      conversions apply. If the template-argument represents a set of
5166      overloaded functions, the matching function is selected from the set
5167      (_over.over_).  */
5168   else if (TYPE_REFFN_P (type))
5169     {
5170       if (TREE_CODE (expr) == ADDR_EXPR)
5171         {
5172           error ("%qE is not a valid template argument for type %qT "
5173                  "because it is a pointer", expr, type);
5174           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5175           return NULL_TREE;
5176         }
5177
5178       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5179       if (!expr || expr == error_mark_node)
5180         return expr;
5181
5182       expr = build_nop (type, build_address (expr));
5183     }
5184   /* [temp.arg.nontype]/5, bullet 6
5185
5186      For a non-type template-parameter of type pointer to member function,
5187      no conversions apply. If the template-argument represents a set of
5188      overloaded member functions, the matching member function is selected
5189      from the set (_over.over_).  */
5190   else if (TYPE_PTRMEMFUNC_P (type))
5191     {
5192       expr = instantiate_type (type, expr, tf_none);
5193       if (expr == error_mark_node)
5194         return error_mark_node;
5195
5196       /* [temp.arg.nontype] bullet 1 says the pointer to member
5197          expression must be a pointer-to-member constant.  */
5198       if (!check_valid_ptrmem_cst_expr (type, expr))
5199         return error_mark_node;
5200
5201       /* There is no way to disable standard conversions in
5202          resolve_address_of_overloaded_function (called by
5203          instantiate_type). It is possible that the call succeeded by
5204          converting &B::I to &D::I (where B is a base of D), so we need
5205          to reject this conversion here.
5206
5207          Actually, even if there was a way to disable standard conversions,
5208          it would still be better to reject them here so that we can
5209          provide a superior diagnostic.  */
5210       if (!same_type_p (TREE_TYPE (expr), type))
5211         {
5212           error ("%qE is not a valid template argument for type %qT "
5213                  "because it is of type %qT", expr, type,
5214                  TREE_TYPE (expr));
5215           /* If we are just one standard conversion off, explain.  */
5216           if (can_convert (type, TREE_TYPE (expr)))
5217             inform (input_location,
5218                     "standard conversions are not allowed in this context");
5219           return NULL_TREE;
5220         }
5221     }
5222   /* [temp.arg.nontype]/5, bullet 7
5223
5224      For a non-type template-parameter of type pointer to data member,
5225      qualification conversions (_conv.qual_) are applied.  */
5226   else if (TYPE_PTRMEM_P (type))
5227     {
5228       /* [temp.arg.nontype] bullet 1 says the pointer to member
5229          expression must be a pointer-to-member constant.  */
5230       if (!check_valid_ptrmem_cst_expr (type, expr))
5231         return error_mark_node;
5232
5233       expr = perform_qualification_conversions (type, expr);
5234       if (expr == error_mark_node)
5235         return expr;
5236     }
5237   /* A template non-type parameter must be one of the above.  */
5238   else
5239     gcc_unreachable ();
5240
5241   /* Sanity check: did we actually convert the argument to the
5242      right type?  */
5243   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5244   return expr;
5245 }
5246
5247 /* Subroutine of coerce_template_template_parms, which returns 1 if
5248    PARM_PARM and ARG_PARM match using the rule for the template
5249    parameters of template template parameters. Both PARM and ARG are
5250    template parameters; the rest of the arguments are the same as for
5251    coerce_template_template_parms.
5252  */
5253 static int
5254 coerce_template_template_parm (tree parm,
5255                               tree arg,
5256                               tsubst_flags_t complain,
5257                               tree in_decl,
5258                               tree outer_args)
5259 {
5260   if (arg == NULL_TREE || arg == error_mark_node
5261       || parm == NULL_TREE || parm == error_mark_node)
5262     return 0;
5263   
5264   if (TREE_CODE (arg) != TREE_CODE (parm))
5265     return 0;
5266   
5267   switch (TREE_CODE (parm))
5268     {
5269     case TEMPLATE_DECL:
5270       /* We encounter instantiations of templates like
5271          template <template <template <class> class> class TT>
5272          class C;  */
5273       {
5274         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5275         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5276         
5277         if (!coerce_template_template_parms
5278             (parmparm, argparm, complain, in_decl, outer_args))
5279           return 0;
5280       }
5281       /* Fall through.  */
5282       
5283     case TYPE_DECL:
5284       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5285           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5286         /* Argument is a parameter pack but parameter is not.  */
5287         return 0;
5288       break;
5289       
5290     case PARM_DECL:
5291       /* The tsubst call is used to handle cases such as
5292          
5293            template <int> class C {};
5294            template <class T, template <T> class TT> class D {};
5295            D<int, C> d;
5296
5297          i.e. the parameter list of TT depends on earlier parameters.  */
5298       if (!uses_template_parms (TREE_TYPE (arg))
5299           && !same_type_p
5300                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5301                  TREE_TYPE (arg)))
5302         return 0;
5303       
5304       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5305           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5306         /* Argument is a parameter pack but parameter is not.  */
5307         return 0;
5308       
5309       break;
5310
5311     default:
5312       gcc_unreachable ();
5313     }
5314
5315   return 1;
5316 }
5317
5318
5319 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5320    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5321    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5322    or PARM_DECL.
5323
5324    Consider the example:
5325      template <class T> class A;
5326      template<template <class U> class TT> class B;
5327
5328    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5329    the parameters to A, and OUTER_ARGS contains A.  */
5330
5331 static int
5332 coerce_template_template_parms (tree parm_parms,
5333                                 tree arg_parms,
5334                                 tsubst_flags_t complain,
5335                                 tree in_decl,
5336                                 tree outer_args)
5337 {
5338   int nparms, nargs, i;
5339   tree parm, arg;
5340   int variadic_p = 0;
5341
5342   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5343   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5344
5345   nparms = TREE_VEC_LENGTH (parm_parms);
5346   nargs = TREE_VEC_LENGTH (arg_parms);
5347
5348   /* Determine whether we have a parameter pack at the end of the
5349      template template parameter's template parameter list.  */
5350   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5351     {
5352       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5353       
5354       if (parm == error_mark_node)
5355         return 0;
5356
5357       switch (TREE_CODE (parm))
5358         {
5359         case TEMPLATE_DECL:
5360         case TYPE_DECL:
5361           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5362             variadic_p = 1;
5363           break;
5364           
5365         case PARM_DECL:
5366           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5367             variadic_p = 1;
5368           break;
5369           
5370         default:
5371           gcc_unreachable ();
5372         }
5373     }
5374  
5375   if (nargs != nparms
5376       && !(variadic_p && nargs >= nparms - 1))
5377     return 0;
5378
5379   /* Check all of the template parameters except the parameter pack at
5380      the end (if any).  */
5381   for (i = 0; i < nparms - variadic_p; ++i)
5382     {
5383       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5384           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5385         continue;
5386
5387       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5388       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5389
5390       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5391                                           outer_args))
5392         return 0;
5393
5394     }
5395
5396   if (variadic_p)
5397     {
5398       /* Check each of the template parameters in the template
5399          argument against the template parameter pack at the end of
5400          the template template parameter.  */
5401       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5402         return 0;
5403
5404       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5405
5406       for (; i < nargs; ++i)
5407         {
5408           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5409             continue;
5410  
5411           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5412  
5413           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5414                                               outer_args))
5415             return 0;
5416         }
5417     }
5418
5419   return 1;
5420 }
5421
5422 /* Verifies that the deduced template arguments (in TARGS) for the
5423    template template parameters (in TPARMS) represent valid bindings,
5424    by comparing the template parameter list of each template argument
5425    to the template parameter list of its corresponding template
5426    template parameter, in accordance with DR150. This
5427    routine can only be called after all template arguments have been
5428    deduced. It will return TRUE if all of the template template
5429    parameter bindings are okay, FALSE otherwise.  */
5430 bool 
5431 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5432 {
5433   int i, ntparms = TREE_VEC_LENGTH (tparms);
5434   bool ret = true;
5435
5436   /* We're dealing with template parms in this process.  */
5437   ++processing_template_decl;
5438
5439   targs = INNERMOST_TEMPLATE_ARGS (targs);
5440
5441   for (i = 0; i < ntparms; ++i)
5442     {
5443       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5444       tree targ = TREE_VEC_ELT (targs, i);
5445
5446       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5447         {
5448           tree packed_args = NULL_TREE;
5449           int idx, len = 1;
5450
5451           if (ARGUMENT_PACK_P (targ))
5452             {
5453               /* Look inside the argument pack.  */
5454               packed_args = ARGUMENT_PACK_ARGS (targ);
5455               len = TREE_VEC_LENGTH (packed_args);
5456             }
5457
5458           for (idx = 0; idx < len; ++idx)
5459             {
5460               tree targ_parms = NULL_TREE;
5461
5462               if (packed_args)
5463                 /* Extract the next argument from the argument
5464                    pack.  */
5465                 targ = TREE_VEC_ELT (packed_args, idx);
5466
5467               if (PACK_EXPANSION_P (targ))
5468                 /* Look at the pattern of the pack expansion.  */
5469                 targ = PACK_EXPANSION_PATTERN (targ);
5470
5471               /* Extract the template parameters from the template
5472                  argument.  */
5473               if (TREE_CODE (targ) == TEMPLATE_DECL)
5474                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5475               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5476                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5477
5478               /* Verify that we can coerce the template template
5479                  parameters from the template argument to the template
5480                  parameter.  This requires an exact match.  */
5481               if (targ_parms
5482                   && !coerce_template_template_parms
5483                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5484                         targ_parms,
5485                         tf_none,
5486                         tparm,
5487                         targs))
5488                 {
5489                   ret = false;
5490                   goto out;
5491                 }
5492             }
5493         }
5494     }
5495
5496  out:
5497
5498   --processing_template_decl;
5499   return ret;
5500 }
5501
5502 /* Convert the indicated template ARG as necessary to match the
5503    indicated template PARM.  Returns the converted ARG, or
5504    error_mark_node if the conversion was unsuccessful.  Error and
5505    warning messages are issued under control of COMPLAIN.  This
5506    conversion is for the Ith parameter in the parameter list.  ARGS is
5507    the full set of template arguments deduced so far.  */
5508
5509 static tree
5510 convert_template_argument (tree parm,
5511                            tree arg,
5512                            tree args,
5513                            tsubst_flags_t complain,
5514                            int i,
5515                            tree in_decl)
5516 {
5517   tree orig_arg;
5518   tree val;
5519   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5520
5521   if (TREE_CODE (arg) == TREE_LIST
5522       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5523     {
5524       /* The template argument was the name of some
5525          member function.  That's usually
5526          invalid, but static members are OK.  In any
5527          case, grab the underlying fields/functions
5528          and issue an error later if required.  */
5529       orig_arg = TREE_VALUE (arg);
5530       TREE_TYPE (arg) = unknown_type_node;
5531     }
5532
5533   orig_arg = arg;
5534
5535   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5536   requires_type = (TREE_CODE (parm) == TYPE_DECL
5537                    || requires_tmpl_type);
5538
5539   /* When determining whether an argument pack expansion is a template,
5540      look at the pattern.  */
5541   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5542     arg = PACK_EXPANSION_PATTERN (arg);
5543
5544   /* Deal with an injected-class-name used as a template template arg.  */
5545   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5546     {
5547       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5548       if (TREE_CODE (t) == TEMPLATE_DECL)
5549         {
5550           if (complain & tf_warning_or_error)
5551             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5552                      " used as template template argument", TYPE_NAME (arg));
5553           else if (flag_pedantic_errors)
5554             t = arg;
5555
5556           arg = t;
5557         }
5558     }
5559
5560   is_tmpl_type = 
5561     ((TREE_CODE (arg) == TEMPLATE_DECL
5562       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5563      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5564      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5565
5566   if (is_tmpl_type
5567       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5568           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5569     arg = TYPE_STUB_DECL (arg);
5570
5571   is_type = TYPE_P (arg) || is_tmpl_type;
5572
5573   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5574       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5575     {
5576       permerror (input_location, "to refer to a type member of a template parameter, "
5577                  "use %<typename %E%>", orig_arg);
5578
5579       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5580                                      TREE_OPERAND (arg, 1),
5581                                      typename_type,
5582                                      complain & tf_error);
5583       arg = orig_arg;
5584       is_type = 1;
5585     }
5586   if (is_type != requires_type)
5587     {
5588       if (in_decl)
5589         {
5590           if (complain & tf_error)
5591             {
5592               error ("type/value mismatch at argument %d in template "
5593                      "parameter list for %qD",
5594                      i + 1, in_decl);
5595               if (is_type)
5596                 error ("  expected a constant of type %qT, got %qT",
5597                        TREE_TYPE (parm),
5598                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5599               else if (requires_tmpl_type)
5600                 error ("  expected a class template, got %qE", orig_arg);
5601               else
5602                 error ("  expected a type, got %qE", orig_arg);
5603             }
5604         }
5605       return error_mark_node;
5606     }
5607   if (is_tmpl_type ^ requires_tmpl_type)
5608     {
5609       if (in_decl && (complain & tf_error))
5610         {
5611           error ("type/value mismatch at argument %d in template "
5612                  "parameter list for %qD",
5613                  i + 1, in_decl);
5614           if (is_tmpl_type)
5615             error ("  expected a type, got %qT", DECL_NAME (arg));
5616           else
5617             error ("  expected a class template, got %qT", orig_arg);
5618         }
5619       return error_mark_node;
5620     }
5621
5622   if (is_type)
5623     {
5624       if (requires_tmpl_type)
5625         {
5626           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5627             /* The number of argument required is not known yet.
5628                Just accept it for now.  */
5629             val = TREE_TYPE (arg);
5630           else
5631             {
5632               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5633               tree argparm;
5634
5635               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5636
5637               if (coerce_template_template_parms (parmparm, argparm,
5638                                                   complain, in_decl,
5639                                                   args))
5640                 {
5641                   val = arg;
5642
5643                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5644                      TEMPLATE_DECL.  */
5645                   if (val != error_mark_node)
5646                     {
5647                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5648                         val = TREE_TYPE (val);
5649                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5650                         val = make_pack_expansion (val);
5651                     }
5652                 }
5653               else
5654                 {
5655                   if (in_decl && (complain & tf_error))
5656                     {
5657                       error ("type/value mismatch at argument %d in "
5658                              "template parameter list for %qD",
5659                              i + 1, in_decl);
5660                       error ("  expected a template of type %qD, got %qT",
5661                              parm, orig_arg);
5662                     }
5663
5664                   val = error_mark_node;
5665                 }
5666             }
5667         }
5668       else
5669         val = orig_arg;
5670       /* We only form one instance of each template specialization.
5671          Therefore, if we use a non-canonical variant (i.e., a
5672          typedef), any future messages referring to the type will use
5673          the typedef, which is confusing if those future uses do not
5674          themselves also use the typedef.  */
5675       if (TYPE_P (val))
5676         val = strip_typedefs (val);
5677     }
5678   else
5679     {
5680       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5681
5682       if (invalid_nontype_parm_type_p (t, complain))
5683         return error_mark_node;
5684
5685       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5686         {
5687           if (same_type_p (t, TREE_TYPE (orig_arg)))
5688             val = orig_arg;
5689           else
5690             {
5691               /* Not sure if this is reachable, but it doesn't hurt
5692                  to be robust.  */
5693               error ("type mismatch in nontype parameter pack");
5694               val = error_mark_node;
5695             }
5696         }
5697       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5698         /* We used to call digest_init here.  However, digest_init
5699            will report errors, which we don't want when complain
5700            is zero.  More importantly, digest_init will try too
5701            hard to convert things: for example, `0' should not be
5702            converted to pointer type at this point according to
5703            the standard.  Accepting this is not merely an
5704            extension, since deciding whether or not these
5705            conversions can occur is part of determining which
5706            function template to call, or whether a given explicit
5707            argument specification is valid.  */
5708         val = convert_nontype_argument (t, orig_arg);
5709       else
5710         val = orig_arg;
5711
5712       if (val == NULL_TREE)
5713         val = error_mark_node;
5714       else if (val == error_mark_node && (complain & tf_error))
5715         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5716
5717       if (TREE_CODE (val) == SCOPE_REF)
5718         {
5719           /* Strip typedefs from the SCOPE_REF.  */
5720           tree type = strip_typedefs (TREE_TYPE (val));
5721           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5722           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5723                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5724         }
5725     }
5726
5727   return val;
5728 }
5729
5730 /* Coerces the remaining template arguments in INNER_ARGS (from
5731    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5732    Returns the coerced argument pack. PARM_IDX is the position of this
5733    parameter in the template parameter list. ARGS is the original
5734    template argument list.  */
5735 static tree
5736 coerce_template_parameter_pack (tree parms,
5737                                 int parm_idx,
5738                                 tree args,
5739                                 tree inner_args,
5740                                 int arg_idx,
5741                                 tree new_args,
5742                                 int* lost,
5743                                 tree in_decl,
5744                                 tsubst_flags_t complain)
5745 {
5746   tree parm = TREE_VEC_ELT (parms, parm_idx);
5747   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5748   tree packed_args;
5749   tree argument_pack;
5750   tree packed_types = NULL_TREE;
5751
5752   if (arg_idx > nargs)
5753     arg_idx = nargs;
5754
5755   packed_args = make_tree_vec (nargs - arg_idx);
5756
5757   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5758       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5759     {
5760       /* When the template parameter is a non-type template
5761          parameter pack whose type uses parameter packs, we need
5762          to look at each of the template arguments
5763          separately. Build a vector of the types for these
5764          non-type template parameters in PACKED_TYPES.  */
5765       tree expansion 
5766         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5767       packed_types = tsubst_pack_expansion (expansion, args,
5768                                             complain, in_decl);
5769
5770       if (packed_types == error_mark_node)
5771         return error_mark_node;
5772
5773       /* Check that we have the right number of arguments.  */
5774       if (arg_idx < nargs
5775           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5776           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5777         {
5778           int needed_parms 
5779             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5780           error ("wrong number of template arguments (%d, should be %d)",
5781                  nargs, needed_parms);
5782           return error_mark_node;
5783         }
5784
5785       /* If we aren't able to check the actual arguments now
5786          (because they haven't been expanded yet), we can at least
5787          verify that all of the types used for the non-type
5788          template parameter pack are, in fact, valid for non-type
5789          template parameters.  */
5790       if (arg_idx < nargs 
5791           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5792         {
5793           int j, len = TREE_VEC_LENGTH (packed_types);
5794           for (j = 0; j < len; ++j)
5795             {
5796               tree t = TREE_VEC_ELT (packed_types, j);
5797               if (invalid_nontype_parm_type_p (t, complain))
5798                 return error_mark_node;
5799             }
5800         }
5801     }
5802
5803   /* Convert the remaining arguments, which will be a part of the
5804      parameter pack "parm".  */
5805   for (; arg_idx < nargs; ++arg_idx)
5806     {
5807       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5808       tree actual_parm = TREE_VALUE (parm);
5809
5810       if (packed_types && !PACK_EXPANSION_P (arg))
5811         {
5812           /* When we have a vector of types (corresponding to the
5813              non-type template parameter pack that uses parameter
5814              packs in its type, as mention above), and the
5815              argument is not an expansion (which expands to a
5816              currently unknown number of arguments), clone the
5817              parm and give it the next type in PACKED_TYPES.  */
5818           actual_parm = copy_node (actual_parm);
5819           TREE_TYPE (actual_parm) = 
5820             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5821         }
5822
5823       if (arg != error_mark_node)
5824         arg = convert_template_argument (actual_parm, 
5825                                          arg, new_args, complain, parm_idx,
5826                                          in_decl);
5827       if (arg == error_mark_node)
5828         (*lost)++;
5829       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5830     }
5831
5832   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5833       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5834     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5835   else
5836     {
5837       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5838       TREE_TYPE (argument_pack) 
5839         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5840       TREE_CONSTANT (argument_pack) = 1;
5841     }
5842
5843   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5844 #ifdef ENABLE_CHECKING
5845   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5846                                        TREE_VEC_LENGTH (packed_args));
5847 #endif
5848   return argument_pack;
5849 }
5850
5851 /* Convert all template arguments to their appropriate types, and
5852    return a vector containing the innermost resulting template
5853    arguments.  If any error occurs, return error_mark_node. Error and
5854    warning messages are issued under control of COMPLAIN.
5855
5856    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5857    for arguments not specified in ARGS.  Otherwise, if
5858    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5859    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5860    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5861    ARGS.  */
5862
5863 static tree
5864 coerce_template_parms (tree parms,
5865                        tree args,
5866                        tree in_decl,
5867                        tsubst_flags_t complain,
5868                        bool require_all_args,
5869                        bool use_default_args)
5870 {
5871   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5872   tree inner_args;
5873   tree new_args;
5874   tree new_inner_args;
5875   int saved_unevaluated_operand;
5876   int saved_inhibit_evaluation_warnings;
5877
5878   /* When used as a boolean value, indicates whether this is a
5879      variadic template parameter list. Since it's an int, we can also
5880      subtract it from nparms to get the number of non-variadic
5881      parameters.  */
5882   int variadic_p = 0;
5883
5884   nparms = TREE_VEC_LENGTH (parms);
5885
5886   /* Determine if there are any parameter packs.  */
5887   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5888     {
5889       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5890       if (template_parameter_pack_p (tparm))
5891         ++variadic_p;
5892     }
5893
5894   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5895   /* If there are 0 or 1 parameter packs, we need to expand any argument
5896      packs so that we can deduce a parameter pack from some non-packed args
5897      followed by an argument pack, as in variadic85.C.  If there are more
5898      than that, we need to leave argument packs intact so the arguments are
5899      assigned to the right parameter packs.  This should only happen when
5900      dealing with a nested class inside a partial specialization of a class
5901      template, as in variadic92.C.  */
5902   if (variadic_p <= 1)
5903     inner_args = expand_template_argument_pack (inner_args);
5904
5905   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5906   if ((nargs > nparms && !variadic_p)
5907       || (nargs < nparms - variadic_p
5908           && require_all_args
5909           && (!use_default_args
5910               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5911                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5912     {
5913       if (complain & tf_error)
5914         {
5915           const char *or_more = "";
5916           if (variadic_p)
5917             {
5918               or_more = " or more";
5919               --nparms;
5920             }
5921
5922           error ("wrong number of template arguments (%d, should be %d%s)",
5923                  nargs, nparms, or_more);
5924
5925           if (in_decl)
5926             error ("provided for %q+D", in_decl);
5927         }
5928
5929       return error_mark_node;
5930     }
5931
5932   /* We need to evaluate the template arguments, even though this
5933      template-id may be nested within a "sizeof".  */
5934   saved_unevaluated_operand = cp_unevaluated_operand;
5935   cp_unevaluated_operand = 0;
5936   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5937   c_inhibit_evaluation_warnings = 0;
5938   new_inner_args = make_tree_vec (nparms);
5939   new_args = add_outermost_template_args (args, new_inner_args);
5940   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5941     {
5942       tree arg;
5943       tree parm;
5944
5945       /* Get the Ith template parameter.  */
5946       parm = TREE_VEC_ELT (parms, parm_idx);
5947  
5948       if (parm == error_mark_node)
5949       {
5950         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5951         continue;
5952       }
5953
5954       /* Calculate the next argument.  */
5955       if (arg_idx < nargs)
5956         arg = TREE_VEC_ELT (inner_args, arg_idx);
5957       else
5958         arg = NULL_TREE;
5959
5960       if (template_parameter_pack_p (TREE_VALUE (parm))
5961           && !(arg && ARGUMENT_PACK_P (arg)))
5962         {
5963           /* All remaining arguments will be placed in the
5964              template parameter pack PARM.  */
5965           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5966                                                 inner_args, arg_idx,
5967                                                 new_args, &lost,
5968                                                 in_decl, complain);
5969
5970           /* Store this argument.  */
5971           if (arg == error_mark_node)
5972             lost++;
5973           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5974
5975           /* We are done with all of the arguments.  */
5976           arg_idx = nargs;
5977           
5978           continue;
5979         }
5980       else if (arg)
5981         {
5982           if (PACK_EXPANSION_P (arg))
5983             {
5984               if (complain & tf_error)
5985                 {
5986                   /* FIXME this restriction was removed by N2555; see
5987                      bug 35722.  */
5988                   /* If ARG is a pack expansion, but PARM is not a
5989                      template parameter pack (if it were, we would have
5990                      handled it above), we're trying to expand into a
5991                      fixed-length argument list.  */
5992                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5993                     sorry ("cannot expand %<%E%> into a fixed-length "
5994                            "argument list", arg);
5995                   else
5996                     sorry ("cannot expand %<%T%> into a fixed-length "
5997                            "argument list", arg);
5998                 }
5999               return error_mark_node;
6000             }
6001         }
6002       else if (require_all_args)
6003         {
6004           /* There must be a default arg in this case.  */
6005           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6006                                      complain, in_decl);
6007           /* The position of the first default template argument,
6008              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6009              Record that.  */
6010           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6011             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6012         }
6013       else
6014         break;
6015
6016       if (arg == error_mark_node)
6017         {
6018           if (complain & tf_error)
6019             error ("template argument %d is invalid", arg_idx + 1);
6020         }
6021       else if (!arg)
6022         /* This only occurs if there was an error in the template
6023            parameter list itself (which we would already have
6024            reported) that we are trying to recover from, e.g., a class
6025            template with a parameter list such as
6026            template<typename..., typename>.  */
6027         return error_mark_node;
6028       else
6029         arg = convert_template_argument (TREE_VALUE (parm),
6030                                          arg, new_args, complain, 
6031                                          parm_idx, in_decl);
6032
6033       if (arg == error_mark_node)
6034         lost++;
6035       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6036     }
6037   cp_unevaluated_operand = saved_unevaluated_operand;
6038   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6039
6040   if (lost)
6041     return error_mark_node;
6042
6043 #ifdef ENABLE_CHECKING
6044   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6045     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6046                                          TREE_VEC_LENGTH (new_inner_args));
6047 #endif
6048
6049   return new_inner_args;
6050 }
6051
6052 /* Returns 1 if template args OT and NT are equivalent.  */
6053
6054 static int
6055 template_args_equal (tree ot, tree nt)
6056 {
6057   if (nt == ot)
6058     return 1;
6059
6060   if (TREE_CODE (nt) == TREE_VEC)
6061     /* For member templates */
6062     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6063   else if (PACK_EXPANSION_P (ot))
6064     return PACK_EXPANSION_P (nt) 
6065       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6066                               PACK_EXPANSION_PATTERN (nt));
6067   else if (ARGUMENT_PACK_P (ot))
6068     {
6069       int i, len;
6070       tree opack, npack;
6071
6072       if (!ARGUMENT_PACK_P (nt))
6073         return 0;
6074
6075       opack = ARGUMENT_PACK_ARGS (ot);
6076       npack = ARGUMENT_PACK_ARGS (nt);
6077       len = TREE_VEC_LENGTH (opack);
6078       if (TREE_VEC_LENGTH (npack) != len)
6079         return 0;
6080       for (i = 0; i < len; ++i)
6081         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6082                                   TREE_VEC_ELT (npack, i)))
6083           return 0;
6084       return 1;
6085     }
6086   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6087     {
6088       /* We get here probably because we are in the middle of substituting
6089          into the pattern of a pack expansion. In that case the
6090          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6091          interested in. So we want to use the initial pack argument for
6092          the comparison.  */
6093       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6094       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6095         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6096       return template_args_equal (ot, nt);
6097     }
6098   else if (TYPE_P (nt))
6099     return TYPE_P (ot) && same_type_p (ot, nt);
6100   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6101     return 0;
6102   else
6103     return cp_tree_equal (ot, nt);
6104 }
6105
6106 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6107    of template arguments.  Returns 0 otherwise.  */
6108
6109 int
6110 comp_template_args (tree oldargs, tree newargs)
6111 {
6112   int i;
6113
6114   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6115     return 0;
6116
6117   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6118     {
6119       tree nt = TREE_VEC_ELT (newargs, i);
6120       tree ot = TREE_VEC_ELT (oldargs, i);
6121
6122       if (! template_args_equal (ot, nt))
6123         return 0;
6124     }
6125   return 1;
6126 }
6127
6128 static void
6129 add_pending_template (tree d)
6130 {
6131   tree ti = (TYPE_P (d)
6132              ? CLASSTYPE_TEMPLATE_INFO (d)
6133              : DECL_TEMPLATE_INFO (d));
6134   struct pending_template *pt;
6135   int level;
6136
6137   if (TI_PENDING_TEMPLATE_FLAG (ti))
6138     return;
6139
6140   /* We are called both from instantiate_decl, where we've already had a
6141      tinst_level pushed, and instantiate_template, where we haven't.
6142      Compensate.  */
6143   level = !current_tinst_level || current_tinst_level->decl != d;
6144
6145   if (level)
6146     push_tinst_level (d);
6147
6148   pt = GGC_NEW (struct pending_template);
6149   pt->next = NULL;
6150   pt->tinst = current_tinst_level;
6151   if (last_pending_template)
6152     last_pending_template->next = pt;
6153   else
6154     pending_templates = pt;
6155
6156   last_pending_template = pt;
6157
6158   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6159
6160   if (level)
6161     pop_tinst_level ();
6162 }
6163
6164
6165 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6166    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6167    documentation for TEMPLATE_ID_EXPR.  */
6168
6169 tree
6170 lookup_template_function (tree fns, tree arglist)
6171 {
6172   tree type;
6173
6174   if (fns == error_mark_node || arglist == error_mark_node)
6175     return error_mark_node;
6176
6177   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6178   gcc_assert (fns && (is_overloaded_fn (fns)
6179                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6180
6181   if (BASELINK_P (fns))
6182     {
6183       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6184                                          unknown_type_node,
6185                                          BASELINK_FUNCTIONS (fns),
6186                                          arglist);
6187       return fns;
6188     }
6189
6190   type = TREE_TYPE (fns);
6191   if (TREE_CODE (fns) == OVERLOAD || !type)
6192     type = unknown_type_node;
6193
6194   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6195 }
6196
6197 /* Within the scope of a template class S<T>, the name S gets bound
6198    (in build_self_reference) to a TYPE_DECL for the class, not a
6199    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6200    or one of its enclosing classes, and that type is a template,
6201    return the associated TEMPLATE_DECL.  Otherwise, the original
6202    DECL is returned.
6203
6204    Also handle the case when DECL is a TREE_LIST of ambiguous
6205    injected-class-names from different bases.  */
6206
6207 tree
6208 maybe_get_template_decl_from_type_decl (tree decl)
6209 {
6210   if (decl == NULL_TREE)
6211     return decl;
6212
6213   /* DR 176: A lookup that finds an injected-class-name (10.2
6214      [class.member.lookup]) can result in an ambiguity in certain cases
6215      (for example, if it is found in more than one base class). If all of
6216      the injected-class-names that are found refer to specializations of
6217      the same class template, and if the name is followed by a
6218      template-argument-list, the reference refers to the class template
6219      itself and not a specialization thereof, and is not ambiguous.  */
6220   if (TREE_CODE (decl) == TREE_LIST)
6221     {
6222       tree t, tmpl = NULL_TREE;
6223       for (t = decl; t; t = TREE_CHAIN (t))
6224         {
6225           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6226           if (!tmpl)
6227             tmpl = elt;
6228           else if (tmpl != elt)
6229             break;
6230         }
6231       if (tmpl && t == NULL_TREE)
6232         return tmpl;
6233       else
6234         return decl;
6235     }
6236
6237   return (decl != NULL_TREE
6238           && DECL_SELF_REFERENCE_P (decl)
6239           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6240     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6241 }
6242
6243 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6244    parameters, find the desired type.
6245
6246    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6247
6248    IN_DECL, if non-NULL, is the template declaration we are trying to
6249    instantiate.
6250
6251    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6252    the class we are looking up.
6253
6254    Issue error and warning messages under control of COMPLAIN.
6255
6256    If the template class is really a local class in a template
6257    function, then the FUNCTION_CONTEXT is the function in which it is
6258    being instantiated.
6259
6260    ??? Note that this function is currently called *twice* for each
6261    template-id: the first time from the parser, while creating the
6262    incomplete type (finish_template_type), and the second type during the
6263    real instantiation (instantiate_template_class). This is surely something
6264    that we want to avoid. It also causes some problems with argument
6265    coercion (see convert_nontype_argument for more information on this).  */
6266
6267 tree
6268 lookup_template_class (tree d1,
6269                        tree arglist,
6270                        tree in_decl,
6271                        tree context,
6272                        int entering_scope,
6273                        tsubst_flags_t complain)
6274 {
6275   tree templ = NULL_TREE, parmlist;
6276   tree t;
6277   spec_entry **slot;
6278   spec_entry *entry;
6279   spec_entry elt;
6280   hashval_t hash;
6281
6282   timevar_push (TV_NAME_LOOKUP);
6283
6284   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6285     {
6286       tree value = innermost_non_namespace_value (d1);
6287       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6288         templ = value;
6289       else
6290         {
6291           if (context)
6292             push_decl_namespace (context);
6293           templ = lookup_name (d1);
6294           templ = maybe_get_template_decl_from_type_decl (templ);
6295           if (context)
6296             pop_decl_namespace ();
6297         }
6298       if (templ)
6299         context = DECL_CONTEXT (templ);
6300     }
6301   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6302     {
6303       tree type = TREE_TYPE (d1);
6304
6305       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6306          an implicit typename for the second A.  Deal with it.  */
6307       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6308         type = TREE_TYPE (type);
6309
6310       if (CLASSTYPE_TEMPLATE_INFO (type))
6311         {
6312           templ = CLASSTYPE_TI_TEMPLATE (type);
6313           d1 = DECL_NAME (templ);
6314         }
6315     }
6316   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6317            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6318     {
6319       templ = TYPE_TI_TEMPLATE (d1);
6320       d1 = DECL_NAME (templ);
6321     }
6322   else if (TREE_CODE (d1) == TEMPLATE_DECL
6323            && DECL_TEMPLATE_RESULT (d1)
6324            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6325     {
6326       templ = d1;
6327       d1 = DECL_NAME (templ);
6328       context = DECL_CONTEXT (templ);
6329     }
6330
6331   /* Issue an error message if we didn't find a template.  */
6332   if (! templ)
6333     {
6334       if (complain & tf_error)
6335         error ("%qT is not a template", d1);
6336       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6337     }
6338
6339   if (TREE_CODE (templ) != TEMPLATE_DECL
6340          /* Make sure it's a user visible template, if it was named by
6341             the user.  */
6342       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6343           && !PRIMARY_TEMPLATE_P (templ)))
6344     {
6345       if (complain & tf_error)
6346         {
6347           error ("non-template type %qT used as a template", d1);
6348           if (in_decl)
6349             error ("for template declaration %q+D", in_decl);
6350         }
6351       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6352     }
6353
6354   complain &= ~tf_user;
6355
6356   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6357     {
6358       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6359          template arguments */
6360
6361       tree parm;
6362       tree arglist2;
6363       tree outer;
6364
6365       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6366
6367       /* Consider an example where a template template parameter declared as
6368
6369            template <class T, class U = std::allocator<T> > class TT
6370
6371          The template parameter level of T and U are one level larger than
6372          of TT.  To proper process the default argument of U, say when an
6373          instantiation `TT<int>' is seen, we need to build the full
6374          arguments containing {int} as the innermost level.  Outer levels,
6375          available when not appearing as default template argument, can be
6376          obtained from the arguments of the enclosing template.
6377
6378          Suppose that TT is later substituted with std::vector.  The above
6379          instantiation is `TT<int, std::allocator<T> >' with TT at
6380          level 1, and T at level 2, while the template arguments at level 1
6381          becomes {std::vector} and the inner level 2 is {int}.  */
6382
6383       outer = DECL_CONTEXT (templ);
6384       if (outer)
6385         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6386       else if (current_template_parms)
6387         /* This is an argument of the current template, so we haven't set
6388            DECL_CONTEXT yet.  */
6389         outer = current_template_args ();
6390
6391       if (outer)
6392         arglist = add_to_template_args (outer, arglist);
6393
6394       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6395                                         complain,
6396                                         /*require_all_args=*/true,
6397                                         /*use_default_args=*/true);
6398       if (arglist2 == error_mark_node
6399           || (!uses_template_parms (arglist2)
6400               && check_instantiated_args (templ, arglist2, complain)))
6401         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6402
6403       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6404       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6405     }
6406   else
6407     {
6408       tree template_type = TREE_TYPE (templ);
6409       tree gen_tmpl;
6410       tree type_decl;
6411       tree found = NULL_TREE;
6412       int arg_depth;
6413       int parm_depth;
6414       int is_dependent_type;
6415       int use_partial_inst_tmpl = false;
6416
6417       gen_tmpl = most_general_template (templ);
6418       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6419       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6420       arg_depth = TMPL_ARGS_DEPTH (arglist);
6421
6422       if (arg_depth == 1 && parm_depth > 1)
6423         {
6424           /* We've been given an incomplete set of template arguments.
6425              For example, given:
6426
6427                template <class T> struct S1 {
6428                  template <class U> struct S2 {};
6429                  template <class U> struct S2<U*> {};
6430                 };
6431
6432              we will be called with an ARGLIST of `U*', but the
6433              TEMPLATE will be `template <class T> template
6434              <class U> struct S1<T>::S2'.  We must fill in the missing
6435              arguments.  */
6436           arglist
6437             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6438                                            arglist);
6439           arg_depth = TMPL_ARGS_DEPTH (arglist);
6440         }
6441
6442       /* Now we should have enough arguments.  */
6443       gcc_assert (parm_depth == arg_depth);
6444
6445       /* From here on, we're only interested in the most general
6446          template.  */
6447
6448       /* Calculate the BOUND_ARGS.  These will be the args that are
6449          actually tsubst'd into the definition to create the
6450          instantiation.  */
6451       if (parm_depth > 1)
6452         {
6453           /* We have multiple levels of arguments to coerce, at once.  */
6454           int i;
6455           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6456
6457           tree bound_args = make_tree_vec (parm_depth);
6458
6459           for (i = saved_depth,
6460                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6461                i > 0 && t != NULL_TREE;
6462                --i, t = TREE_CHAIN (t))
6463             {
6464               tree a = coerce_template_parms (TREE_VALUE (t),
6465                                               arglist, gen_tmpl,
6466                                               complain,
6467                                               /*require_all_args=*/true,
6468                                               /*use_default_args=*/true);
6469
6470               /* Don't process further if one of the levels fails.  */
6471               if (a == error_mark_node)
6472                 {
6473                   /* Restore the ARGLIST to its full size.  */
6474                   TREE_VEC_LENGTH (arglist) = saved_depth;
6475                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6476                 }
6477
6478               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6479
6480               /* We temporarily reduce the length of the ARGLIST so
6481                  that coerce_template_parms will see only the arguments
6482                  corresponding to the template parameters it is
6483                  examining.  */
6484               TREE_VEC_LENGTH (arglist)--;
6485             }
6486
6487           /* Restore the ARGLIST to its full size.  */
6488           TREE_VEC_LENGTH (arglist) = saved_depth;
6489
6490           arglist = bound_args;
6491         }
6492       else
6493         arglist
6494           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6495                                    INNERMOST_TEMPLATE_ARGS (arglist),
6496                                    gen_tmpl,
6497                                    complain,
6498                                    /*require_all_args=*/true,
6499                                    /*use_default_args=*/true);
6500
6501       if (arglist == error_mark_node)
6502         /* We were unable to bind the arguments.  */
6503         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6504
6505       /* In the scope of a template class, explicit references to the
6506          template class refer to the type of the template, not any
6507          instantiation of it.  For example, in:
6508
6509            template <class T> class C { void f(C<T>); }
6510
6511          the `C<T>' is just the same as `C'.  Outside of the
6512          class, however, such a reference is an instantiation.  */
6513       if ((entering_scope
6514            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6515            || currently_open_class (template_type))
6516           /* comp_template_args is expensive, check it last.  */
6517           && comp_template_args (TYPE_TI_ARGS (template_type),
6518                                  arglist))
6519         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6520
6521       /* If we already have this specialization, return it.  */
6522       elt.tmpl = gen_tmpl;
6523       elt.args = arglist;
6524       hash = hash_specialization (&elt);
6525       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6526                                                   &elt, hash);
6527
6528       if (entry)
6529         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6530
6531       is_dependent_type = uses_template_parms (arglist);
6532
6533       /* If the deduced arguments are invalid, then the binding
6534          failed.  */
6535       if (!is_dependent_type
6536           && check_instantiated_args (gen_tmpl,
6537                                       INNERMOST_TEMPLATE_ARGS (arglist),
6538                                       complain))
6539         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6540
6541       if (!is_dependent_type
6542           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6543           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6544           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6545         {
6546           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6547                                       DECL_NAME (gen_tmpl),
6548                                       /*tag_scope=*/ts_global);
6549           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6550         }
6551
6552       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6553                         complain, in_decl);
6554       if (!context)
6555         context = global_namespace;
6556
6557       /* Create the type.  */
6558       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6559         {
6560           if (!is_dependent_type)
6561             {
6562               set_current_access_from_decl (TYPE_NAME (template_type));
6563               t = start_enum (TYPE_IDENTIFIER (template_type),
6564                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6565                                       arglist, complain, in_decl),
6566                               SCOPED_ENUM_P (template_type));
6567             }
6568           else
6569             {
6570               /* We don't want to call start_enum for this type, since
6571                  the values for the enumeration constants may involve
6572                  template parameters.  And, no one should be interested
6573                  in the enumeration constants for such a type.  */
6574               t = cxx_make_type (ENUMERAL_TYPE);
6575               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6576             }
6577         }
6578       else
6579         {
6580           t = make_class_type (TREE_CODE (template_type));
6581           CLASSTYPE_DECLARED_CLASS (t)
6582             = CLASSTYPE_DECLARED_CLASS (template_type);
6583           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6584           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6585
6586           /* A local class.  Make sure the decl gets registered properly.  */
6587           if (context == current_function_decl)
6588             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6589
6590           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6591             /* This instantiation is another name for the primary
6592                template type. Set the TYPE_CANONICAL field
6593                appropriately. */
6594             TYPE_CANONICAL (t) = template_type;
6595           else if (any_template_arguments_need_structural_equality_p (arglist))
6596             /* Some of the template arguments require structural
6597                equality testing, so this template class requires
6598                structural equality testing. */
6599             SET_TYPE_STRUCTURAL_EQUALITY (t);
6600         }
6601
6602       /* If we called start_enum or pushtag above, this information
6603          will already be set up.  */
6604       if (!TYPE_NAME (t))
6605         {
6606           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6607
6608           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6609           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6610           DECL_SOURCE_LOCATION (type_decl)
6611             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6612         }
6613       else
6614         type_decl = TYPE_NAME (t);
6615
6616       TREE_PRIVATE (type_decl)
6617         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6618       TREE_PROTECTED (type_decl)
6619         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6620       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6621         {
6622           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6623           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6624         }
6625
6626       /* Let's consider the explicit specialization of a member
6627          of a class template specialization that is implicitely instantiated,
6628          e.g.:
6629              template<class T>
6630              struct S
6631              {
6632                template<class U> struct M {}; //#0
6633              };
6634
6635              template<>
6636              template<>
6637              struct S<int>::M<char> //#1
6638              {
6639                int i;
6640              };
6641         [temp.expl.spec]/4 says this is valid.
6642
6643         In this case, when we write:
6644         S<int>::M<char> m;
6645
6646         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6647         the one of #0.
6648
6649         When we encounter #1, we want to store the partial instantiation
6650         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6651
6652         For all cases other than this "explicit specialization of member of a
6653         class template", we just want to store the most general template into
6654         the CLASSTYPE_TI_TEMPLATE of M.
6655
6656         This case of "explicit specialization of member of a class template"
6657         only happens when:
6658         1/ the enclosing class is an instantiation of, and therefore not
6659         the same as, the context of the most general template, and
6660         2/ we aren't looking at the partial instantiation itself, i.e.
6661         the innermost arguments are not the same as the innermost parms of
6662         the most general template.
6663
6664         So it's only when 1/ and 2/ happens that we want to use the partial
6665         instantiation of the member template in lieu of its most general
6666         template.  */
6667
6668       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6669           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6670           /* the enclosing class must be an instantiation...  */
6671           && CLASS_TYPE_P (context)
6672           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6673         {
6674           tree partial_inst_args;
6675           TREE_VEC_LENGTH (arglist)--;
6676           ++processing_template_decl;
6677           partial_inst_args =
6678             tsubst (INNERMOST_TEMPLATE_ARGS
6679                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6680                     arglist, complain, NULL_TREE);
6681           --processing_template_decl;
6682           TREE_VEC_LENGTH (arglist)++;
6683           use_partial_inst_tmpl =
6684             /*...and we must not be looking at the partial instantiation
6685              itself. */
6686             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6687                                  partial_inst_args);
6688         }
6689
6690       if (!use_partial_inst_tmpl)
6691         /* This case is easy; there are no member templates involved.  */
6692         found = gen_tmpl;
6693       else
6694         {
6695           /* This is a full instantiation of a member template.  Find
6696              the partial instantiation of which this is an instance.  */
6697
6698           /* Temporarily reduce by one the number of levels in the ARGLIST
6699              so as to avoid comparing the last set of arguments.  */
6700           TREE_VEC_LENGTH (arglist)--;
6701           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6702           TREE_VEC_LENGTH (arglist)++;
6703           found = CLASSTYPE_TI_TEMPLATE (found);
6704         }
6705
6706       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6707
6708       elt.spec = t;
6709       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6710                                                        &elt, hash, INSERT);
6711       *slot = GGC_NEW (spec_entry);
6712       **slot = elt;
6713
6714       /* Note this use of the partial instantiation so we can check it
6715          later in maybe_process_partial_specialization.  */
6716       DECL_TEMPLATE_INSTANTIATIONS (templ)
6717         = tree_cons (arglist, t,
6718                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6719
6720       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6721         /* Now that the type has been registered on the instantiations
6722            list, we set up the enumerators.  Because the enumeration
6723            constants may involve the enumeration type itself, we make
6724            sure to register the type first, and then create the
6725            constants.  That way, doing tsubst_expr for the enumeration
6726            constants won't result in recursive calls here; we'll find
6727            the instantiation and exit above.  */
6728         tsubst_enum (template_type, t, arglist);
6729
6730       if (is_dependent_type)
6731         /* If the type makes use of template parameters, the
6732            code that generates debugging information will crash.  */
6733         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6734
6735       /* Possibly limit visibility based on template args.  */
6736       TREE_PUBLIC (type_decl) = 1;
6737       determine_visibility (type_decl);
6738
6739       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6740     }
6741   timevar_pop (TV_NAME_LOOKUP);
6742 }
6743 \f
6744 struct pair_fn_data
6745 {
6746   tree_fn_t fn;
6747   void *data;
6748   /* True when we should also visit template parameters that occur in
6749      non-deduced contexts.  */
6750   bool include_nondeduced_p;
6751   struct pointer_set_t *visited;
6752 };
6753
6754 /* Called from for_each_template_parm via walk_tree.  */
6755
6756 static tree
6757 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6758 {
6759   tree t = *tp;
6760   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6761   tree_fn_t fn = pfd->fn;
6762   void *data = pfd->data;
6763
6764   if (TYPE_P (t)
6765       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6766       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6767                                  pfd->include_nondeduced_p))
6768     return error_mark_node;
6769
6770   switch (TREE_CODE (t))
6771     {
6772     case RECORD_TYPE:
6773       if (TYPE_PTRMEMFUNC_P (t))
6774         break;
6775       /* Fall through.  */
6776
6777     case UNION_TYPE:
6778     case ENUMERAL_TYPE:
6779       if (!TYPE_TEMPLATE_INFO (t))
6780         *walk_subtrees = 0;
6781       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6782                                        fn, data, pfd->visited, 
6783                                        pfd->include_nondeduced_p))
6784         return error_mark_node;
6785       break;
6786
6787     case INTEGER_TYPE:
6788       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6789                                   fn, data, pfd->visited, 
6790                                   pfd->include_nondeduced_p)
6791           || for_each_template_parm (TYPE_MAX_VALUE (t),
6792                                      fn, data, pfd->visited,
6793                                      pfd->include_nondeduced_p))
6794         return error_mark_node;
6795       break;
6796
6797     case METHOD_TYPE:
6798       /* Since we're not going to walk subtrees, we have to do this
6799          explicitly here.  */
6800       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6801                                   pfd->visited, pfd->include_nondeduced_p))
6802         return error_mark_node;
6803       /* Fall through.  */
6804
6805     case FUNCTION_TYPE:
6806       /* Check the return type.  */
6807       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6808                                   pfd->include_nondeduced_p))
6809         return error_mark_node;
6810
6811       /* Check the parameter types.  Since default arguments are not
6812          instantiated until they are needed, the TYPE_ARG_TYPES may
6813          contain expressions that involve template parameters.  But,
6814          no-one should be looking at them yet.  And, once they're
6815          instantiated, they don't contain template parameters, so
6816          there's no point in looking at them then, either.  */
6817       {
6818         tree parm;
6819
6820         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6821           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6822                                       pfd->visited, pfd->include_nondeduced_p))
6823             return error_mark_node;
6824
6825         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6826            want walk_tree walking into them itself.  */
6827         *walk_subtrees = 0;
6828       }
6829       break;
6830
6831     case TYPEOF_TYPE:
6832       if (pfd->include_nondeduced_p
6833           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6834                                      pfd->visited, 
6835                                      pfd->include_nondeduced_p))
6836         return error_mark_node;
6837       break;
6838
6839     case FUNCTION_DECL:
6840     case VAR_DECL:
6841       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6842           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6843                                      pfd->visited, pfd->include_nondeduced_p))
6844         return error_mark_node;
6845       /* Fall through.  */
6846
6847     case PARM_DECL:
6848     case CONST_DECL:
6849       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6850           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6851                                      pfd->visited, pfd->include_nondeduced_p))
6852         return error_mark_node;
6853       if (DECL_CONTEXT (t)
6854           && pfd->include_nondeduced_p
6855           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6856                                      pfd->visited, pfd->include_nondeduced_p))
6857         return error_mark_node;
6858       break;
6859
6860     case BOUND_TEMPLATE_TEMPLATE_PARM:
6861       /* Record template parameters such as `T' inside `TT<T>'.  */
6862       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6863                                   pfd->include_nondeduced_p))
6864         return error_mark_node;
6865       /* Fall through.  */
6866
6867     case TEMPLATE_TEMPLATE_PARM:
6868     case TEMPLATE_TYPE_PARM:
6869     case TEMPLATE_PARM_INDEX:
6870       if (fn && (*fn)(t, data))
6871         return error_mark_node;
6872       else if (!fn)
6873         return error_mark_node;
6874       break;
6875
6876     case TEMPLATE_DECL:
6877       /* A template template parameter is encountered.  */
6878       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6879           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6880                                      pfd->include_nondeduced_p))
6881         return error_mark_node;
6882
6883       /* Already substituted template template parameter */
6884       *walk_subtrees = 0;
6885       break;
6886
6887     case TYPENAME_TYPE:
6888       if (!fn
6889           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6890                                      data, pfd->visited, 
6891                                      pfd->include_nondeduced_p))
6892         return error_mark_node;
6893       break;
6894
6895     case CONSTRUCTOR:
6896       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6897           && pfd->include_nondeduced_p
6898           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6899                                      (TREE_TYPE (t)), fn, data,
6900                                      pfd->visited, pfd->include_nondeduced_p))
6901         return error_mark_node;
6902       break;
6903
6904     case INDIRECT_REF:
6905     case COMPONENT_REF:
6906       /* If there's no type, then this thing must be some expression
6907          involving template parameters.  */
6908       if (!fn && !TREE_TYPE (t))
6909         return error_mark_node;
6910       break;
6911
6912     case MODOP_EXPR:
6913     case CAST_EXPR:
6914     case REINTERPRET_CAST_EXPR:
6915     case CONST_CAST_EXPR:
6916     case STATIC_CAST_EXPR:
6917     case DYNAMIC_CAST_EXPR:
6918     case ARROW_EXPR:
6919     case DOTSTAR_EXPR:
6920     case TYPEID_EXPR:
6921     case PSEUDO_DTOR_EXPR:
6922       if (!fn)
6923         return error_mark_node;
6924       break;
6925
6926     default:
6927       break;
6928     }
6929
6930   /* We didn't find any template parameters we liked.  */
6931   return NULL_TREE;
6932 }
6933
6934 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6935    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6936    call FN with the parameter and the DATA.
6937    If FN returns nonzero, the iteration is terminated, and
6938    for_each_template_parm returns 1.  Otherwise, the iteration
6939    continues.  If FN never returns a nonzero value, the value
6940    returned by for_each_template_parm is 0.  If FN is NULL, it is
6941    considered to be the function which always returns 1.
6942
6943    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6944    parameters that occur in non-deduced contexts.  When false, only
6945    visits those template parameters that can be deduced.  */
6946
6947 static int
6948 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6949                         struct pointer_set_t *visited,
6950                         bool include_nondeduced_p)
6951 {
6952   struct pair_fn_data pfd;
6953   int result;
6954
6955   /* Set up.  */
6956   pfd.fn = fn;
6957   pfd.data = data;
6958   pfd.include_nondeduced_p = include_nondeduced_p;
6959
6960   /* Walk the tree.  (Conceptually, we would like to walk without
6961      duplicates, but for_each_template_parm_r recursively calls
6962      for_each_template_parm, so we would need to reorganize a fair
6963      bit to use walk_tree_without_duplicates, so we keep our own
6964      visited list.)  */
6965   if (visited)
6966     pfd.visited = visited;
6967   else
6968     pfd.visited = pointer_set_create ();
6969   result = cp_walk_tree (&t,
6970                          for_each_template_parm_r,
6971                          &pfd,
6972                          pfd.visited) != NULL_TREE;
6973
6974   /* Clean up.  */
6975   if (!visited)
6976     {
6977       pointer_set_destroy (pfd.visited);
6978       pfd.visited = 0;
6979     }
6980
6981   return result;
6982 }
6983
6984 /* Returns true if T depends on any template parameter.  */
6985
6986 int
6987 uses_template_parms (tree t)
6988 {
6989   bool dependent_p;
6990   int saved_processing_template_decl;
6991
6992   saved_processing_template_decl = processing_template_decl;
6993   if (!saved_processing_template_decl)
6994     processing_template_decl = 1;
6995   if (TYPE_P (t))
6996     dependent_p = dependent_type_p (t);
6997   else if (TREE_CODE (t) == TREE_VEC)
6998     dependent_p = any_dependent_template_arguments_p (t);
6999   else if (TREE_CODE (t) == TREE_LIST)
7000     dependent_p = (uses_template_parms (TREE_VALUE (t))
7001                    || uses_template_parms (TREE_CHAIN (t)));
7002   else if (TREE_CODE (t) == TYPE_DECL)
7003     dependent_p = dependent_type_p (TREE_TYPE (t));
7004   else if (DECL_P (t)
7005            || EXPR_P (t)
7006            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7007            || TREE_CODE (t) == OVERLOAD
7008            || TREE_CODE (t) == BASELINK
7009            || TREE_CODE (t) == IDENTIFIER_NODE
7010            || TREE_CODE (t) == TRAIT_EXPR
7011            || TREE_CODE (t) == CONSTRUCTOR
7012            || CONSTANT_CLASS_P (t))
7013     dependent_p = (type_dependent_expression_p (t)
7014                    || value_dependent_expression_p (t));
7015   else
7016     {
7017       gcc_assert (t == error_mark_node);
7018       dependent_p = false;
7019     }
7020
7021   processing_template_decl = saved_processing_template_decl;
7022
7023   return dependent_p;
7024 }
7025
7026 /* Returns true if T depends on any template parameter with level LEVEL.  */
7027
7028 int
7029 uses_template_parms_level (tree t, int level)
7030 {
7031   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7032                                  /*include_nondeduced_p=*/true);
7033 }
7034
7035 static int tinst_depth;
7036 extern int max_tinst_depth;
7037 #ifdef GATHER_STATISTICS
7038 int depth_reached;
7039 #endif
7040 static int tinst_level_tick;
7041 static int last_template_error_tick;
7042
7043 /* We're starting to instantiate D; record the template instantiation context
7044    for diagnostics and to restore it later.  */
7045
7046 int
7047 push_tinst_level (tree d)
7048 {
7049   struct tinst_level *new_level;
7050
7051   if (tinst_depth >= max_tinst_depth)
7052     {
7053       /* If the instantiation in question still has unbound template parms,
7054          we don't really care if we can't instantiate it, so just return.
7055          This happens with base instantiation for implicit `typename'.  */
7056       if (uses_template_parms (d))
7057         return 0;
7058
7059       last_template_error_tick = tinst_level_tick;
7060       error ("template instantiation depth exceeds maximum of %d (use "
7061              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7062              max_tinst_depth, d);
7063
7064       print_instantiation_context ();
7065
7066       return 0;
7067     }
7068
7069   new_level = GGC_NEW (struct tinst_level);
7070   new_level->decl = d;
7071   new_level->locus = input_location;
7072   new_level->in_system_header_p = in_system_header;
7073   new_level->next = current_tinst_level;
7074   current_tinst_level = new_level;
7075
7076   ++tinst_depth;
7077 #ifdef GATHER_STATISTICS
7078   if (tinst_depth > depth_reached)
7079     depth_reached = tinst_depth;
7080 #endif
7081
7082   ++tinst_level_tick;
7083   return 1;
7084 }
7085
7086 /* We're done instantiating this template; return to the instantiation
7087    context.  */
7088
7089 void
7090 pop_tinst_level (void)
7091 {
7092   /* Restore the filename and line number stashed away when we started
7093      this instantiation.  */
7094   input_location = current_tinst_level->locus;
7095   current_tinst_level = current_tinst_level->next;
7096   --tinst_depth;
7097   ++tinst_level_tick;
7098 }
7099
7100 /* We're instantiating a deferred template; restore the template
7101    instantiation context in which the instantiation was requested, which
7102    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7103
7104 static tree
7105 reopen_tinst_level (struct tinst_level *level)
7106 {
7107   struct tinst_level *t;
7108
7109   tinst_depth = 0;
7110   for (t = level; t; t = t->next)
7111     ++tinst_depth;
7112
7113   current_tinst_level = level;
7114   pop_tinst_level ();
7115   return level->decl;
7116 }
7117
7118 /* Returns the TINST_LEVEL which gives the original instantiation
7119    context.  */
7120
7121 struct tinst_level *
7122 outermost_tinst_level (void)
7123 {
7124   struct tinst_level *level = current_tinst_level;
7125   if (level)
7126     while (level->next)
7127       level = level->next;
7128   return level;
7129 }
7130
7131 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7132
7133 bool
7134 parameter_of_template_p (tree parm, tree templ)
7135 {
7136   tree parms;
7137   int i;
7138
7139   if (!parm || !templ)
7140     return false;
7141
7142   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7143   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7144
7145   parms = DECL_TEMPLATE_PARMS (templ);
7146   parms = INNERMOST_TEMPLATE_PARMS (parms);
7147
7148   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7149     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7150       return true;
7151
7152   return false;
7153 }
7154
7155 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7156    vector of template arguments, as for tsubst.
7157
7158    Returns an appropriate tsubst'd friend declaration.  */
7159
7160 static tree
7161 tsubst_friend_function (tree decl, tree args)
7162 {
7163   tree new_friend;
7164
7165   if (TREE_CODE (decl) == FUNCTION_DECL
7166       && DECL_TEMPLATE_INSTANTIATION (decl)
7167       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7168     /* This was a friend declared with an explicit template
7169        argument list, e.g.:
7170
7171        friend void f<>(T);
7172
7173        to indicate that f was a template instantiation, not a new
7174        function declaration.  Now, we have to figure out what
7175        instantiation of what template.  */
7176     {
7177       tree template_id, arglist, fns;
7178       tree new_args;
7179       tree tmpl;
7180       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7181
7182       /* Friend functions are looked up in the containing namespace scope.
7183          We must enter that scope, to avoid finding member functions of the
7184          current class with same name.  */
7185       push_nested_namespace (ns);
7186       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7187                          tf_warning_or_error, NULL_TREE,
7188                          /*integral_constant_expression_p=*/false);
7189       pop_nested_namespace (ns);
7190       arglist = tsubst (DECL_TI_ARGS (decl), args,
7191                         tf_warning_or_error, NULL_TREE);
7192       template_id = lookup_template_function (fns, arglist);
7193
7194       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7195       tmpl = determine_specialization (template_id, new_friend,
7196                                        &new_args,
7197                                        /*need_member_template=*/0,
7198                                        TREE_VEC_LENGTH (args),
7199                                        tsk_none);
7200       return instantiate_template (tmpl, new_args, tf_error);
7201     }
7202
7203   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7204
7205   /* The NEW_FRIEND will look like an instantiation, to the
7206      compiler, but is not an instantiation from the point of view of
7207      the language.  For example, we might have had:
7208
7209      template <class T> struct S {
7210        template <class U> friend void f(T, U);
7211      };
7212
7213      Then, in S<int>, template <class U> void f(int, U) is not an
7214      instantiation of anything.  */
7215   if (new_friend == error_mark_node)
7216     return error_mark_node;
7217
7218   DECL_USE_TEMPLATE (new_friend) = 0;
7219   if (TREE_CODE (decl) == TEMPLATE_DECL)
7220     {
7221       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7222       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7223         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7224     }
7225
7226   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7227      is not a template instantiation and should not be mangled like
7228      one.  Therefore, we forget the mangling here; we'll recompute it
7229      later if we need it.  */
7230   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7231     {
7232       SET_DECL_RTL (new_friend, NULL_RTX);
7233       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7234     }
7235
7236   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7237     {
7238       tree old_decl;
7239       tree new_friend_template_info;
7240       tree new_friend_result_template_info;
7241       tree ns;
7242       int  new_friend_is_defn;
7243
7244       /* We must save some information from NEW_FRIEND before calling
7245          duplicate decls since that function will free NEW_FRIEND if
7246          possible.  */
7247       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7248       new_friend_is_defn =
7249             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7250                            (template_for_substitution (new_friend)))
7251              != NULL_TREE);
7252       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7253         {
7254           /* This declaration is a `primary' template.  */
7255           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7256
7257           new_friend_result_template_info
7258             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7259         }
7260       else
7261         new_friend_result_template_info = NULL_TREE;
7262
7263       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7264       if (new_friend_is_defn)
7265         DECL_INITIAL (new_friend) = error_mark_node;
7266
7267       /* Inside pushdecl_namespace_level, we will push into the
7268          current namespace. However, the friend function should go
7269          into the namespace of the template.  */
7270       ns = decl_namespace_context (new_friend);
7271       push_nested_namespace (ns);
7272       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7273       pop_nested_namespace (ns);
7274
7275       if (old_decl == error_mark_node)
7276         return error_mark_node;
7277
7278       if (old_decl != new_friend)
7279         {
7280           /* This new friend declaration matched an existing
7281              declaration.  For example, given:
7282
7283                template <class T> void f(T);
7284                template <class U> class C {
7285                  template <class T> friend void f(T) {}
7286                };
7287
7288              the friend declaration actually provides the definition
7289              of `f', once C has been instantiated for some type.  So,
7290              old_decl will be the out-of-class template declaration,
7291              while new_friend is the in-class definition.
7292
7293              But, if `f' was called before this point, the
7294              instantiation of `f' will have DECL_TI_ARGS corresponding
7295              to `T' but not to `U', references to which might appear
7296              in the definition of `f'.  Previously, the most general
7297              template for an instantiation of `f' was the out-of-class
7298              version; now it is the in-class version.  Therefore, we
7299              run through all specialization of `f', adding to their
7300              DECL_TI_ARGS appropriately.  In particular, they need a
7301              new set of outer arguments, corresponding to the
7302              arguments for this class instantiation.
7303
7304              The same situation can arise with something like this:
7305
7306                friend void f(int);
7307                template <class T> class C {
7308                  friend void f(T) {}
7309                };
7310
7311              when `C<int>' is instantiated.  Now, `f(int)' is defined
7312              in the class.  */
7313
7314           if (!new_friend_is_defn)
7315             /* On the other hand, if the in-class declaration does
7316                *not* provide a definition, then we don't want to alter
7317                existing definitions.  We can just leave everything
7318                alone.  */
7319             ;
7320           else
7321             {
7322               tree new_template = TI_TEMPLATE (new_friend_template_info);
7323               tree new_args = TI_ARGS (new_friend_template_info);
7324
7325               /* Overwrite whatever template info was there before, if
7326                  any, with the new template information pertaining to
7327                  the declaration.  */
7328               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7329
7330               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7331                 /* We should have called reregister_specialization in
7332                    duplicate_decls.  */
7333                 gcc_assert (retrieve_specialization (new_template,
7334                                                      new_args, 0)
7335                             == old_decl);
7336               else
7337                 {
7338                   tree t;
7339
7340                   /* Indicate that the old function template is a partial
7341                      instantiation.  */
7342                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7343                     = new_friend_result_template_info;
7344
7345                   gcc_assert (new_template
7346                               == most_general_template (new_template));
7347                   gcc_assert (new_template != old_decl);
7348
7349                   /* Reassign any specializations already in the hash table
7350                      to the new more general template, and add the
7351                      additional template args.  */
7352                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7353                        t != NULL_TREE;
7354                        t = TREE_CHAIN (t))
7355                     {
7356                       tree spec = TREE_VALUE (t);
7357                       spec_entry elt;
7358
7359                       elt.tmpl = old_decl;
7360                       elt.args = DECL_TI_ARGS (spec);
7361                       elt.spec = NULL_TREE;
7362
7363                       htab_remove_elt (decl_specializations, &elt);
7364
7365                       DECL_TI_ARGS (spec)
7366                         = add_outermost_template_args (new_args,
7367                                                        DECL_TI_ARGS (spec));
7368
7369                       register_specialization
7370                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7371
7372                     }
7373                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7374                 }
7375             }
7376
7377           /* The information from NEW_FRIEND has been merged into OLD_DECL
7378              by duplicate_decls.  */
7379           new_friend = old_decl;
7380         }
7381     }
7382   else
7383     {
7384       tree context = DECL_CONTEXT (new_friend);
7385       bool dependent_p;
7386
7387       /* In the code
7388            template <class T> class C {
7389              template <class U> friend void C1<U>::f (); // case 1
7390              friend void C2<T>::f ();                    // case 2
7391            };
7392          we only need to make sure CONTEXT is a complete type for
7393          case 2.  To distinguish between the two cases, we note that
7394          CONTEXT of case 1 remains dependent type after tsubst while
7395          this isn't true for case 2.  */
7396       ++processing_template_decl;
7397       dependent_p = dependent_type_p (context);
7398       --processing_template_decl;
7399
7400       if (!dependent_p
7401           && !complete_type_or_else (context, NULL_TREE))
7402         return error_mark_node;
7403
7404       if (COMPLETE_TYPE_P (context))
7405         {
7406           /* Check to see that the declaration is really present, and,
7407              possibly obtain an improved declaration.  */
7408           tree fn = check_classfn (context,
7409                                    new_friend, NULL_TREE);
7410
7411           if (fn)
7412             new_friend = fn;
7413         }
7414     }
7415
7416   return new_friend;
7417 }
7418
7419 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7420    template arguments, as for tsubst.
7421
7422    Returns an appropriate tsubst'd friend type or error_mark_node on
7423    failure.  */
7424
7425 static tree
7426 tsubst_friend_class (tree friend_tmpl, tree args)
7427 {
7428   tree friend_type;
7429   tree tmpl;
7430   tree context;
7431
7432   context = DECL_CONTEXT (friend_tmpl);
7433
7434   if (context)
7435     {
7436       if (TREE_CODE (context) == NAMESPACE_DECL)
7437         push_nested_namespace (context);
7438       else
7439         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7440     }
7441
7442   /* Look for a class template declaration.  We look for hidden names
7443      because two friend declarations of the same template are the
7444      same.  For example, in:
7445
7446        struct A { 
7447          template <typename> friend class F;
7448        };
7449        template <typename> struct B { 
7450          template <typename> friend class F;
7451        };
7452
7453      both F templates are the same.  */
7454   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7455                            /*block_p=*/true, 0, 
7456                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7457
7458   /* But, if we don't find one, it might be because we're in a
7459      situation like this:
7460
7461        template <class T>
7462        struct S {
7463          template <class U>
7464          friend struct S;
7465        };
7466
7467      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7468      for `S<int>', not the TEMPLATE_DECL.  */
7469   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7470     {
7471       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7472       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7473     }
7474
7475   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7476     {
7477       /* The friend template has already been declared.  Just
7478          check to see that the declarations match, and install any new
7479          default parameters.  We must tsubst the default parameters,
7480          of course.  We only need the innermost template parameters
7481          because that is all that redeclare_class_template will look
7482          at.  */
7483       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7484           > TMPL_ARGS_DEPTH (args))
7485         {
7486           tree parms;
7487           location_t saved_input_location;
7488           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7489                                          args, tf_warning_or_error);
7490
7491           saved_input_location = input_location;
7492           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7493           redeclare_class_template (TREE_TYPE (tmpl), parms);
7494           input_location = saved_input_location;
7495           
7496         }
7497
7498       friend_type = TREE_TYPE (tmpl);
7499     }
7500   else
7501     {
7502       /* The friend template has not already been declared.  In this
7503          case, the instantiation of the template class will cause the
7504          injection of this template into the global scope.  */
7505       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7506       if (tmpl == error_mark_node)
7507         return error_mark_node;
7508
7509       /* The new TMPL is not an instantiation of anything, so we
7510          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7511          the new type because that is supposed to be the corresponding
7512          template decl, i.e., TMPL.  */
7513       DECL_USE_TEMPLATE (tmpl) = 0;
7514       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7515       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7516       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7517         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7518
7519       /* Inject this template into the global scope.  */
7520       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7521     }
7522
7523   if (context)
7524     {
7525       if (TREE_CODE (context) == NAMESPACE_DECL)
7526         pop_nested_namespace (context);
7527       else
7528         pop_nested_class ();
7529     }
7530
7531   return friend_type;
7532 }
7533
7534 /* Returns zero if TYPE cannot be completed later due to circularity.
7535    Otherwise returns one.  */
7536
7537 static int
7538 can_complete_type_without_circularity (tree type)
7539 {
7540   if (type == NULL_TREE || type == error_mark_node)
7541     return 0;
7542   else if (COMPLETE_TYPE_P (type))
7543     return 1;
7544   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7545     return can_complete_type_without_circularity (TREE_TYPE (type));
7546   else if (CLASS_TYPE_P (type)
7547            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7548     return 0;
7549   else
7550     return 1;
7551 }
7552
7553 /* Apply any attributes which had to be deferred until instantiation
7554    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7555    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7556
7557 static void
7558 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7559                                 tree args, tsubst_flags_t complain, tree in_decl)
7560 {
7561   tree last_dep = NULL_TREE;
7562   tree t;
7563   tree *p;
7564
7565   for (t = attributes; t; t = TREE_CHAIN (t))
7566     if (ATTR_IS_DEPENDENT (t))
7567       {
7568         last_dep = t;
7569         attributes = copy_list (attributes);
7570         break;
7571       }
7572
7573   if (DECL_P (*decl_p))
7574     {
7575       if (TREE_TYPE (*decl_p) == error_mark_node)
7576         return;
7577       p = &DECL_ATTRIBUTES (*decl_p);
7578     }
7579   else
7580     p = &TYPE_ATTRIBUTES (*decl_p);
7581
7582   if (last_dep)
7583     {
7584       tree late_attrs = NULL_TREE;
7585       tree *q = &late_attrs;
7586
7587       for (*p = attributes; *p; )
7588         {
7589           t = *p;
7590           if (ATTR_IS_DEPENDENT (t))
7591             {
7592               *p = TREE_CHAIN (t);
7593               TREE_CHAIN (t) = NULL_TREE;
7594               /* If the first attribute argument is an identifier, don't
7595                  pass it through tsubst.  Attributes like mode, format,
7596                  cleanup and several target specific attributes expect it
7597                  unmodified.  */
7598               if (TREE_VALUE (t)
7599                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7600                   && TREE_VALUE (TREE_VALUE (t))
7601                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7602                       == IDENTIFIER_NODE))
7603                 {
7604                   tree chain
7605                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7606                                    in_decl,
7607                                    /*integral_constant_expression_p=*/false);
7608                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7609                     TREE_VALUE (t)
7610                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7611                                    chain);
7612                 }
7613               else
7614                 TREE_VALUE (t)
7615                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7616                                  /*integral_constant_expression_p=*/false);
7617               *q = t;
7618               q = &TREE_CHAIN (t);
7619             }
7620           else
7621             p = &TREE_CHAIN (t);
7622         }
7623
7624       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7625     }
7626 }
7627
7628 /* Perform (or defer) access check for typedefs that were referenced
7629    from within the template TMPL code.
7630    This is a subroutine of instantiate_template and instantiate_class_template.
7631    TMPL is the template to consider and TARGS is the list of arguments of
7632    that template.  */
7633
7634 static void
7635 perform_typedefs_access_check (tree tmpl, tree targs)
7636 {
7637   location_t saved_location;
7638   int i;
7639   qualified_typedef_usage_t *iter;
7640
7641   if (!tmpl
7642       || (!CLASS_TYPE_P (tmpl)
7643           && TREE_CODE (tmpl) != FUNCTION_DECL))
7644     return;
7645
7646   saved_location = input_location;
7647   for (i = 0;
7648        VEC_iterate (qualified_typedef_usage_t,
7649                     get_types_needing_access_check (tmpl),
7650                     i, iter);
7651         ++i)
7652     {
7653       tree type_decl = iter->typedef_decl;
7654       tree type_scope = iter->context;
7655
7656       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7657         continue;
7658
7659       if (uses_template_parms (type_decl))
7660         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7661       if (uses_template_parms (type_scope))
7662         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7663
7664       /* Make access check error messages point to the location
7665          of the use of the typedef.  */
7666       input_location = iter->locus;
7667       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7668                                      type_decl, type_decl);
7669     }
7670     input_location = saved_location;
7671 }
7672
7673 tree
7674 instantiate_class_template (tree type)
7675 {
7676   tree templ, args, pattern, t, member;
7677   tree typedecl;
7678   tree pbinfo;
7679   tree base_list;
7680   unsigned int saved_maximum_field_alignment;
7681
7682   if (type == error_mark_node)
7683     return error_mark_node;
7684
7685   if (TYPE_BEING_DEFINED (type)
7686       || COMPLETE_TYPE_P (type)
7687       || uses_template_parms (type))
7688     return type;
7689
7690   /* Figure out which template is being instantiated.  */
7691   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7692   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7693
7694   /* Determine what specialization of the original template to
7695      instantiate.  */
7696   t = most_specialized_class (type, templ);
7697   if (t == error_mark_node)
7698     {
7699       TYPE_BEING_DEFINED (type) = 1;
7700       return error_mark_node;
7701     }
7702   else if (t)
7703     {
7704       /* This TYPE is actually an instantiation of a partial
7705          specialization.  We replace the innermost set of ARGS with
7706          the arguments appropriate for substitution.  For example,
7707          given:
7708
7709            template <class T> struct S {};
7710            template <class T> struct S<T*> {};
7711
7712          and supposing that we are instantiating S<int*>, ARGS will
7713          presently be {int*} -- but we need {int}.  */
7714       pattern = TREE_TYPE (t);
7715       args = TREE_PURPOSE (t);
7716     }
7717   else
7718     {
7719       pattern = TREE_TYPE (templ);
7720       args = CLASSTYPE_TI_ARGS (type);
7721     }
7722
7723   /* If the template we're instantiating is incomplete, then clearly
7724      there's nothing we can do.  */
7725   if (!COMPLETE_TYPE_P (pattern))
7726     return type;
7727
7728   /* If we've recursively instantiated too many templates, stop.  */
7729   if (! push_tinst_level (type))
7730     return type;
7731
7732   /* Now we're really doing the instantiation.  Mark the type as in
7733      the process of being defined.  */
7734   TYPE_BEING_DEFINED (type) = 1;
7735
7736   /* We may be in the middle of deferred access check.  Disable
7737      it now.  */
7738   push_deferring_access_checks (dk_no_deferred);
7739
7740   push_to_top_level ();
7741   /* Use #pragma pack from the template context.  */
7742   saved_maximum_field_alignment = maximum_field_alignment;
7743   maximum_field_alignment = TYPE_PRECISION (pattern);
7744
7745   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7746
7747   /* Set the input location to the most specialized template definition.
7748      This is needed if tsubsting causes an error.  */
7749   typedecl = TYPE_MAIN_DECL (pattern);
7750   input_location = DECL_SOURCE_LOCATION (typedecl);
7751
7752   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7753   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7754   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7755   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7756   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7757   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7758   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7759   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7760   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7761   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7762   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7763   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7764   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7765   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7766   if (ANON_AGGR_TYPE_P (pattern))
7767     SET_ANON_AGGR_TYPE_P (type);
7768   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7769     {
7770       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7771       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7772     }
7773
7774   pbinfo = TYPE_BINFO (pattern);
7775
7776   /* We should never instantiate a nested class before its enclosing
7777      class; we need to look up the nested class by name before we can
7778      instantiate it, and that lookup should instantiate the enclosing
7779      class.  */
7780   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7781               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7782               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7783
7784   base_list = NULL_TREE;
7785   if (BINFO_N_BASE_BINFOS (pbinfo))
7786     {
7787       tree pbase_binfo;
7788       tree context = TYPE_CONTEXT (type);
7789       tree pushed_scope;
7790       int i;
7791
7792       /* We must enter the scope containing the type, as that is where
7793          the accessibility of types named in dependent bases are
7794          looked up from.  */
7795       pushed_scope = push_scope (context ? context : global_namespace);
7796
7797       /* Substitute into each of the bases to determine the actual
7798          basetypes.  */
7799       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7800         {
7801           tree base;
7802           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7803           tree expanded_bases = NULL_TREE;
7804           int idx, len = 1;
7805
7806           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7807             {
7808               expanded_bases = 
7809                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7810                                        args, tf_error, NULL_TREE);
7811               if (expanded_bases == error_mark_node)
7812                 continue;
7813
7814               len = TREE_VEC_LENGTH (expanded_bases);
7815             }
7816
7817           for (idx = 0; idx < len; idx++)
7818             {
7819               if (expanded_bases)
7820                 /* Extract the already-expanded base class.  */
7821                 base = TREE_VEC_ELT (expanded_bases, idx);
7822               else
7823                 /* Substitute to figure out the base class.  */
7824                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7825                                NULL_TREE);
7826
7827               if (base == error_mark_node)
7828                 continue;
7829
7830               base_list = tree_cons (access, base, base_list);
7831               if (BINFO_VIRTUAL_P (pbase_binfo))
7832                 TREE_TYPE (base_list) = integer_type_node;
7833             }
7834         }
7835
7836       /* The list is now in reverse order; correct that.  */
7837       base_list = nreverse (base_list);
7838
7839       if (pushed_scope)
7840         pop_scope (pushed_scope);
7841     }
7842   /* Now call xref_basetypes to set up all the base-class
7843      information.  */
7844   xref_basetypes (type, base_list);
7845
7846   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7847                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7848                                   args, tf_error, NULL_TREE);
7849
7850   /* Now that our base classes are set up, enter the scope of the
7851      class, so that name lookups into base classes, etc. will work
7852      correctly.  This is precisely analogous to what we do in
7853      begin_class_definition when defining an ordinary non-template
7854      class, except we also need to push the enclosing classes.  */
7855   push_nested_class (type);
7856
7857   /* Now members are processed in the order of declaration.  */
7858   for (member = CLASSTYPE_DECL_LIST (pattern);
7859        member; member = TREE_CHAIN (member))
7860     {
7861       tree t = TREE_VALUE (member);
7862
7863       if (TREE_PURPOSE (member))
7864         {
7865           if (TYPE_P (t))
7866             {
7867               /* Build new CLASSTYPE_NESTED_UTDS.  */
7868
7869               tree newtag;
7870               bool class_template_p;
7871
7872               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7873                                   && TYPE_LANG_SPECIFIC (t)
7874                                   && CLASSTYPE_IS_TEMPLATE (t));
7875               /* If the member is a class template, then -- even after
7876                  substitution -- there may be dependent types in the
7877                  template argument list for the class.  We increment
7878                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7879                  that function will assume that no types are dependent
7880                  when outside of a template.  */
7881               if (class_template_p)
7882                 ++processing_template_decl;
7883               newtag = tsubst (t, args, tf_error, NULL_TREE);
7884               if (class_template_p)
7885                 --processing_template_decl;
7886               if (newtag == error_mark_node)
7887                 continue;
7888
7889               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7890                 {
7891                   tree name = TYPE_IDENTIFIER (t);
7892
7893                   if (class_template_p)
7894                     /* Unfortunately, lookup_template_class sets
7895                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7896                        instantiation (i.e., for the type of a member
7897                        template class nested within a template class.)
7898                        This behavior is required for
7899                        maybe_process_partial_specialization to work
7900                        correctly, but is not accurate in this case;
7901                        the TAG is not an instantiation of anything.
7902                        (The corresponding TEMPLATE_DECL is an
7903                        instantiation, but the TYPE is not.) */
7904                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7905
7906                   /* Now, we call pushtag to put this NEWTAG into the scope of
7907                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7908                      pushtag calling push_template_decl.  We don't have to do
7909                      this for enums because it will already have been done in
7910                      tsubst_enum.  */
7911                   if (name)
7912                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7913                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7914                 }
7915             }
7916           else if (TREE_CODE (t) == FUNCTION_DECL
7917                    || DECL_FUNCTION_TEMPLATE_P (t))
7918             {
7919               /* Build new TYPE_METHODS.  */
7920               tree r;
7921
7922               if (TREE_CODE (t) == TEMPLATE_DECL)
7923                 ++processing_template_decl;
7924               r = tsubst (t, args, tf_error, NULL_TREE);
7925               if (TREE_CODE (t) == TEMPLATE_DECL)
7926                 --processing_template_decl;
7927               set_current_access_from_decl (r);
7928               finish_member_declaration (r);
7929             }
7930           else
7931             {
7932               /* Build new TYPE_FIELDS.  */
7933               if (TREE_CODE (t) == STATIC_ASSERT)
7934                 {
7935                   tree condition = 
7936                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7937                                  tf_warning_or_error, NULL_TREE,
7938                                  /*integral_constant_expression_p=*/true);
7939                   finish_static_assert (condition,
7940                                         STATIC_ASSERT_MESSAGE (t), 
7941                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7942                                         /*member_p=*/true);
7943                 }
7944               else if (TREE_CODE (t) != CONST_DECL)
7945                 {
7946                   tree r;
7947
7948                   /* The file and line for this declaration, to
7949                      assist in error message reporting.  Since we
7950                      called push_tinst_level above, we don't need to
7951                      restore these.  */
7952                   input_location = DECL_SOURCE_LOCATION (t);
7953
7954                   if (TREE_CODE (t) == TEMPLATE_DECL)
7955                     ++processing_template_decl;
7956                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7957                   if (TREE_CODE (t) == TEMPLATE_DECL)
7958                     --processing_template_decl;
7959                   if (TREE_CODE (r) == VAR_DECL)
7960                     {
7961                       /* In [temp.inst]:
7962
7963                            [t]he initialization (and any associated
7964                            side-effects) of a static data member does
7965                            not occur unless the static data member is
7966                            itself used in a way that requires the
7967                            definition of the static data member to
7968                            exist.
7969
7970                          Therefore, we do not substitute into the
7971                          initialized for the static data member here.  */
7972                       finish_static_data_member_decl
7973                         (r,
7974                          /*init=*/NULL_TREE,
7975                          /*init_const_expr_p=*/false,
7976                          /*asmspec_tree=*/NULL_TREE,
7977                          /*flags=*/0);
7978                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7979                         check_static_variable_definition (r, TREE_TYPE (r));
7980                     }
7981                   else if (TREE_CODE (r) == FIELD_DECL)
7982                     {
7983                       /* Determine whether R has a valid type and can be
7984                          completed later.  If R is invalid, then it is
7985                          replaced by error_mark_node so that it will not be
7986                          added to TYPE_FIELDS.  */
7987                       tree rtype = TREE_TYPE (r);
7988                       if (can_complete_type_without_circularity (rtype))
7989                         complete_type (rtype);
7990
7991                       if (!COMPLETE_TYPE_P (rtype))
7992                         {
7993                           cxx_incomplete_type_error (r, rtype);
7994                           r = error_mark_node;
7995                         }
7996                     }
7997
7998                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7999                      such a thing will already have been added to the field
8000                      list by tsubst_enum in finish_member_declaration in the
8001                      CLASSTYPE_NESTED_UTDS case above.  */
8002                   if (!(TREE_CODE (r) == TYPE_DECL
8003                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8004                         && DECL_ARTIFICIAL (r)))
8005                     {
8006                       set_current_access_from_decl (r);
8007                       finish_member_declaration (r);
8008                     }
8009                 }
8010             }
8011         }
8012       else
8013         {
8014           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8015             {
8016               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8017
8018               tree friend_type = t;
8019               bool adjust_processing_template_decl = false;
8020
8021               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8022                 {
8023                   /* template <class T> friend class C;  */
8024                   friend_type = tsubst_friend_class (friend_type, args);
8025                   adjust_processing_template_decl = true;
8026                 }
8027               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8028                 {
8029                   /* template <class T> friend class C::D;  */
8030                   friend_type = tsubst (friend_type, args,
8031                                         tf_warning_or_error, NULL_TREE);
8032                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8033                     friend_type = TREE_TYPE (friend_type);
8034                   adjust_processing_template_decl = true;
8035                 }
8036               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8037                 {
8038                   /* This could be either
8039
8040                        friend class T::C;
8041
8042                      when dependent_type_p is false or
8043
8044                        template <class U> friend class T::C;
8045
8046                      otherwise.  */
8047                   friend_type = tsubst (friend_type, args,
8048                                         tf_warning_or_error, NULL_TREE);
8049                   /* Bump processing_template_decl for correct
8050                      dependent_type_p calculation.  */
8051                   ++processing_template_decl;
8052                   if (dependent_type_p (friend_type))
8053                     adjust_processing_template_decl = true;
8054                   --processing_template_decl;
8055                 }
8056               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8057                        && hidden_name_p (TYPE_NAME (friend_type)))
8058                 {
8059                   /* friend class C;
8060
8061                      where C hasn't been declared yet.  Let's lookup name
8062                      from namespace scope directly, bypassing any name that
8063                      come from dependent base class.  */
8064                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8065
8066                   /* The call to xref_tag_from_type does injection for friend
8067                      classes.  */
8068                   push_nested_namespace (ns);
8069                   friend_type =
8070                     xref_tag_from_type (friend_type, NULL_TREE,
8071                                         /*tag_scope=*/ts_current);
8072                   pop_nested_namespace (ns);
8073                 }
8074               else if (uses_template_parms (friend_type))
8075                 /* friend class C<T>;  */
8076                 friend_type = tsubst (friend_type, args,
8077                                       tf_warning_or_error, NULL_TREE);
8078               /* Otherwise it's
8079
8080                    friend class C;
8081
8082                  where C is already declared or
8083
8084                    friend class C<int>;
8085
8086                  We don't have to do anything in these cases.  */
8087
8088               if (adjust_processing_template_decl)
8089                 /* Trick make_friend_class into realizing that the friend
8090                    we're adding is a template, not an ordinary class.  It's
8091                    important that we use make_friend_class since it will
8092                    perform some error-checking and output cross-reference
8093                    information.  */
8094                 ++processing_template_decl;
8095
8096               if (friend_type != error_mark_node)
8097                 make_friend_class (type, friend_type, /*complain=*/false);
8098
8099               if (adjust_processing_template_decl)
8100                 --processing_template_decl;
8101             }
8102           else
8103             {
8104               /* Build new DECL_FRIENDLIST.  */
8105               tree r;
8106
8107               /* The file and line for this declaration, to
8108                  assist in error message reporting.  Since we
8109                  called push_tinst_level above, we don't need to
8110                  restore these.  */
8111               input_location = DECL_SOURCE_LOCATION (t);
8112
8113               if (TREE_CODE (t) == TEMPLATE_DECL)
8114                 {
8115                   ++processing_template_decl;
8116                   push_deferring_access_checks (dk_no_check);
8117                 }
8118
8119               r = tsubst_friend_function (t, args);
8120               add_friend (type, r, /*complain=*/false);
8121               if (TREE_CODE (t) == TEMPLATE_DECL)
8122                 {
8123                   pop_deferring_access_checks ();
8124                   --processing_template_decl;
8125                 }
8126             }
8127         }
8128     }
8129
8130   /* Set the file and line number information to whatever is given for
8131      the class itself.  This puts error messages involving generated
8132      implicit functions at a predictable point, and the same point
8133      that would be used for non-template classes.  */
8134   input_location = DECL_SOURCE_LOCATION (typedecl);
8135
8136   unreverse_member_declarations (type);
8137   finish_struct_1 (type);
8138   TYPE_BEING_DEFINED (type) = 0;
8139
8140   /* Now that the class is complete, instantiate default arguments for
8141      any member functions.  We don't do this earlier because the
8142      default arguments may reference members of the class.  */
8143   if (!PRIMARY_TEMPLATE_P (templ))
8144     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8145       if (TREE_CODE (t) == FUNCTION_DECL
8146           /* Implicitly generated member functions will not have template
8147              information; they are not instantiations, but instead are
8148              created "fresh" for each instantiation.  */
8149           && DECL_TEMPLATE_INFO (t))
8150         tsubst_default_arguments (t);
8151
8152   /* Some typedefs referenced from within the template code need to be access
8153      checked at template instantiation time, i.e now. These types were
8154      added to the template at parsing time. Let's get those and perform
8155      the access checks then.  */
8156   perform_typedefs_access_check (pattern, args);
8157   perform_deferred_access_checks ();
8158   pop_nested_class ();
8159   maximum_field_alignment = saved_maximum_field_alignment;
8160   pop_from_top_level ();
8161   pop_deferring_access_checks ();
8162   pop_tinst_level ();
8163
8164   /* The vtable for a template class can be emitted in any translation
8165      unit in which the class is instantiated.  When there is no key
8166      method, however, finish_struct_1 will already have added TYPE to
8167      the keyed_classes list.  */
8168   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8169     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8170
8171   return type;
8172 }
8173
8174 static tree
8175 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8176 {
8177   tree r;
8178
8179   if (!t)
8180     r = t;
8181   else if (TYPE_P (t))
8182     r = tsubst (t, args, complain, in_decl);
8183   else
8184     {
8185       r = tsubst_expr (t, args, complain, in_decl,
8186                        /*integral_constant_expression_p=*/true);
8187       r = fold_non_dependent_expr (r);
8188     }
8189   return r;
8190 }
8191
8192 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8193    NONTYPE_ARGUMENT_PACK.  */
8194
8195 static tree
8196 make_fnparm_pack (tree spec_parm)
8197 {
8198   /* Collect all of the extra "packed" parameters into an
8199      argument pack.  */
8200   tree parmvec;
8201   tree parmtypevec;
8202   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8203   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8204   int i, len = list_length (spec_parm);
8205
8206   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8207   parmvec = make_tree_vec (len);
8208   parmtypevec = make_tree_vec (len);
8209   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8210     {
8211       TREE_VEC_ELT (parmvec, i) = spec_parm;
8212       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8213     }
8214
8215   /* Build the argument packs.  */
8216   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8217   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8218   TREE_TYPE (argpack) = argtypepack;
8219
8220   return argpack;
8221 }        
8222
8223 /* Substitute ARGS into T, which is an pack expansion
8224    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8225    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8226    (if only a partial substitution could be performed) or
8227    ERROR_MARK_NODE if there was an error.  */
8228 tree
8229 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8230                        tree in_decl)
8231 {
8232   tree pattern;
8233   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8234   int i, len = -1;
8235   tree result;
8236   int incomplete = 0;
8237   bool very_local_specializations = false;
8238
8239   gcc_assert (PACK_EXPANSION_P (t));
8240   pattern = PACK_EXPANSION_PATTERN (t);
8241
8242   /* Determine the argument packs that will instantiate the parameter
8243      packs used in the expansion expression. While we're at it,
8244      compute the number of arguments to be expanded and make sure it
8245      is consistent.  */
8246   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8247        pack = TREE_CHAIN (pack))
8248     {
8249       tree parm_pack = TREE_VALUE (pack);
8250       tree arg_pack = NULL_TREE;
8251       tree orig_arg = NULL_TREE;
8252
8253       if (TREE_CODE (parm_pack) == PARM_DECL)
8254         {
8255           arg_pack = retrieve_local_specialization (parm_pack);
8256           if (arg_pack == NULL_TREE)
8257             {
8258               /* This can happen for a parameter name used later in a function
8259                  declaration (such as in a late-specified return type).  Just
8260                  make a dummy decl, since it's only used for its type.  */
8261               gcc_assert (cp_unevaluated_operand != 0);
8262               arg_pack = tsubst_decl (parm_pack, args, complain);
8263               arg_pack = make_fnparm_pack (arg_pack);
8264             }
8265         }
8266       else
8267         {
8268           int level, idx, levels;
8269           template_parm_level_and_index (parm_pack, &level, &idx);
8270
8271           levels = TMPL_ARGS_DEPTH (args);
8272           if (level <= levels)
8273             arg_pack = TMPL_ARG (args, level, idx);
8274         }
8275
8276       orig_arg = arg_pack;
8277       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8278         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8279       
8280       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8281         /* This can only happen if we forget to expand an argument
8282            pack somewhere else. Just return an error, silently.  */
8283         {
8284           result = make_tree_vec (1);
8285           TREE_VEC_ELT (result, 0) = error_mark_node;
8286           return result;
8287         }
8288
8289       if (arg_pack
8290           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8291           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8292         {
8293           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8294           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8295           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8296               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8297             /* The argument pack that the parameter maps to is just an
8298                expansion of the parameter itself, such as one would
8299                find in the implicit typedef of a class inside the
8300                class itself.  Consider this parameter "unsubstituted",
8301                so that we will maintain the outer pack expansion.  */
8302             arg_pack = NULL_TREE;
8303         }
8304           
8305       if (arg_pack)
8306         {
8307           int my_len = 
8308             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8309
8310           /* It's all-or-nothing with incomplete argument packs.  */
8311           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8312             return error_mark_node;
8313           
8314           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8315             incomplete = 1;
8316
8317           if (len < 0)
8318             len = my_len;
8319           else if (len != my_len)
8320             {
8321               if (incomplete)
8322                 /* We got explicit args for some packs but not others;
8323                    do nothing now and try again after deduction.  */
8324                 return t;
8325               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8326                 error ("mismatched argument pack lengths while expanding "
8327                        "%<%T%>",
8328                        pattern);
8329               else
8330                 error ("mismatched argument pack lengths while expanding "
8331                        "%<%E%>",
8332                        pattern);
8333               return error_mark_node;
8334             }
8335
8336           /* Keep track of the parameter packs and their corresponding
8337              argument packs.  */
8338           packs = tree_cons (parm_pack, arg_pack, packs);
8339           TREE_TYPE (packs) = orig_arg;
8340         }
8341       else
8342         /* We can't substitute for this parameter pack.  */
8343         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8344                                          TREE_VALUE (pack),
8345                                          unsubstituted_packs);
8346     }
8347
8348   /* We cannot expand this expansion expression, because we don't have
8349      all of the argument packs we need. Substitute into the pattern
8350      and return a PACK_EXPANSION_*. The caller will need to deal with
8351      that.  */
8352   if (unsubstituted_packs)
8353     {
8354       tree new_pat;
8355       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8356         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8357                                /*integral_constant_expression_p=*/false);
8358       else
8359         new_pat = tsubst (pattern, args, complain, in_decl);
8360       return make_pack_expansion (new_pat);
8361     }
8362
8363   /* We could not find any argument packs that work.  */
8364   if (len < 0)
8365     return error_mark_node;
8366
8367   if (!local_specializations)
8368     {
8369       /* We're in a late-specified return type, so we don't have a local
8370          specializations table.  Create one for doing this expansion.  */
8371       very_local_specializations = true;
8372       local_specializations = htab_create (37,
8373                                            hash_local_specialization,
8374                                            eq_local_specializations,
8375                                            NULL);
8376     }
8377
8378   /* For each argument in each argument pack, substitute into the
8379      pattern.  */
8380   result = make_tree_vec (len + incomplete);
8381   for (i = 0; i < len + incomplete; ++i)
8382     {
8383       /* For parameter pack, change the substitution of the parameter
8384          pack to the ith argument in its argument pack, then expand
8385          the pattern.  */
8386       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8387         {
8388           tree parm = TREE_PURPOSE (pack);
8389
8390           if (TREE_CODE (parm) == PARM_DECL)
8391             {
8392               /* Select the Ith argument from the pack.  */
8393               tree arg = make_node (ARGUMENT_PACK_SELECT);
8394               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8395               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8396               mark_used (parm);
8397               register_local_specialization (arg, parm);
8398             }
8399           else
8400             {
8401               tree value = parm;
8402               int idx, level;
8403               template_parm_level_and_index (parm, &level, &idx);
8404               
8405               if (i < len) 
8406                 {
8407                   /* Select the Ith argument from the pack. */
8408                   value = make_node (ARGUMENT_PACK_SELECT);
8409                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8410                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8411                 }
8412
8413               /* Update the corresponding argument.  */
8414               TMPL_ARG (args, level, idx) = value;
8415             }
8416         }
8417
8418       /* Substitute into the PATTERN with the altered arguments.  */
8419       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8420         TREE_VEC_ELT (result, i) = 
8421           tsubst_expr (pattern, args, complain, in_decl,
8422                        /*integral_constant_expression_p=*/false);
8423       else
8424         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8425
8426       if (i == len)
8427         /* When we have incomplete argument packs, the last "expanded"
8428            result is itself a pack expansion, which allows us
8429            to deduce more arguments.  */
8430         TREE_VEC_ELT (result, i) = 
8431           make_pack_expansion (TREE_VEC_ELT (result, i));
8432
8433       if (TREE_VEC_ELT (result, i) == error_mark_node)
8434         {
8435           result = error_mark_node;
8436           break;
8437         }
8438     }
8439
8440   /* Update ARGS to restore the substitution from parameter packs to
8441      their argument packs.  */
8442   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8443     {
8444       tree parm = TREE_PURPOSE (pack);
8445
8446       if (TREE_CODE (parm) == PARM_DECL)
8447         register_local_specialization (TREE_TYPE (pack), parm);
8448       else
8449         {
8450           int idx, level;
8451           template_parm_level_and_index (parm, &level, &idx);
8452           
8453           /* Update the corresponding argument.  */
8454           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8455             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8456               TREE_TYPE (pack);
8457           else
8458             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8459         }
8460     }
8461
8462   if (very_local_specializations)
8463     {
8464       htab_delete (local_specializations);
8465       local_specializations = NULL;
8466     }
8467   
8468   return result;
8469 }
8470
8471 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8472    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8473    parameter packs; all parms generated from a function parameter pack will
8474    have the same DECL_PARM_INDEX.  */
8475
8476 tree
8477 get_pattern_parm (tree parm, tree tmpl)
8478 {
8479   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8480   tree patparm;
8481
8482   if (DECL_ARTIFICIAL (parm))
8483     {
8484       for (patparm = DECL_ARGUMENTS (pattern);
8485            patparm; patparm = TREE_CHAIN (patparm))
8486         if (DECL_ARTIFICIAL (patparm)
8487             && DECL_NAME (parm) == DECL_NAME (patparm))
8488           break;
8489     }
8490   else
8491     {
8492       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8493       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8494       gcc_assert (DECL_PARM_INDEX (patparm)
8495                   == DECL_PARM_INDEX (parm));
8496     }
8497
8498   return patparm;
8499 }
8500
8501 /* Substitute ARGS into the vector or list of template arguments T.  */
8502
8503 static tree
8504 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8505 {
8506   tree orig_t = t;
8507   int len = TREE_VEC_LENGTH (t);
8508   int need_new = 0, i, expanded_len_adjust = 0, out;
8509   tree *elts = (tree *) alloca (len * sizeof (tree));
8510
8511   for (i = 0; i < len; i++)
8512     {
8513       tree orig_arg = TREE_VEC_ELT (t, i);
8514       tree new_arg;
8515
8516       if (TREE_CODE (orig_arg) == TREE_VEC)
8517         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8518       else if (PACK_EXPANSION_P (orig_arg))
8519         {
8520           /* Substitute into an expansion expression.  */
8521           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8522
8523           if (TREE_CODE (new_arg) == TREE_VEC)
8524             /* Add to the expanded length adjustment the number of
8525                expanded arguments. We subtract one from this
8526                measurement, because the argument pack expression
8527                itself is already counted as 1 in
8528                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8529                the argument pack is empty.  */
8530             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8531         }
8532       else if (ARGUMENT_PACK_P (orig_arg))
8533         {
8534           /* Substitute into each of the arguments.  */
8535           new_arg = TYPE_P (orig_arg)
8536             ? cxx_make_type (TREE_CODE (orig_arg))
8537             : make_node (TREE_CODE (orig_arg));
8538           
8539           SET_ARGUMENT_PACK_ARGS (
8540             new_arg,
8541             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8542                                   args, complain, in_decl));
8543
8544           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8545             new_arg = error_mark_node;
8546
8547           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8548             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8549                                           complain, in_decl);
8550             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8551
8552             if (TREE_TYPE (new_arg) == error_mark_node)
8553               new_arg = error_mark_node;
8554           }
8555         }
8556       else
8557         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8558
8559       if (new_arg == error_mark_node)
8560         return error_mark_node;
8561
8562       elts[i] = new_arg;
8563       if (new_arg != orig_arg)
8564         need_new = 1;
8565     }
8566
8567   if (!need_new)
8568     return t;
8569
8570   /* Make space for the expanded arguments coming from template
8571      argument packs.  */
8572   t = make_tree_vec (len + expanded_len_adjust);
8573   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8574      arguments for a member template.
8575      In that case each TREE_VEC in ORIG_T represents a level of template
8576      arguments, and ORIG_T won't carry any non defaulted argument count.
8577      It will rather be the nested TREE_VECs that will carry one.
8578      In other words, ORIG_T carries a non defaulted argument count only
8579      if it doesn't contain any nested TREE_VEC.  */
8580   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8581     {
8582       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8583       count += expanded_len_adjust;
8584       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8585     }
8586   for (i = 0, out = 0; i < len; i++)
8587     {
8588       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8589            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8590           && TREE_CODE (elts[i]) == TREE_VEC)
8591         {
8592           int idx;
8593
8594           /* Now expand the template argument pack "in place".  */
8595           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8596             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8597         }
8598       else
8599         {
8600           TREE_VEC_ELT (t, out) = elts[i];
8601           out++;
8602         }
8603     }
8604
8605   return t;
8606 }
8607
8608 /* Return the result of substituting ARGS into the template parameters
8609    given by PARMS.  If there are m levels of ARGS and m + n levels of
8610    PARMS, then the result will contain n levels of PARMS.  For
8611    example, if PARMS is `template <class T> template <class U>
8612    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8613    result will be `template <int*, double, class V>'.  */
8614
8615 static tree
8616 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8617 {
8618   tree r = NULL_TREE;
8619   tree* new_parms;
8620
8621   /* When substituting into a template, we must set
8622      PROCESSING_TEMPLATE_DECL as the template parameters may be
8623      dependent if they are based on one-another, and the dependency
8624      predicates are short-circuit outside of templates.  */
8625   ++processing_template_decl;
8626
8627   for (new_parms = &r;
8628        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8629        new_parms = &(TREE_CHAIN (*new_parms)),
8630          parms = TREE_CHAIN (parms))
8631     {
8632       tree new_vec =
8633         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8634       int i;
8635
8636       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8637         {
8638           tree tuple;
8639           tree default_value;
8640           tree parm_decl;
8641
8642           if (parms == error_mark_node)
8643             continue;
8644
8645           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8646
8647           if (tuple == error_mark_node)
8648             continue;
8649
8650           default_value = TREE_PURPOSE (tuple);
8651           parm_decl = TREE_VALUE (tuple);
8652
8653           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8654           if (TREE_CODE (parm_decl) == PARM_DECL
8655               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8656             parm_decl = error_mark_node;
8657           default_value = tsubst_template_arg (default_value, args,
8658                                                complain, NULL_TREE);
8659
8660           tuple = build_tree_list (default_value, parm_decl);
8661           TREE_VEC_ELT (new_vec, i) = tuple;
8662         }
8663
8664       *new_parms =
8665         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8666                              - TMPL_ARGS_DEPTH (args)),
8667                    new_vec, NULL_TREE);
8668     }
8669
8670   --processing_template_decl;
8671
8672   return r;
8673 }
8674
8675 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8676    type T.  If T is not an aggregate or enumeration type, it is
8677    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8678    ENTERING_SCOPE is nonzero, T is the context for a template which
8679    we are presently tsubst'ing.  Return the substituted value.  */
8680
8681 static tree
8682 tsubst_aggr_type (tree t,
8683                   tree args,
8684                   tsubst_flags_t complain,
8685                   tree in_decl,
8686                   int entering_scope)
8687 {
8688   if (t == NULL_TREE)
8689     return NULL_TREE;
8690
8691   switch (TREE_CODE (t))
8692     {
8693     case RECORD_TYPE:
8694       if (TYPE_PTRMEMFUNC_P (t))
8695         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8696
8697       /* Else fall through.  */
8698     case ENUMERAL_TYPE:
8699     case UNION_TYPE:
8700       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8701         {
8702           tree argvec;
8703           tree context;
8704           tree r;
8705           int saved_unevaluated_operand;
8706           int saved_inhibit_evaluation_warnings;
8707
8708           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8709           saved_unevaluated_operand = cp_unevaluated_operand;
8710           cp_unevaluated_operand = 0;
8711           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8712           c_inhibit_evaluation_warnings = 0;
8713
8714           /* First, determine the context for the type we are looking
8715              up.  */
8716           context = TYPE_CONTEXT (t);
8717           if (context)
8718             {
8719               context = tsubst_aggr_type (context, args, complain,
8720                                           in_decl, /*entering_scope=*/1);
8721               /* If context is a nested class inside a class template,
8722                  it may still need to be instantiated (c++/33959).  */
8723               if (TYPE_P (context))
8724                 context = complete_type (context);
8725             }
8726
8727           /* Then, figure out what arguments are appropriate for the
8728              type we are trying to find.  For example, given:
8729
8730                template <class T> struct S;
8731                template <class T, class U> void f(T, U) { S<U> su; }
8732
8733              and supposing that we are instantiating f<int, double>,
8734              then our ARGS will be {int, double}, but, when looking up
8735              S we only want {double}.  */
8736           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8737                                          complain, in_decl);
8738           if (argvec == error_mark_node)
8739             r = error_mark_node;
8740           else
8741             {
8742               r = lookup_template_class (t, argvec, in_decl, context,
8743                                          entering_scope, complain);
8744               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8745             }
8746
8747           cp_unevaluated_operand = saved_unevaluated_operand;
8748           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8749
8750           return r;
8751         }
8752       else
8753         /* This is not a template type, so there's nothing to do.  */
8754         return t;
8755
8756     default:
8757       return tsubst (t, args, complain, in_decl);
8758     }
8759 }
8760
8761 /* Substitute into the default argument ARG (a default argument for
8762    FN), which has the indicated TYPE.  */
8763
8764 tree
8765 tsubst_default_argument (tree fn, tree type, tree arg)
8766 {
8767   tree saved_class_ptr = NULL_TREE;
8768   tree saved_class_ref = NULL_TREE;
8769
8770   /* This default argument came from a template.  Instantiate the
8771      default argument here, not in tsubst.  In the case of
8772      something like:
8773
8774        template <class T>
8775        struct S {
8776          static T t();
8777          void f(T = t());
8778        };
8779
8780      we must be careful to do name lookup in the scope of S<T>,
8781      rather than in the current class.  */
8782   push_access_scope (fn);
8783   /* The "this" pointer is not valid in a default argument.  */
8784   if (cfun)
8785     {
8786       saved_class_ptr = current_class_ptr;
8787       cp_function_chain->x_current_class_ptr = NULL_TREE;
8788       saved_class_ref = current_class_ref;
8789       cp_function_chain->x_current_class_ref = NULL_TREE;
8790     }
8791
8792   push_deferring_access_checks(dk_no_deferred);
8793   /* The default argument expression may cause implicitly defined
8794      member functions to be synthesized, which will result in garbage
8795      collection.  We must treat this situation as if we were within
8796      the body of function so as to avoid collecting live data on the
8797      stack.  */
8798   ++function_depth;
8799   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8800                      tf_warning_or_error, NULL_TREE,
8801                      /*integral_constant_expression_p=*/false);
8802   --function_depth;
8803   pop_deferring_access_checks();
8804
8805   /* Restore the "this" pointer.  */
8806   if (cfun)
8807     {
8808       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8809       cp_function_chain->x_current_class_ref = saved_class_ref;
8810     }
8811
8812   /* Make sure the default argument is reasonable.  */
8813   arg = check_default_argument (type, arg);
8814
8815   pop_access_scope (fn);
8816
8817   return arg;
8818 }
8819
8820 /* Substitute into all the default arguments for FN.  */
8821
8822 static void
8823 tsubst_default_arguments (tree fn)
8824 {
8825   tree arg;
8826   tree tmpl_args;
8827
8828   tmpl_args = DECL_TI_ARGS (fn);
8829
8830   /* If this function is not yet instantiated, we certainly don't need
8831      its default arguments.  */
8832   if (uses_template_parms (tmpl_args))
8833     return;
8834
8835   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8836        arg;
8837        arg = TREE_CHAIN (arg))
8838     if (TREE_PURPOSE (arg))
8839       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8840                                                     TREE_VALUE (arg),
8841                                                     TREE_PURPOSE (arg));
8842 }
8843
8844 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8845    result of the substitution.  Issue error and warning messages under
8846    control of COMPLAIN.  */
8847
8848 static tree
8849 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8850 {
8851 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8852   location_t saved_loc;
8853   tree r = NULL_TREE;
8854   tree in_decl = t;
8855   hashval_t hash = 0;
8856
8857   /* Set the filename and linenumber to improve error-reporting.  */
8858   saved_loc = input_location;
8859   input_location = DECL_SOURCE_LOCATION (t);
8860
8861   switch (TREE_CODE (t))
8862     {
8863     case TEMPLATE_DECL:
8864       {
8865         /* We can get here when processing a member function template,
8866            member class template, or template template parameter.  */
8867         tree decl = DECL_TEMPLATE_RESULT (t);
8868         tree spec;
8869         tree tmpl_args;
8870         tree full_args;
8871
8872         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8873           {
8874             /* Template template parameter is treated here.  */
8875             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8876             if (new_type == error_mark_node)
8877               RETURN (error_mark_node);
8878
8879             r = copy_decl (t);
8880             TREE_CHAIN (r) = NULL_TREE;
8881             TREE_TYPE (r) = new_type;
8882             DECL_TEMPLATE_RESULT (r)
8883               = build_decl (DECL_SOURCE_LOCATION (decl),
8884                             TYPE_DECL, DECL_NAME (decl), new_type);
8885             DECL_TEMPLATE_PARMS (r)
8886               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8887                                        complain);
8888             TYPE_NAME (new_type) = r;
8889             break;
8890           }
8891
8892         /* We might already have an instance of this template.
8893            The ARGS are for the surrounding class type, so the
8894            full args contain the tsubst'd args for the context,
8895            plus the innermost args from the template decl.  */
8896         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8897           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8898           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8899         /* Because this is a template, the arguments will still be
8900            dependent, even after substitution.  If
8901            PROCESSING_TEMPLATE_DECL is not set, the dependency
8902            predicates will short-circuit.  */
8903         ++processing_template_decl;
8904         full_args = tsubst_template_args (tmpl_args, args,
8905                                           complain, in_decl);
8906         --processing_template_decl;
8907         if (full_args == error_mark_node)
8908           RETURN (error_mark_node);
8909
8910         /* If this is a default template template argument,
8911            tsubst might not have changed anything.  */
8912         if (full_args == tmpl_args)
8913           RETURN (t);
8914
8915         hash = hash_tmpl_and_args (t, full_args);
8916         spec = retrieve_specialization (t, full_args, hash);
8917         if (spec != NULL_TREE)
8918           {
8919             r = spec;
8920             break;
8921           }
8922
8923         /* Make a new template decl.  It will be similar to the
8924            original, but will record the current template arguments.
8925            We also create a new function declaration, which is just
8926            like the old one, but points to this new template, rather
8927            than the old one.  */
8928         r = copy_decl (t);
8929         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8930         TREE_CHAIN (r) = NULL_TREE;
8931
8932         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8933
8934         if (TREE_CODE (decl) == TYPE_DECL)
8935           {
8936             tree new_type;
8937             ++processing_template_decl;
8938             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8939             --processing_template_decl;
8940             if (new_type == error_mark_node)
8941               RETURN (error_mark_node);
8942
8943             TREE_TYPE (r) = new_type;
8944             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8945             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8946             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8947             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8948           }
8949         else
8950           {
8951             tree new_decl;
8952             ++processing_template_decl;
8953             new_decl = tsubst (decl, args, complain, in_decl);
8954             --processing_template_decl;
8955             if (new_decl == error_mark_node)
8956               RETURN (error_mark_node);
8957
8958             DECL_TEMPLATE_RESULT (r) = new_decl;
8959             DECL_TI_TEMPLATE (new_decl) = r;
8960             TREE_TYPE (r) = TREE_TYPE (new_decl);
8961             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8962             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8963           }
8964
8965         SET_DECL_IMPLICIT_INSTANTIATION (r);
8966         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8967         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8968
8969         /* The template parameters for this new template are all the
8970            template parameters for the old template, except the
8971            outermost level of parameters.  */
8972         DECL_TEMPLATE_PARMS (r)
8973           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8974                                    complain);
8975
8976         if (PRIMARY_TEMPLATE_P (t))
8977           DECL_PRIMARY_TEMPLATE (r) = r;
8978
8979         if (TREE_CODE (decl) != TYPE_DECL)
8980           /* Record this non-type partial instantiation.  */
8981           register_specialization (r, t,
8982                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8983                                    false, hash);
8984       }
8985       break;
8986
8987     case FUNCTION_DECL:
8988       {
8989         tree ctx;
8990         tree argvec = NULL_TREE;
8991         tree *friends;
8992         tree gen_tmpl;
8993         tree type;
8994         int member;
8995         int args_depth;
8996         int parms_depth;
8997
8998         /* Nobody should be tsubst'ing into non-template functions.  */
8999         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9000
9001         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9002           {
9003             tree spec;
9004             bool dependent_p;
9005
9006             /* If T is not dependent, just return it.  We have to
9007                increment PROCESSING_TEMPLATE_DECL because
9008                value_dependent_expression_p assumes that nothing is
9009                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9010             ++processing_template_decl;
9011             dependent_p = value_dependent_expression_p (t);
9012             --processing_template_decl;
9013             if (!dependent_p)
9014               RETURN (t);
9015
9016             /* Calculate the most general template of which R is a
9017                specialization, and the complete set of arguments used to
9018                specialize R.  */
9019             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9020             argvec = tsubst_template_args (DECL_TI_ARGS
9021                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
9022                                            args, complain, in_decl);
9023
9024             /* Check to see if we already have this specialization.  */
9025             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9026             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9027
9028             if (spec)
9029               {
9030                 r = spec;
9031                 break;
9032               }
9033
9034             /* We can see more levels of arguments than parameters if
9035                there was a specialization of a member template, like
9036                this:
9037
9038                  template <class T> struct S { template <class U> void f(); }
9039                  template <> template <class U> void S<int>::f(U);
9040
9041                Here, we'll be substituting into the specialization,
9042                because that's where we can find the code we actually
9043                want to generate, but we'll have enough arguments for
9044                the most general template.
9045
9046                We also deal with the peculiar case:
9047
9048                  template <class T> struct S {
9049                    template <class U> friend void f();
9050                  };
9051                  template <class U> void f() {}
9052                  template S<int>;
9053                  template void f<double>();
9054
9055                Here, the ARGS for the instantiation of will be {int,
9056                double}.  But, we only need as many ARGS as there are
9057                levels of template parameters in CODE_PATTERN.  We are
9058                careful not to get fooled into reducing the ARGS in
9059                situations like:
9060
9061                  template <class T> struct S { template <class U> void f(U); }
9062                  template <class T> template <> void S<T>::f(int) {}
9063
9064                which we can spot because the pattern will be a
9065                specialization in this case.  */
9066             args_depth = TMPL_ARGS_DEPTH (args);
9067             parms_depth =
9068               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9069             if (args_depth > parms_depth
9070                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9071               args = get_innermost_template_args (args, parms_depth);
9072           }
9073         else
9074           {
9075             /* This special case arises when we have something like this:
9076
9077                  template <class T> struct S {
9078                    friend void f<int>(int, double);
9079                  };
9080
9081                Here, the DECL_TI_TEMPLATE for the friend declaration
9082                will be an IDENTIFIER_NODE.  We are being called from
9083                tsubst_friend_function, and we want only to create a
9084                new decl (R) with appropriate types so that we can call
9085                determine_specialization.  */
9086             gen_tmpl = NULL_TREE;
9087           }
9088
9089         if (DECL_CLASS_SCOPE_P (t))
9090           {
9091             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9092               member = 2;
9093             else
9094               member = 1;
9095             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9096                                     complain, t, /*entering_scope=*/1);
9097           }
9098         else
9099           {
9100             member = 0;
9101             ctx = DECL_CONTEXT (t);
9102           }
9103         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9104         if (type == error_mark_node)
9105           RETURN (error_mark_node);
9106
9107         /* We do NOT check for matching decls pushed separately at this
9108            point, as they may not represent instantiations of this
9109            template, and in any case are considered separate under the
9110            discrete model.  */
9111         r = copy_decl (t);
9112         DECL_USE_TEMPLATE (r) = 0;
9113         TREE_TYPE (r) = type;
9114         /* Clear out the mangled name and RTL for the instantiation.  */
9115         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9116         SET_DECL_RTL (r, NULL_RTX);
9117         /* Leave DECL_INITIAL set on deleted instantiations.  */
9118         if (!DECL_DELETED_FN (r))
9119           DECL_INITIAL (r) = NULL_TREE;
9120         DECL_CONTEXT (r) = ctx;
9121
9122         if (member && DECL_CONV_FN_P (r))
9123           /* Type-conversion operator.  Reconstruct the name, in
9124              case it's the name of one of the template's parameters.  */
9125           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9126
9127         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9128                                      complain, t);
9129         DECL_RESULT (r) = NULL_TREE;
9130
9131         TREE_STATIC (r) = 0;
9132         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9133         DECL_EXTERNAL (r) = 1;
9134         /* If this is an instantiation of a function with internal
9135            linkage, we already know what object file linkage will be
9136            assigned to the instantiation.  */
9137         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9138         DECL_DEFER_OUTPUT (r) = 0;
9139         TREE_CHAIN (r) = NULL_TREE;
9140         DECL_PENDING_INLINE_INFO (r) = 0;
9141         DECL_PENDING_INLINE_P (r) = 0;
9142         DECL_SAVED_TREE (r) = NULL_TREE;
9143         DECL_STRUCT_FUNCTION (r) = NULL;
9144         TREE_USED (r) = 0;
9145         /* We'll re-clone as appropriate in instantiate_template.  */
9146         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9147
9148         /* If we aren't complaining now, return on error before we register
9149            the specialization so that we'll complain eventually.  */
9150         if ((complain & tf_error) == 0
9151             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9152             && !grok_op_properties (r, /*complain=*/false))
9153           RETURN (error_mark_node);
9154
9155         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9156            this in the special friend case mentioned above where
9157            GEN_TMPL is NULL.  */
9158         if (gen_tmpl)
9159           {
9160             DECL_TEMPLATE_INFO (r)
9161               = build_template_info (gen_tmpl, argvec);
9162             SET_DECL_IMPLICIT_INSTANTIATION (r);
9163             register_specialization (r, gen_tmpl, argvec, false, hash);
9164
9165             /* We're not supposed to instantiate default arguments
9166                until they are called, for a template.  But, for a
9167                declaration like:
9168
9169                  template <class T> void f ()
9170                  { extern void g(int i = T()); }
9171
9172                we should do the substitution when the template is
9173                instantiated.  We handle the member function case in
9174                instantiate_class_template since the default arguments
9175                might refer to other members of the class.  */
9176             if (!member
9177                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9178                 && !uses_template_parms (argvec))
9179               tsubst_default_arguments (r);
9180           }
9181         else
9182           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9183
9184         /* Copy the list of befriending classes.  */
9185         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9186              *friends;
9187              friends = &TREE_CHAIN (*friends))
9188           {
9189             *friends = copy_node (*friends);
9190             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9191                                             args, complain,
9192                                             in_decl);
9193           }
9194
9195         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9196           {
9197             maybe_retrofit_in_chrg (r);
9198             if (DECL_CONSTRUCTOR_P (r))
9199               grok_ctor_properties (ctx, r);
9200             /* If this is an instantiation of a member template, clone it.
9201                If it isn't, that'll be handled by
9202                clone_constructors_and_destructors.  */
9203             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9204               clone_function_decl (r, /*update_method_vec_p=*/0);
9205           }
9206         else if ((complain & tf_error) != 0
9207                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9208                  && !grok_op_properties (r, /*complain=*/true))
9209           RETURN (error_mark_node);
9210
9211         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9212           SET_DECL_FRIEND_CONTEXT (r,
9213                                    tsubst (DECL_FRIEND_CONTEXT (t),
9214                                             args, complain, in_decl));
9215
9216         /* Possibly limit visibility based on template args.  */
9217         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9218         if (DECL_VISIBILITY_SPECIFIED (t))
9219           {
9220             DECL_VISIBILITY_SPECIFIED (r) = 0;
9221             DECL_ATTRIBUTES (r)
9222               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9223           }
9224         determine_visibility (r);
9225         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9226             && !processing_template_decl)
9227           defaulted_late_check (r);
9228
9229         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9230                                         args, complain, in_decl);
9231       }
9232       break;
9233
9234     case PARM_DECL:
9235       {
9236         tree type = NULL_TREE;
9237         int i, len = 1;
9238         tree expanded_types = NULL_TREE;
9239         tree prev_r = NULL_TREE;
9240         tree first_r = NULL_TREE;
9241
9242         if (FUNCTION_PARAMETER_PACK_P (t))
9243           {
9244             /* If there is a local specialization that isn't a
9245                parameter pack, it means that we're doing a "simple"
9246                substitution from inside tsubst_pack_expansion. Just
9247                return the local specialization (which will be a single
9248                parm).  */
9249             tree spec = retrieve_local_specialization (t);
9250             if (spec 
9251                 && TREE_CODE (spec) == PARM_DECL
9252                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9253               RETURN (spec);
9254
9255             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9256                the parameters in this function parameter pack.  */
9257             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9258                                                     complain, in_decl);
9259             if (TREE_CODE (expanded_types) == TREE_VEC)
9260               {
9261                 len = TREE_VEC_LENGTH (expanded_types);
9262
9263                 /* Zero-length parameter packs are boring. Just substitute
9264                    into the chain.  */
9265                 if (len == 0)
9266                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9267                                   TREE_CHAIN (t)));
9268               }
9269             else
9270               {
9271                 /* All we did was update the type. Make a note of that.  */
9272                 type = expanded_types;
9273                 expanded_types = NULL_TREE;
9274               }
9275           }
9276
9277         /* Loop through all of the parameter's we'll build. When T is
9278            a function parameter pack, LEN is the number of expanded
9279            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9280         r = NULL_TREE;
9281         for (i = 0; i < len; ++i)
9282           {
9283             prev_r = r;
9284             r = copy_node (t);
9285             if (DECL_TEMPLATE_PARM_P (t))
9286               SET_DECL_TEMPLATE_PARM_P (r);
9287
9288             /* An argument of a function parameter pack is not a parameter
9289                pack.  */
9290             FUNCTION_PARAMETER_PACK_P (r) = false;
9291
9292             if (expanded_types)
9293               /* We're on the Ith parameter of the function parameter
9294                  pack.  */
9295               {
9296                 /* Get the Ith type.  */
9297                 type = TREE_VEC_ELT (expanded_types, i);
9298
9299                 if (DECL_NAME (r))
9300                   /* Rename the parameter to include the index.  */
9301                   DECL_NAME (r) =
9302                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9303               }
9304             else if (!type)
9305               /* We're dealing with a normal parameter.  */
9306               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9307
9308             type = type_decays_to (type);
9309             TREE_TYPE (r) = type;
9310             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9311
9312             if (DECL_INITIAL (r))
9313               {
9314                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9315                   DECL_INITIAL (r) = TREE_TYPE (r);
9316                 else
9317                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9318                                              complain, in_decl);
9319               }
9320
9321             DECL_CONTEXT (r) = NULL_TREE;
9322
9323             if (!DECL_TEMPLATE_PARM_P (r))
9324               DECL_ARG_TYPE (r) = type_passed_as (type);
9325
9326             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9327                                             args, complain, in_decl);
9328
9329             /* Keep track of the first new parameter we
9330                generate. That's what will be returned to the
9331                caller.  */
9332             if (!first_r)
9333               first_r = r;
9334
9335             /* Build a proper chain of parameters when substituting
9336                into a function parameter pack.  */
9337             if (prev_r)
9338               TREE_CHAIN (prev_r) = r;
9339           }
9340
9341         if (TREE_CHAIN (t))
9342           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9343                                    complain, TREE_CHAIN (t));
9344
9345         /* FIRST_R contains the start of the chain we've built.  */
9346         r = first_r;
9347       }
9348       break;
9349
9350     case FIELD_DECL:
9351       {
9352         tree type;
9353
9354         r = copy_decl (t);
9355         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9356         if (type == error_mark_node)
9357           RETURN (error_mark_node);
9358         TREE_TYPE (r) = type;
9359         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9360
9361         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9362         DECL_INITIAL (r)
9363           = tsubst_expr (DECL_INITIAL (t), args,
9364                          complain, in_decl,
9365                          /*integral_constant_expression_p=*/true);
9366         /* We don't have to set DECL_CONTEXT here; it is set by
9367            finish_member_declaration.  */
9368         TREE_CHAIN (r) = NULL_TREE;
9369         if (VOID_TYPE_P (type))
9370           error ("instantiation of %q+D as type %qT", r, type);
9371
9372         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9373                                         args, complain, in_decl);
9374       }
9375       break;
9376
9377     case USING_DECL:
9378       /* We reach here only for member using decls.  */
9379       if (DECL_DEPENDENT_P (t))
9380         {
9381           r = do_class_using_decl
9382             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9383              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9384           if (!r)
9385             r = error_mark_node;
9386           else
9387             {
9388               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9389               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9390             }
9391         }
9392       else
9393         {
9394           r = copy_node (t);
9395           TREE_CHAIN (r) = NULL_TREE;
9396         }
9397       break;
9398
9399     case TYPE_DECL:
9400     case VAR_DECL:
9401       {
9402         tree argvec = NULL_TREE;
9403         tree gen_tmpl = NULL_TREE;
9404         tree spec;
9405         tree tmpl = NULL_TREE;
9406         tree ctx;
9407         tree type = NULL_TREE;
9408         bool local_p;
9409
9410         if (TREE_CODE (t) == TYPE_DECL
9411             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9412           {
9413             /* If this is the canonical decl, we don't have to
9414                mess with instantiations, and often we can't (for
9415                typename, template type parms and such).  Note that
9416                TYPE_NAME is not correct for the above test if
9417                we've copied the type for a typedef.  */
9418             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9419             if (type == error_mark_node)
9420               RETURN (error_mark_node);
9421             r = TYPE_NAME (type);
9422             break;
9423           }
9424
9425         /* Check to see if we already have the specialization we
9426            need.  */
9427         spec = NULL_TREE;
9428         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9429           {
9430             /* T is a static data member or namespace-scope entity.
9431                We have to substitute into namespace-scope variables
9432                (even though such entities are never templates) because
9433                of cases like:
9434                
9435                  template <class T> void f() { extern T t; }
9436
9437                where the entity referenced is not known until
9438                instantiation time.  */
9439             local_p = false;
9440             ctx = DECL_CONTEXT (t);
9441             if (DECL_CLASS_SCOPE_P (t))
9442               {
9443                 ctx = tsubst_aggr_type (ctx, args,
9444                                         complain,
9445                                         in_decl, /*entering_scope=*/1);
9446                 /* If CTX is unchanged, then T is in fact the
9447                    specialization we want.  That situation occurs when
9448                    referencing a static data member within in its own
9449                    class.  We can use pointer equality, rather than
9450                    same_type_p, because DECL_CONTEXT is always
9451                    canonical.  */
9452                 if (ctx == DECL_CONTEXT (t))
9453                   spec = t;
9454               }
9455
9456             if (!spec)
9457               {
9458                 tmpl = DECL_TI_TEMPLATE (t);
9459                 gen_tmpl = most_general_template (tmpl);
9460                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9461                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9462                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9463               }
9464           }
9465         else
9466           {
9467             /* A local variable.  */
9468             local_p = true;
9469             /* Subsequent calls to pushdecl will fill this in.  */
9470             ctx = NULL_TREE;
9471             spec = retrieve_local_specialization (t);
9472           }
9473         /* If we already have the specialization we need, there is
9474            nothing more to do.  */ 
9475         if (spec)
9476           {
9477             r = spec;
9478             break;
9479           }
9480
9481         /* Create a new node for the specialization we need.  */
9482         r = copy_decl (t);
9483         if (type == NULL_TREE)
9484           {
9485             if (is_typedef_decl (t))
9486               type = DECL_ORIGINAL_TYPE (t);
9487             else
9488               type = TREE_TYPE (t);
9489             type = tsubst (type, args, complain, in_decl);
9490           }
9491         if (TREE_CODE (r) == VAR_DECL)
9492           {
9493             /* Even if the original location is out of scope, the
9494                newly substituted one is not.  */
9495             DECL_DEAD_FOR_LOCAL (r) = 0;
9496             DECL_INITIALIZED_P (r) = 0;
9497             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9498             if (type == error_mark_node)
9499               RETURN (error_mark_node);
9500             if (TREE_CODE (type) == FUNCTION_TYPE)
9501               {
9502                 /* It may seem that this case cannot occur, since:
9503
9504                      typedef void f();
9505                      void g() { f x; }
9506
9507                    declares a function, not a variable.  However:
9508       
9509                      typedef void f();
9510                      template <typename T> void g() { T t; }
9511                      template void g<f>();
9512
9513                    is an attempt to declare a variable with function
9514                    type.  */
9515                 error ("variable %qD has function type",
9516                        /* R is not yet sufficiently initialized, so we
9517                           just use its name.  */
9518                        DECL_NAME (r));
9519                 RETURN (error_mark_node);
9520               }
9521             type = complete_type (type);
9522             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9523               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9524             type = check_var_type (DECL_NAME (r), type);
9525
9526             if (DECL_HAS_VALUE_EXPR_P (t))
9527               {
9528                 tree ve = DECL_VALUE_EXPR (t);
9529                 ve = tsubst_expr (ve, args, complain, in_decl,
9530                                   /*constant_expression_p=*/false);
9531                 SET_DECL_VALUE_EXPR (r, ve);
9532               }
9533           }
9534         else if (DECL_SELF_REFERENCE_P (t))
9535           SET_DECL_SELF_REFERENCE_P (r);
9536         TREE_TYPE (r) = type;
9537         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9538         DECL_CONTEXT (r) = ctx;
9539         /* Clear out the mangled name and RTL for the instantiation.  */
9540         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9541         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9542           SET_DECL_RTL (r, NULL_RTX);
9543         /* The initializer must not be expanded until it is required;
9544            see [temp.inst].  */
9545         DECL_INITIAL (r) = NULL_TREE;
9546         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9547           SET_DECL_RTL (r, NULL_RTX);
9548         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9549         if (TREE_CODE (r) == VAR_DECL)
9550           {
9551             /* Possibly limit visibility based on template args.  */
9552             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9553             if (DECL_VISIBILITY_SPECIFIED (t))
9554               {
9555                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9556                 DECL_ATTRIBUTES (r)
9557                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9558               }
9559             determine_visibility (r);
9560           }
9561
9562         if (!local_p)
9563           {
9564             /* A static data member declaration is always marked
9565                external when it is declared in-class, even if an
9566                initializer is present.  We mimic the non-template
9567                processing here.  */
9568             DECL_EXTERNAL (r) = 1;
9569
9570             register_specialization (r, gen_tmpl, argvec, false, hash);
9571             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9572             SET_DECL_IMPLICIT_INSTANTIATION (r);
9573           }
9574         else if (cp_unevaluated_operand)
9575           {
9576             /* We're substituting this var in a decltype outside of its
9577                scope, such as for a lambda return type.  Don't add it to
9578                local_specializations, do perform auto deduction.  */
9579             tree auto_node = type_uses_auto (type);
9580             tree init
9581               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9582                              /*constant_expression_p=*/false);
9583
9584             if (auto_node && init && describable_type (init))
9585               {
9586                 type = do_auto_deduction (type, init, auto_node);
9587                 TREE_TYPE (r) = type;
9588               }
9589           }
9590         else
9591           register_local_specialization (r, t);
9592
9593         TREE_CHAIN (r) = NULL_TREE;
9594
9595         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9596                                         /*flags=*/0,
9597                                         args, complain, in_decl);
9598
9599         /* Preserve a typedef that names a type.  */
9600         if (is_typedef_decl (r))
9601           {
9602             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9603             set_underlying_type (r);
9604           }
9605
9606         layout_decl (r, 0);
9607       }
9608       break;
9609
9610     default:
9611       gcc_unreachable ();
9612     }
9613 #undef RETURN
9614
9615  out:
9616   /* Restore the file and line information.  */
9617   input_location = saved_loc;
9618
9619   return r;
9620 }
9621
9622 /* Substitute into the ARG_TYPES of a function type.  */
9623
9624 static tree
9625 tsubst_arg_types (tree arg_types,
9626                   tree args,
9627                   tsubst_flags_t complain,
9628                   tree in_decl)
9629 {
9630   tree remaining_arg_types;
9631   tree type = NULL_TREE;
9632   int i = 1;
9633   tree expanded_args = NULL_TREE;
9634   tree default_arg;
9635
9636   if (!arg_types || arg_types == void_list_node)
9637     return arg_types;
9638
9639   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9640                                           args, complain, in_decl);
9641   if (remaining_arg_types == error_mark_node)
9642     return error_mark_node;
9643
9644   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9645     {
9646       /* For a pack expansion, perform substitution on the
9647          entire expression. Later on, we'll handle the arguments
9648          one-by-one.  */
9649       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9650                                             args, complain, in_decl);
9651
9652       if (TREE_CODE (expanded_args) == TREE_VEC)
9653         /* So that we'll spin through the parameters, one by one.  */
9654         i = TREE_VEC_LENGTH (expanded_args);
9655       else
9656         {
9657           /* We only partially substituted into the parameter
9658              pack. Our type is TYPE_PACK_EXPANSION.  */
9659           type = expanded_args;
9660           expanded_args = NULL_TREE;
9661         }
9662     }
9663
9664   while (i > 0) {
9665     --i;
9666     
9667     if (expanded_args)
9668       type = TREE_VEC_ELT (expanded_args, i);
9669     else if (!type)
9670       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9671
9672     if (type == error_mark_node)
9673       return error_mark_node;
9674     if (VOID_TYPE_P (type))
9675       {
9676         if (complain & tf_error)
9677           {
9678             error ("invalid parameter type %qT", type);
9679             if (in_decl)
9680               error ("in declaration %q+D", in_decl);
9681           }
9682         return error_mark_node;
9683     }
9684     
9685     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9686        top-level qualifiers as required.  */
9687     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9688
9689     /* We do not substitute into default arguments here.  The standard
9690        mandates that they be instantiated only when needed, which is
9691        done in build_over_call.  */
9692     default_arg = TREE_PURPOSE (arg_types);
9693
9694     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9695       {
9696         /* We've instantiated a template before its default arguments
9697            have been parsed.  This can happen for a nested template
9698            class, and is not an error unless we require the default
9699            argument in a call of this function.  */
9700         remaining_arg_types = 
9701           tree_cons (default_arg, type, remaining_arg_types);
9702         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9703                        remaining_arg_types);
9704       }
9705     else
9706       remaining_arg_types = 
9707         hash_tree_cons (default_arg, type, remaining_arg_types);
9708   }
9709         
9710   return remaining_arg_types;
9711 }
9712
9713 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9714    *not* handle the exception-specification for FNTYPE, because the
9715    initial substitution of explicitly provided template parameters
9716    during argument deduction forbids substitution into the
9717    exception-specification:
9718
9719      [temp.deduct]
9720
9721      All references in the function type of the function template to  the
9722      corresponding template parameters are replaced by the specified tem-
9723      plate argument values.  If a substitution in a template parameter or
9724      in  the function type of the function template results in an invalid
9725      type, type deduction fails.  [Note: The equivalent  substitution  in
9726      exception specifications is done only when the function is instanti-
9727      ated, at which point a program is  ill-formed  if  the  substitution
9728      results in an invalid type.]  */
9729
9730 static tree
9731 tsubst_function_type (tree t,
9732                       tree args,
9733                       tsubst_flags_t complain,
9734                       tree in_decl)
9735 {
9736   tree return_type;
9737   tree arg_types;
9738   tree fntype;
9739
9740   /* The TYPE_CONTEXT is not used for function/method types.  */
9741   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9742
9743   /* Substitute the return type.  */
9744   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9745   if (return_type == error_mark_node)
9746     return error_mark_node;
9747   /* The standard does not presently indicate that creation of a
9748      function type with an invalid return type is a deduction failure.
9749      However, that is clearly analogous to creating an array of "void"
9750      or a reference to a reference.  This is core issue #486.  */
9751   if (TREE_CODE (return_type) == ARRAY_TYPE
9752       || TREE_CODE (return_type) == FUNCTION_TYPE)
9753     {
9754       if (complain & tf_error)
9755         {
9756           if (TREE_CODE (return_type) == ARRAY_TYPE)
9757             error ("function returning an array");
9758           else
9759             error ("function returning a function");
9760         }
9761       return error_mark_node;
9762     }
9763
9764   /* Substitute the argument types.  */
9765   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9766                                 complain, in_decl);
9767   if (arg_types == error_mark_node)
9768     return error_mark_node;
9769
9770   /* Construct a new type node and return it.  */
9771   if (TREE_CODE (t) == FUNCTION_TYPE)
9772     fntype = build_function_type (return_type, arg_types);
9773   else
9774     {
9775       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9776       if (! MAYBE_CLASS_TYPE_P (r))
9777         {
9778           /* [temp.deduct]
9779
9780              Type deduction may fail for any of the following
9781              reasons:
9782
9783              -- Attempting to create "pointer to member of T" when T
9784              is not a class type.  */
9785           if (complain & tf_error)
9786             error ("creating pointer to member function of non-class type %qT",
9787                       r);
9788           return error_mark_node;
9789         }
9790
9791       fntype = build_method_type_directly (r, return_type,
9792                                            TREE_CHAIN (arg_types));
9793     }
9794   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9795   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9796
9797   return fntype;
9798 }
9799
9800 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9801    ARGS into that specification, and return the substituted
9802    specification.  If there is no specification, return NULL_TREE.  */
9803
9804 static tree
9805 tsubst_exception_specification (tree fntype,
9806                                 tree args,
9807                                 tsubst_flags_t complain,
9808                                 tree in_decl)
9809 {
9810   tree specs;
9811   tree new_specs;
9812
9813   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9814   new_specs = NULL_TREE;
9815   if (specs)
9816     {
9817       if (! TREE_VALUE (specs))
9818         new_specs = specs;
9819       else
9820         while (specs)
9821           {
9822             tree spec;
9823             int i, len = 1;
9824             tree expanded_specs = NULL_TREE;
9825
9826             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9827               {
9828                 /* Expand the pack expansion type.  */
9829                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9830                                                        args, complain,
9831                                                        in_decl);
9832
9833                 if (expanded_specs == error_mark_node)
9834                   return error_mark_node;
9835                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9836                   len = TREE_VEC_LENGTH (expanded_specs);
9837                 else
9838                   {
9839                     /* We're substituting into a member template, so
9840                        we got a TYPE_PACK_EXPANSION back.  Add that
9841                        expansion and move on.  */
9842                     gcc_assert (TREE_CODE (expanded_specs) 
9843                                 == TYPE_PACK_EXPANSION);
9844                     new_specs = add_exception_specifier (new_specs,
9845                                                          expanded_specs,
9846                                                          complain);
9847                     specs = TREE_CHAIN (specs);
9848                     continue;
9849                   }
9850               }
9851
9852             for (i = 0; i < len; ++i)
9853               {
9854                 if (expanded_specs)
9855                   spec = TREE_VEC_ELT (expanded_specs, i);
9856                 else
9857                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9858                 if (spec == error_mark_node)
9859                   return spec;
9860                 new_specs = add_exception_specifier (new_specs, spec, 
9861                                                      complain);
9862               }
9863
9864             specs = TREE_CHAIN (specs);
9865           }
9866     }
9867   return new_specs;
9868 }
9869
9870 /* Take the tree structure T and replace template parameters used
9871    therein with the argument vector ARGS.  IN_DECL is an associated
9872    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9873    Issue error and warning messages under control of COMPLAIN.  Note
9874    that we must be relatively non-tolerant of extensions here, in
9875    order to preserve conformance; if we allow substitutions that
9876    should not be allowed, we may allow argument deductions that should
9877    not succeed, and therefore report ambiguous overload situations
9878    where there are none.  In theory, we could allow the substitution,
9879    but indicate that it should have failed, and allow our caller to
9880    make sure that the right thing happens, but we don't try to do this
9881    yet.
9882
9883    This function is used for dealing with types, decls and the like;
9884    for expressions, use tsubst_expr or tsubst_copy.  */
9885
9886 tree
9887 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9888 {
9889   tree type, r;
9890
9891   if (t == NULL_TREE || t == error_mark_node
9892       || t == integer_type_node
9893       || t == void_type_node
9894       || t == char_type_node
9895       || t == unknown_type_node
9896       || TREE_CODE (t) == NAMESPACE_DECL)
9897     return t;
9898
9899   if (DECL_P (t))
9900     return tsubst_decl (t, args, complain);
9901
9902   if (args == NULL_TREE)
9903     return t;
9904
9905   if (TREE_CODE (t) == IDENTIFIER_NODE)
9906     type = IDENTIFIER_TYPE_VALUE (t);
9907   else
9908     type = TREE_TYPE (t);
9909
9910   gcc_assert (type != unknown_type_node);
9911
9912   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9913      such as attribute aligned.  */
9914   if (TYPE_P (t)
9915       && TYPE_NAME (t)
9916       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9917     {
9918       tree decl = TYPE_NAME (t);
9919       
9920       if (DECL_CLASS_SCOPE_P (decl)
9921           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9922           && uses_template_parms (DECL_CONTEXT (decl)))
9923         {
9924           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9925           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9926           r = retrieve_specialization (tmpl, gen_args, 0);
9927         }
9928       else if (DECL_FUNCTION_SCOPE_P (decl)
9929                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9930                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9931         r = retrieve_local_specialization (decl);
9932       else
9933         /* The typedef is from a non-template context.  */
9934         return t;
9935
9936       if (r)
9937         {
9938           r = TREE_TYPE (r);
9939           r = cp_build_qualified_type_real
9940             (r, cp_type_quals (t) | cp_type_quals (r),
9941              complain | tf_ignore_bad_quals);
9942           return r;
9943         }
9944       /* Else we must be instantiating the typedef, so fall through.  */
9945     }
9946
9947   if (type
9948       && TREE_CODE (t) != TYPENAME_TYPE
9949       && TREE_CODE (t) != TEMPLATE_TYPE_PARM
9950       && TREE_CODE (t) != IDENTIFIER_NODE
9951       && TREE_CODE (t) != FUNCTION_TYPE
9952       && TREE_CODE (t) != METHOD_TYPE)
9953     type = tsubst (type, args, complain, in_decl);
9954   if (type == error_mark_node)
9955     return error_mark_node;
9956
9957   switch (TREE_CODE (t))
9958     {
9959     case RECORD_TYPE:
9960     case UNION_TYPE:
9961     case ENUMERAL_TYPE:
9962       return tsubst_aggr_type (t, args, complain, in_decl,
9963                                /*entering_scope=*/0);
9964
9965     case ERROR_MARK:
9966     case IDENTIFIER_NODE:
9967     case VOID_TYPE:
9968     case REAL_TYPE:
9969     case COMPLEX_TYPE:
9970     case VECTOR_TYPE:
9971     case BOOLEAN_TYPE:
9972     case INTEGER_CST:
9973     case REAL_CST:
9974     case STRING_CST:
9975       return t;
9976
9977     case INTEGER_TYPE:
9978       if (t == integer_type_node)
9979         return t;
9980
9981       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9982           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9983         return t;
9984
9985       {
9986         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9987
9988         max = tsubst_expr (omax, args, complain, in_decl,
9989                            /*integral_constant_expression_p=*/false);
9990
9991         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9992            needed.  */
9993         if (TREE_CODE (max) == NOP_EXPR
9994             && TREE_SIDE_EFFECTS (omax)
9995             && !TREE_TYPE (max))
9996           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9997
9998         max = fold_decl_constant_value (max);
9999
10000         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10001            with TREE_SIDE_EFFECTS that indicates this is not an integral
10002            constant expression.  */
10003         if (processing_template_decl
10004             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10005           {
10006             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10007             TREE_SIDE_EFFECTS (max) = 1;
10008           }
10009
10010         if (TREE_CODE (max) != INTEGER_CST
10011             && !at_function_scope_p ()
10012             && !TREE_SIDE_EFFECTS (max)
10013             && !value_dependent_expression_p (max))
10014           {
10015             if (complain & tf_error)
10016               error ("array bound is not an integer constant");
10017             return error_mark_node;
10018           }
10019
10020         /* [temp.deduct]
10021
10022            Type deduction may fail for any of the following
10023            reasons:
10024
10025              Attempting to create an array with a size that is
10026              zero or negative.  */
10027         if (integer_zerop (max) && !(complain & tf_error))
10028           /* We must fail if performing argument deduction (as
10029              indicated by the state of complain), so that
10030              another substitution can be found.  */
10031           return error_mark_node;
10032         else if (TREE_CODE (max) == INTEGER_CST
10033                  && INT_CST_LT (max, integer_zero_node))
10034           {
10035             if (complain & tf_error)
10036               error ("creating array with negative size (%qE)", max);
10037
10038             return error_mark_node;
10039           }
10040
10041         return compute_array_index_type (NULL_TREE, max);
10042       }
10043
10044     case TEMPLATE_TYPE_PARM:
10045     case TEMPLATE_TEMPLATE_PARM:
10046     case BOUND_TEMPLATE_TEMPLATE_PARM:
10047     case TEMPLATE_PARM_INDEX:
10048       {
10049         int idx;
10050         int level;
10051         int levels;
10052         tree arg = NULL_TREE;
10053
10054         r = NULL_TREE;
10055
10056         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10057         template_parm_level_and_index (t, &level, &idx); 
10058
10059         levels = TMPL_ARGS_DEPTH (args);
10060         if (level <= levels)
10061           {
10062             arg = TMPL_ARG (args, level, idx);
10063
10064             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10065               /* See through ARGUMENT_PACK_SELECT arguments. */
10066               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10067           }
10068
10069         if (arg == error_mark_node)
10070           return error_mark_node;
10071         else if (arg != NULL_TREE)
10072           {
10073             if (ARGUMENT_PACK_P (arg))
10074               /* If ARG is an argument pack, we don't actually want to
10075                  perform a substitution here, because substitutions
10076                  for argument packs are only done
10077                  element-by-element. We can get to this point when
10078                  substituting the type of a non-type template
10079                  parameter pack, when that type actually contains
10080                  template parameter packs from an outer template, e.g.,
10081
10082                  template<typename... Types> struct A {
10083                    template<Types... Values> struct B { };
10084                  };  */
10085               return t;
10086
10087             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10088               {
10089                 int quals;
10090                 gcc_assert (TYPE_P (arg));
10091
10092                 /* cv-quals from the template are discarded when
10093                    substituting in a function or reference type.  */
10094                 if (TREE_CODE (arg) == FUNCTION_TYPE
10095                     || TREE_CODE (arg) == METHOD_TYPE
10096                     || TREE_CODE (arg) == REFERENCE_TYPE)
10097                   quals = cp_type_quals (arg);
10098                 else
10099                   quals = cp_type_quals (arg) | cp_type_quals (t);
10100                   
10101                 return cp_build_qualified_type_real
10102                   (arg, quals, complain | tf_ignore_bad_quals);
10103               }
10104             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10105               {
10106                 /* We are processing a type constructed from a
10107                    template template parameter.  */
10108                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10109                                       args, complain, in_decl);
10110                 if (argvec == error_mark_node)
10111                   return error_mark_node;
10112
10113                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10114                    are resolving nested-types in the signature of a
10115                    member function templates.  Otherwise ARG is a
10116                    TEMPLATE_DECL and is the real template to be
10117                    instantiated.  */
10118                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10119                   arg = TYPE_NAME (arg);
10120
10121                 r = lookup_template_class (arg,
10122                                            argvec, in_decl,
10123                                            DECL_CONTEXT (arg),
10124                                             /*entering_scope=*/0,
10125                                            complain);
10126                 return cp_build_qualified_type_real
10127                   (r, TYPE_QUALS (t), complain);
10128               }
10129             else
10130               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10131               return arg;
10132           }
10133
10134         if (level == 1)
10135           /* This can happen during the attempted tsubst'ing in
10136              unify.  This means that we don't yet have any information
10137              about the template parameter in question.  */
10138           return t;
10139
10140         /* If we get here, we must have been looking at a parm for a
10141            more deeply nested template.  Make a new version of this
10142            template parameter, but with a lower level.  */
10143         switch (TREE_CODE (t))
10144           {
10145           case TEMPLATE_TYPE_PARM:
10146           case TEMPLATE_TEMPLATE_PARM:
10147           case BOUND_TEMPLATE_TEMPLATE_PARM:
10148             if (cp_type_quals (t))
10149               {
10150                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10151                 r = cp_build_qualified_type_real
10152                   (r, cp_type_quals (t),
10153                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10154                                ? tf_ignore_bad_quals : 0));
10155               }
10156             else
10157               {
10158                 r = copy_type (t);
10159                 TEMPLATE_TYPE_PARM_INDEX (r)
10160                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10161                                                 r, levels, args, complain);
10162                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10163                 TYPE_MAIN_VARIANT (r) = r;
10164                 TYPE_POINTER_TO (r) = NULL_TREE;
10165                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10166
10167                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10168                   /* We have reduced the level of the template
10169                      template parameter, but not the levels of its
10170                      template parameters, so canonical_type_parameter
10171                      will not be able to find the canonical template
10172                      template parameter for this level. Thus, we
10173                      require structural equality checking to compare
10174                      TEMPLATE_TEMPLATE_PARMs. */
10175                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10176                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10177                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10178                 else
10179                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10180
10181                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10182                   {
10183                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10184                                           complain, in_decl);
10185                     if (argvec == error_mark_node)
10186                       return error_mark_node;
10187
10188                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10189                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10190                   }
10191               }
10192             break;
10193
10194           case TEMPLATE_PARM_INDEX:
10195             r = reduce_template_parm_level (t, type, levels, args, complain);
10196             break;
10197
10198           default:
10199             gcc_unreachable ();
10200           }
10201
10202         return r;
10203       }
10204
10205     case TREE_LIST:
10206       {
10207         tree purpose, value, chain;
10208
10209         if (t == void_list_node)
10210           return t;
10211
10212         purpose = TREE_PURPOSE (t);
10213         if (purpose)
10214           {
10215             purpose = tsubst (purpose, args, complain, in_decl);
10216             if (purpose == error_mark_node)
10217               return error_mark_node;
10218           }
10219         value = TREE_VALUE (t);
10220         if (value)
10221           {
10222             value = tsubst (value, args, complain, in_decl);
10223             if (value == error_mark_node)
10224               return error_mark_node;
10225           }
10226         chain = TREE_CHAIN (t);
10227         if (chain && chain != void_type_node)
10228           {
10229             chain = tsubst (chain, args, complain, in_decl);
10230             if (chain == error_mark_node)
10231               return error_mark_node;
10232           }
10233         if (purpose == TREE_PURPOSE (t)
10234             && value == TREE_VALUE (t)
10235             && chain == TREE_CHAIN (t))
10236           return t;
10237         return hash_tree_cons (purpose, value, chain);
10238       }
10239
10240     case TREE_BINFO:
10241       /* We should never be tsubsting a binfo.  */
10242       gcc_unreachable ();
10243
10244     case TREE_VEC:
10245       /* A vector of template arguments.  */
10246       gcc_assert (!type);
10247       return tsubst_template_args (t, args, complain, in_decl);
10248
10249     case POINTER_TYPE:
10250     case REFERENCE_TYPE:
10251       {
10252         enum tree_code code;
10253
10254         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10255           return t;
10256
10257         code = TREE_CODE (t);
10258
10259
10260         /* [temp.deduct]
10261
10262            Type deduction may fail for any of the following
10263            reasons:
10264
10265            -- Attempting to create a pointer to reference type.
10266            -- Attempting to create a reference to a reference type or
10267               a reference to void.
10268
10269           Core issue 106 says that creating a reference to a reference
10270           during instantiation is no longer a cause for failure. We
10271           only enforce this check in strict C++98 mode.  */
10272         if ((TREE_CODE (type) == REFERENCE_TYPE
10273              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10274             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10275           {
10276             static location_t last_loc;
10277
10278             /* We keep track of the last time we issued this error
10279                message to avoid spewing a ton of messages during a
10280                single bad template instantiation.  */
10281             if (complain & tf_error
10282                 && last_loc != input_location)
10283               {
10284                 if (TREE_CODE (type) == VOID_TYPE)
10285                   error ("forming reference to void");
10286                else if (code == POINTER_TYPE)
10287                  error ("forming pointer to reference type %qT", type);
10288                else
10289                   error ("forming reference to reference type %qT", type);
10290                 last_loc = input_location;
10291               }
10292
10293             return error_mark_node;
10294           }
10295         else if (code == POINTER_TYPE)
10296           {
10297             r = build_pointer_type (type);
10298             if (TREE_CODE (type) == METHOD_TYPE)
10299               r = build_ptrmemfunc_type (r);
10300           }
10301         else if (TREE_CODE (type) == REFERENCE_TYPE)
10302           /* In C++0x, during template argument substitution, when there is an
10303              attempt to create a reference to a reference type, reference
10304              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10305
10306              "If a template-argument for a template-parameter T names a type
10307              that is a reference to a type A, an attempt to create the type
10308              'lvalue reference to cv T' creates the type 'lvalue reference to
10309              A,' while an attempt to create the type type rvalue reference to
10310              cv T' creates the type T"
10311           */
10312           r = cp_build_reference_type
10313               (TREE_TYPE (type),
10314                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10315         else
10316           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10317         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10318
10319         if (r != error_mark_node)
10320           /* Will this ever be needed for TYPE_..._TO values?  */
10321           layout_type (r);
10322
10323         return r;
10324       }
10325     case OFFSET_TYPE:
10326       {
10327         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10328         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10329           {
10330             /* [temp.deduct]
10331
10332                Type deduction may fail for any of the following
10333                reasons:
10334
10335                -- Attempting to create "pointer to member of T" when T
10336                   is not a class type.  */
10337             if (complain & tf_error)
10338               error ("creating pointer to member of non-class type %qT", r);
10339             return error_mark_node;
10340           }
10341         if (TREE_CODE (type) == REFERENCE_TYPE)
10342           {
10343             if (complain & tf_error)
10344               error ("creating pointer to member reference type %qT", type);
10345             return error_mark_node;
10346           }
10347         if (TREE_CODE (type) == VOID_TYPE)
10348           {
10349             if (complain & tf_error)
10350               error ("creating pointer to member of type void");
10351             return error_mark_node;
10352           }
10353         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10354         if (TREE_CODE (type) == FUNCTION_TYPE)
10355           {
10356             /* The type of the implicit object parameter gets its
10357                cv-qualifiers from the FUNCTION_TYPE. */
10358             tree memptr;
10359             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10360             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10361             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10362                                                  complain);
10363           }
10364         else
10365           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10366                                                TYPE_QUALS (t),
10367                                                complain);
10368       }
10369     case FUNCTION_TYPE:
10370     case METHOD_TYPE:
10371       {
10372         tree fntype;
10373         tree specs;
10374         fntype = tsubst_function_type (t, args, complain, in_decl);
10375         if (fntype == error_mark_node)
10376           return error_mark_node;
10377
10378         /* Substitute the exception specification.  */
10379         specs = tsubst_exception_specification (t, args, complain,
10380                                                 in_decl);
10381         if (specs == error_mark_node)
10382           return error_mark_node;
10383         if (specs)
10384           fntype = build_exception_variant (fntype, specs);
10385         return fntype;
10386       }
10387     case ARRAY_TYPE:
10388       {
10389         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10390         if (domain == error_mark_node)
10391           return error_mark_node;
10392
10393         /* As an optimization, we avoid regenerating the array type if
10394            it will obviously be the same as T.  */
10395         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10396           return t;
10397
10398         /* These checks should match the ones in grokdeclarator.
10399
10400            [temp.deduct]
10401
10402            The deduction may fail for any of the following reasons:
10403
10404            -- Attempting to create an array with an element type that
10405               is void, a function type, or a reference type, or [DR337]
10406               an abstract class type.  */
10407         if (TREE_CODE (type) == VOID_TYPE
10408             || TREE_CODE (type) == FUNCTION_TYPE
10409             || TREE_CODE (type) == REFERENCE_TYPE)
10410           {
10411             if (complain & tf_error)
10412               error ("creating array of %qT", type);
10413             return error_mark_node;
10414           }
10415         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10416           {
10417             if (complain & tf_error)
10418               error ("creating array of %qT, which is an abstract class type",
10419                      type);
10420             return error_mark_node;
10421           }
10422
10423         r = build_cplus_array_type (type, domain);
10424
10425         if (TYPE_USER_ALIGN (t))
10426           {
10427             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10428             TYPE_USER_ALIGN (r) = 1;
10429           }
10430
10431         return r;
10432       }
10433
10434     case PLUS_EXPR:
10435     case MINUS_EXPR:
10436       {
10437         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10438         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10439
10440         if (e1 == error_mark_node || e2 == error_mark_node)
10441           return error_mark_node;
10442
10443         return fold_build2_loc (input_location,
10444                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10445       }
10446
10447     case NEGATE_EXPR:
10448     case NOP_EXPR:
10449       {
10450         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10451         if (e == error_mark_node)
10452           return error_mark_node;
10453
10454         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10455       }
10456
10457     case TYPENAME_TYPE:
10458       {
10459         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10460                                      in_decl, /*entering_scope=*/1);
10461         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10462                               complain, in_decl);
10463
10464         if (ctx == error_mark_node || f == error_mark_node)
10465           return error_mark_node;
10466
10467         if (!MAYBE_CLASS_TYPE_P (ctx))
10468           {
10469             if (complain & tf_error)
10470               error ("%qT is not a class, struct, or union type", ctx);
10471             return error_mark_node;
10472           }
10473         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10474           {
10475             /* Normally, make_typename_type does not require that the CTX
10476                have complete type in order to allow things like:
10477
10478                  template <class T> struct S { typename S<T>::X Y; };
10479
10480                But, such constructs have already been resolved by this
10481                point, so here CTX really should have complete type, unless
10482                it's a partial instantiation.  */
10483             if (!(complain & tf_no_class_instantiations))
10484               ctx = complete_type (ctx);
10485             if (!COMPLETE_TYPE_P (ctx))
10486               {
10487                 if (complain & tf_error)
10488                   cxx_incomplete_type_error (NULL_TREE, ctx);
10489                 return error_mark_node;
10490               }
10491           }
10492
10493         f = make_typename_type (ctx, f, typename_type,
10494                                 (complain & tf_error) | tf_keep_type_decl);
10495         if (f == error_mark_node)
10496           return f;
10497         if (TREE_CODE (f) == TYPE_DECL)
10498           {
10499             complain |= tf_ignore_bad_quals;
10500             f = TREE_TYPE (f);
10501           }
10502
10503         if (TREE_CODE (f) != TYPENAME_TYPE)
10504           {
10505             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10506               error ("%qT resolves to %qT, which is not an enumeration type",
10507                      t, f);
10508             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10509               error ("%qT resolves to %qT, which is is not a class type",
10510                      t, f);
10511           }
10512
10513         return cp_build_qualified_type_real
10514           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10515       }
10516
10517     case UNBOUND_CLASS_TEMPLATE:
10518       {
10519         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10520                                      in_decl, /*entering_scope=*/1);
10521         tree name = TYPE_IDENTIFIER (t);
10522         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10523
10524         if (ctx == error_mark_node || name == error_mark_node)
10525           return error_mark_node;
10526
10527         if (parm_list)
10528           parm_list = tsubst_template_parms (parm_list, args, complain);
10529         return make_unbound_class_template (ctx, name, parm_list, complain);
10530       }
10531
10532     case INDIRECT_REF:
10533     case ADDR_EXPR:
10534     case CALL_EXPR:
10535       gcc_unreachable ();
10536
10537     case ARRAY_REF:
10538       {
10539         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10540         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10541                                /*integral_constant_expression_p=*/false);
10542         if (e1 == error_mark_node || e2 == error_mark_node)
10543           return error_mark_node;
10544
10545         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10546       }
10547
10548     case SCOPE_REF:
10549       {
10550         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10551         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10552         if (e1 == error_mark_node || e2 == error_mark_node)
10553           return error_mark_node;
10554
10555         return build_qualified_name (/*type=*/NULL_TREE,
10556                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10557       }
10558
10559     case TYPEOF_TYPE:
10560       {
10561         tree type;
10562
10563         ++cp_unevaluated_operand;
10564         ++c_inhibit_evaluation_warnings;
10565
10566         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10567                             complain, in_decl,
10568                             /*integral_constant_expression_p=*/false);
10569
10570         --cp_unevaluated_operand;
10571         --c_inhibit_evaluation_warnings;
10572
10573         type = finish_typeof (type);
10574         return cp_build_qualified_type_real (type,
10575                                              cp_type_quals (t)
10576                                              | cp_type_quals (type),
10577                                              complain);
10578       }
10579
10580     case DECLTYPE_TYPE:
10581       {
10582         tree type;
10583
10584         ++cp_unevaluated_operand;
10585         ++c_inhibit_evaluation_warnings;
10586
10587         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10588                             complain, in_decl,
10589                             /*integral_constant_expression_p=*/false);
10590
10591         --cp_unevaluated_operand;
10592         --c_inhibit_evaluation_warnings;
10593
10594         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10595           type = lambda_capture_field_type (type);
10596         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10597           type = lambda_return_type (type);
10598         else
10599           type = finish_decltype_type
10600             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10601         return cp_build_qualified_type_real (type,
10602                                              cp_type_quals (t)
10603                                              | cp_type_quals (type),
10604                                              complain);
10605       }
10606
10607     case TYPE_ARGUMENT_PACK:
10608     case NONTYPE_ARGUMENT_PACK:
10609       {
10610         tree r = TYPE_P (t)
10611           ? cxx_make_type (TREE_CODE (t))
10612           : make_node (TREE_CODE (t));
10613         tree packed_out = 
10614           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10615                                 args,
10616                                 complain,
10617                                 in_decl);
10618         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10619
10620         /* For template nontype argument packs, also substitute into
10621            the type.  */
10622         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10623           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10624
10625         return r;
10626       }
10627       break;
10628
10629     default:
10630       sorry ("use of %qs in template",
10631              tree_code_name [(int) TREE_CODE (t)]);
10632       return error_mark_node;
10633     }
10634 }
10635
10636 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10637    type of the expression on the left-hand side of the "." or "->"
10638    operator.  */
10639
10640 static tree
10641 tsubst_baselink (tree baselink, tree object_type,
10642                  tree args, tsubst_flags_t complain, tree in_decl)
10643 {
10644     tree name;
10645     tree qualifying_scope;
10646     tree fns;
10647     tree optype;
10648     tree template_args = 0;
10649     bool template_id_p = false;
10650
10651     /* A baselink indicates a function from a base class.  Both the
10652        BASELINK_ACCESS_BINFO and the base class referenced may
10653        indicate bases of the template class, rather than the
10654        instantiated class.  In addition, lookups that were not
10655        ambiguous before may be ambiguous now.  Therefore, we perform
10656        the lookup again.  */
10657     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10658     qualifying_scope = tsubst (qualifying_scope, args,
10659                                complain, in_decl);
10660     fns = BASELINK_FUNCTIONS (baselink);
10661     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10662     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10663       {
10664         template_id_p = true;
10665         template_args = TREE_OPERAND (fns, 1);
10666         fns = TREE_OPERAND (fns, 0);
10667         if (template_args)
10668           template_args = tsubst_template_args (template_args, args,
10669                                                 complain, in_decl);
10670       }
10671     name = DECL_NAME (get_first_fn (fns));
10672     if (IDENTIFIER_TYPENAME_P (name))
10673       name = mangle_conv_op_name_for_type (optype);
10674     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10675
10676     /* If lookup found a single function, mark it as used at this
10677        point.  (If it lookup found multiple functions the one selected
10678        later by overload resolution will be marked as used at that
10679        point.)  */
10680     if (BASELINK_P (baselink))
10681       fns = BASELINK_FUNCTIONS (baselink);
10682     if (!template_id_p && !really_overloaded_fn (fns))
10683       mark_used (OVL_CURRENT (fns));
10684
10685     /* Add back the template arguments, if present.  */
10686     if (BASELINK_P (baselink) && template_id_p)
10687       BASELINK_FUNCTIONS (baselink)
10688         = build_nt (TEMPLATE_ID_EXPR,
10689                     BASELINK_FUNCTIONS (baselink),
10690                     template_args);
10691     /* Update the conversion operator type.  */
10692     BASELINK_OPTYPE (baselink) = optype;
10693
10694     if (!object_type)
10695       object_type = current_class_type;
10696     return adjust_result_of_qualified_name_lookup (baselink,
10697                                                    qualifying_scope,
10698                                                    object_type);
10699 }
10700
10701 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10702    true if the qualified-id will be a postfix-expression in-and-of
10703    itself; false if more of the postfix-expression follows the
10704    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10705    of "&".  */
10706
10707 static tree
10708 tsubst_qualified_id (tree qualified_id, tree args,
10709                      tsubst_flags_t complain, tree in_decl,
10710                      bool done, bool address_p)
10711 {
10712   tree expr;
10713   tree scope;
10714   tree name;
10715   bool is_template;
10716   tree template_args;
10717
10718   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10719
10720   /* Figure out what name to look up.  */
10721   name = TREE_OPERAND (qualified_id, 1);
10722   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10723     {
10724       is_template = true;
10725       template_args = TREE_OPERAND (name, 1);
10726       if (template_args)
10727         template_args = tsubst_template_args (template_args, args,
10728                                               complain, in_decl);
10729       name = TREE_OPERAND (name, 0);
10730     }
10731   else
10732     {
10733       is_template = false;
10734       template_args = NULL_TREE;
10735     }
10736
10737   /* Substitute into the qualifying scope.  When there are no ARGS, we
10738      are just trying to simplify a non-dependent expression.  In that
10739      case the qualifying scope may be dependent, and, in any case,
10740      substituting will not help.  */
10741   scope = TREE_OPERAND (qualified_id, 0);
10742   if (args)
10743     {
10744       scope = tsubst (scope, args, complain, in_decl);
10745       expr = tsubst_copy (name, args, complain, in_decl);
10746     }
10747   else
10748     expr = name;
10749
10750   if (dependent_scope_p (scope))
10751     return build_qualified_name (NULL_TREE, scope, expr,
10752                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10753
10754   if (!BASELINK_P (name) && !DECL_P (expr))
10755     {
10756       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10757         {
10758           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10759           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10760             {
10761               error ("qualifying type %qT does not match destructor name ~%qT",
10762                      scope, TREE_OPERAND (expr, 0));
10763               expr = error_mark_node;
10764             }
10765           else
10766             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10767                                           /*is_type_p=*/0, false);
10768         }
10769       else
10770         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10771       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10772                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10773         {
10774           if (complain & tf_error)
10775             {
10776               error ("dependent-name %qE is parsed as a non-type, but "
10777                      "instantiation yields a type", qualified_id);
10778               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10779             }
10780           return error_mark_node;
10781         }
10782     }
10783
10784   if (DECL_P (expr))
10785     {
10786       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10787                                            scope);
10788       /* Remember that there was a reference to this entity.  */
10789       mark_used (expr);
10790     }
10791
10792   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10793     {
10794       if (complain & tf_error)
10795         qualified_name_lookup_error (scope,
10796                                      TREE_OPERAND (qualified_id, 1),
10797                                      expr, input_location);
10798       return error_mark_node;
10799     }
10800
10801   if (is_template)
10802     expr = lookup_template_function (expr, template_args);
10803
10804   if (expr == error_mark_node && complain & tf_error)
10805     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10806                                  expr, input_location);
10807   else if (TYPE_P (scope))
10808     {
10809       expr = (adjust_result_of_qualified_name_lookup
10810               (expr, scope, current_class_type));
10811       expr = (finish_qualified_id_expr
10812               (scope, expr, done, address_p,
10813                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10814                /*template_arg_p=*/false));
10815     }
10816
10817   /* Expressions do not generally have reference type.  */
10818   if (TREE_CODE (expr) != SCOPE_REF
10819       /* However, if we're about to form a pointer-to-member, we just
10820          want the referenced member referenced.  */
10821       && TREE_CODE (expr) != OFFSET_REF)
10822     expr = convert_from_reference (expr);
10823
10824   return expr;
10825 }
10826
10827 /* Like tsubst, but deals with expressions.  This function just replaces
10828    template parms; to finish processing the resultant expression, use
10829    tsubst_expr.  */
10830
10831 static tree
10832 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10833 {
10834   enum tree_code code;
10835   tree r;
10836
10837   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10838     return t;
10839
10840   code = TREE_CODE (t);
10841
10842   switch (code)
10843     {
10844     case PARM_DECL:
10845       r = retrieve_local_specialization (t);
10846
10847       if (r == NULL)
10848         {
10849           tree c;
10850           /* This can happen for a parameter name used later in a function
10851              declaration (such as in a late-specified return type).  Just
10852              make a dummy decl, since it's only used for its type.  */
10853           gcc_assert (cp_unevaluated_operand != 0);
10854           /* We copy T because want to tsubst the PARM_DECL only,
10855              not the following PARM_DECLs that are chained to T.  */
10856           c = copy_node (t);
10857           r = tsubst_decl (c, args, complain);
10858           /* Give it the template pattern as its context; its true context
10859              hasn't been instantiated yet and this is good enough for
10860              mangling.  */
10861           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10862         }
10863       
10864       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10865         r = ARGUMENT_PACK_SELECT_ARG (r);
10866       mark_used (r);
10867       return r;
10868
10869     case CONST_DECL:
10870       {
10871         tree enum_type;
10872         tree v;
10873
10874         if (DECL_TEMPLATE_PARM_P (t))
10875           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10876         /* There is no need to substitute into namespace-scope
10877            enumerators.  */
10878         if (DECL_NAMESPACE_SCOPE_P (t))
10879           return t;
10880         /* If ARGS is NULL, then T is known to be non-dependent.  */
10881         if (args == NULL_TREE)
10882           return integral_constant_value (t);
10883
10884         /* Unfortunately, we cannot just call lookup_name here.
10885            Consider:
10886
10887              template <int I> int f() {
10888              enum E { a = I };
10889              struct S { void g() { E e = a; } };
10890              };
10891
10892            When we instantiate f<7>::S::g(), say, lookup_name is not
10893            clever enough to find f<7>::a.  */
10894         enum_type
10895           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10896                               /*entering_scope=*/0);
10897
10898         for (v = TYPE_VALUES (enum_type);
10899              v != NULL_TREE;
10900              v = TREE_CHAIN (v))
10901           if (TREE_PURPOSE (v) == DECL_NAME (t))
10902             return TREE_VALUE (v);
10903
10904           /* We didn't find the name.  That should never happen; if
10905              name-lookup found it during preliminary parsing, we
10906              should find it again here during instantiation.  */
10907         gcc_unreachable ();
10908       }
10909       return t;
10910
10911     case FIELD_DECL:
10912       if (DECL_CONTEXT (t))
10913         {
10914           tree ctx;
10915
10916           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10917                                   /*entering_scope=*/1);
10918           if (ctx != DECL_CONTEXT (t))
10919             {
10920               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10921               if (!r)
10922                 {
10923                   if (complain & tf_error)
10924                     error ("using invalid field %qD", t);
10925                   return error_mark_node;
10926                 }
10927               return r;
10928             }
10929         }
10930
10931       return t;
10932
10933     case VAR_DECL:
10934     case FUNCTION_DECL:
10935       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10936           || local_variable_p (t))
10937         t = tsubst (t, args, complain, in_decl);
10938       mark_used (t);
10939       return t;
10940
10941     case BASELINK:
10942       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10943
10944     case TEMPLATE_DECL:
10945       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10946         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10947                        args, complain, in_decl);
10948       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10949         return tsubst (t, args, complain, in_decl);
10950       else if (DECL_CLASS_SCOPE_P (t)
10951                && uses_template_parms (DECL_CONTEXT (t)))
10952         {
10953           /* Template template argument like the following example need
10954              special treatment:
10955
10956                template <template <class> class TT> struct C {};
10957                template <class T> struct D {
10958                  template <class U> struct E {};
10959                  C<E> c;                                // #1
10960                };
10961                D<int> d;                                // #2
10962
10963              We are processing the template argument `E' in #1 for
10964              the template instantiation #2.  Originally, `E' is a
10965              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10966              have to substitute this with one having context `D<int>'.  */
10967
10968           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10969           return lookup_field (context, DECL_NAME(t), 0, false);
10970         }
10971       else
10972         /* Ordinary template template argument.  */
10973         return t;
10974
10975     case CAST_EXPR:
10976     case REINTERPRET_CAST_EXPR:
10977     case CONST_CAST_EXPR:
10978     case STATIC_CAST_EXPR:
10979     case DYNAMIC_CAST_EXPR:
10980     case NOP_EXPR:
10981       return build1
10982         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10983          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10984
10985     case SIZEOF_EXPR:
10986       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10987         {
10988           /* We only want to compute the number of arguments.  */
10989           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10990                                                 complain, in_decl);
10991           int len = 0;
10992
10993           if (TREE_CODE (expanded) == TREE_VEC)
10994             len = TREE_VEC_LENGTH (expanded);
10995
10996           if (expanded == error_mark_node)
10997             return error_mark_node;
10998           else if (PACK_EXPANSION_P (expanded)
10999                    || (TREE_CODE (expanded) == TREE_VEC
11000                        && len > 0
11001                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11002             {
11003               if (TREE_CODE (expanded) == TREE_VEC)
11004                 expanded = TREE_VEC_ELT (expanded, len - 1);
11005
11006               if (TYPE_P (expanded))
11007                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11008                                                    complain & tf_error);
11009               else
11010                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11011                                                    complain & tf_error);
11012             }
11013           else
11014             return build_int_cst (size_type_node, len);
11015         }
11016       /* Fall through */
11017
11018     case INDIRECT_REF:
11019     case NEGATE_EXPR:
11020     case TRUTH_NOT_EXPR:
11021     case BIT_NOT_EXPR:
11022     case ADDR_EXPR:
11023     case UNARY_PLUS_EXPR:      /* Unary + */
11024     case ALIGNOF_EXPR:
11025     case ARROW_EXPR:
11026     case THROW_EXPR:
11027     case TYPEID_EXPR:
11028     case REALPART_EXPR:
11029     case IMAGPART_EXPR:
11030       return build1
11031         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11032          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11033
11034     case COMPONENT_REF:
11035       {
11036         tree object;
11037         tree name;
11038
11039         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11040         name = TREE_OPERAND (t, 1);
11041         if (TREE_CODE (name) == BIT_NOT_EXPR)
11042           {
11043             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11044                                 complain, in_decl);
11045             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11046           }
11047         else if (TREE_CODE (name) == SCOPE_REF
11048                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11049           {
11050             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11051                                      complain, in_decl);
11052             name = TREE_OPERAND (name, 1);
11053             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11054                                 complain, in_decl);
11055             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11056             name = build_qualified_name (/*type=*/NULL_TREE,
11057                                          base, name,
11058                                          /*template_p=*/false);
11059           }
11060         else if (TREE_CODE (name) == BASELINK)
11061           name = tsubst_baselink (name,
11062                                   non_reference (TREE_TYPE (object)),
11063                                   args, complain,
11064                                   in_decl);
11065         else
11066           name = tsubst_copy (name, args, complain, in_decl);
11067         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11068       }
11069
11070     case PLUS_EXPR:
11071     case MINUS_EXPR:
11072     case MULT_EXPR:
11073     case TRUNC_DIV_EXPR:
11074     case CEIL_DIV_EXPR:
11075     case FLOOR_DIV_EXPR:
11076     case ROUND_DIV_EXPR:
11077     case EXACT_DIV_EXPR:
11078     case BIT_AND_EXPR:
11079     case BIT_IOR_EXPR:
11080     case BIT_XOR_EXPR:
11081     case TRUNC_MOD_EXPR:
11082     case FLOOR_MOD_EXPR:
11083     case TRUTH_ANDIF_EXPR:
11084     case TRUTH_ORIF_EXPR:
11085     case TRUTH_AND_EXPR:
11086     case TRUTH_OR_EXPR:
11087     case RSHIFT_EXPR:
11088     case LSHIFT_EXPR:
11089     case RROTATE_EXPR:
11090     case LROTATE_EXPR:
11091     case EQ_EXPR:
11092     case NE_EXPR:
11093     case MAX_EXPR:
11094     case MIN_EXPR:
11095     case LE_EXPR:
11096     case GE_EXPR:
11097     case LT_EXPR:
11098     case GT_EXPR:
11099     case COMPOUND_EXPR:
11100     case DOTSTAR_EXPR:
11101     case MEMBER_REF:
11102     case PREDECREMENT_EXPR:
11103     case PREINCREMENT_EXPR:
11104     case POSTDECREMENT_EXPR:
11105     case POSTINCREMENT_EXPR:
11106       return build_nt
11107         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11108          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11109
11110     case SCOPE_REF:
11111       return build_qualified_name (/*type=*/NULL_TREE,
11112                                    tsubst_copy (TREE_OPERAND (t, 0),
11113                                                 args, complain, in_decl),
11114                                    tsubst_copy (TREE_OPERAND (t, 1),
11115                                                 args, complain, in_decl),
11116                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11117
11118     case ARRAY_REF:
11119       return build_nt
11120         (ARRAY_REF,
11121          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11122          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11123          NULL_TREE, NULL_TREE);
11124
11125     case CALL_EXPR:
11126       {
11127         int n = VL_EXP_OPERAND_LENGTH (t);
11128         tree result = build_vl_exp (CALL_EXPR, n);
11129         int i;
11130         for (i = 0; i < n; i++)
11131           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11132                                              complain, in_decl);
11133         return result;
11134       }
11135
11136     case COND_EXPR:
11137     case MODOP_EXPR:
11138     case PSEUDO_DTOR_EXPR:
11139       {
11140         r = build_nt
11141           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11142            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11143            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11144         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11145         return r;
11146       }
11147
11148     case NEW_EXPR:
11149       {
11150         r = build_nt
11151         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11152          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11153          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11154         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11155         return r;
11156       }
11157
11158     case DELETE_EXPR:
11159       {
11160         r = build_nt
11161         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11162          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11163         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11164         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11165         return r;
11166       }
11167
11168     case TEMPLATE_ID_EXPR:
11169       {
11170         /* Substituted template arguments */
11171         tree fn = TREE_OPERAND (t, 0);
11172         tree targs = TREE_OPERAND (t, 1);
11173
11174         fn = tsubst_copy (fn, args, complain, in_decl);
11175         if (targs)
11176           targs = tsubst_template_args (targs, args, complain, in_decl);
11177
11178         return lookup_template_function (fn, targs);
11179       }
11180
11181     case TREE_LIST:
11182       {
11183         tree purpose, value, chain;
11184
11185         if (t == void_list_node)
11186           return t;
11187
11188         purpose = TREE_PURPOSE (t);
11189         if (purpose)
11190           purpose = tsubst_copy (purpose, args, complain, in_decl);
11191         value = TREE_VALUE (t);
11192         if (value)
11193           value = tsubst_copy (value, args, complain, in_decl);
11194         chain = TREE_CHAIN (t);
11195         if (chain && chain != void_type_node)
11196           chain = tsubst_copy (chain, args, complain, in_decl);
11197         if (purpose == TREE_PURPOSE (t)
11198             && value == TREE_VALUE (t)
11199             && chain == TREE_CHAIN (t))
11200           return t;
11201         return tree_cons (purpose, value, chain);
11202       }
11203
11204     case RECORD_TYPE:
11205     case UNION_TYPE:
11206     case ENUMERAL_TYPE:
11207     case INTEGER_TYPE:
11208     case TEMPLATE_TYPE_PARM:
11209     case TEMPLATE_TEMPLATE_PARM:
11210     case BOUND_TEMPLATE_TEMPLATE_PARM:
11211     case TEMPLATE_PARM_INDEX:
11212     case POINTER_TYPE:
11213     case REFERENCE_TYPE:
11214     case OFFSET_TYPE:
11215     case FUNCTION_TYPE:
11216     case METHOD_TYPE:
11217     case ARRAY_TYPE:
11218     case TYPENAME_TYPE:
11219     case UNBOUND_CLASS_TEMPLATE:
11220     case TYPEOF_TYPE:
11221     case DECLTYPE_TYPE:
11222     case TYPE_DECL:
11223       return tsubst (t, args, complain, in_decl);
11224
11225     case IDENTIFIER_NODE:
11226       if (IDENTIFIER_TYPENAME_P (t))
11227         {
11228           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11229           return mangle_conv_op_name_for_type (new_type);
11230         }
11231       else
11232         return t;
11233
11234     case CONSTRUCTOR:
11235       /* This is handled by tsubst_copy_and_build.  */
11236       gcc_unreachable ();
11237
11238     case VA_ARG_EXPR:
11239       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11240                                           in_decl),
11241                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11242
11243     case CLEANUP_POINT_EXPR:
11244       /* We shouldn't have built any of these during initial template
11245          generation.  Instead, they should be built during instantiation
11246          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11247       gcc_unreachable ();
11248
11249     case OFFSET_REF:
11250       mark_used (TREE_OPERAND (t, 1));
11251       return t;
11252
11253     case EXPR_PACK_EXPANSION:
11254       error ("invalid use of pack expansion expression");
11255       return error_mark_node;
11256
11257     case NONTYPE_ARGUMENT_PACK:
11258       error ("use %<...%> to expand argument pack");
11259       return error_mark_node;
11260
11261     default:
11262       return t;
11263     }
11264 }
11265
11266 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11267
11268 static tree
11269 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11270                     tree in_decl)
11271 {
11272   tree new_clauses = NULL, nc, oc;
11273
11274   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11275     {
11276       nc = copy_node (oc);
11277       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11278       new_clauses = nc;
11279
11280       switch (OMP_CLAUSE_CODE (nc))
11281         {
11282         case OMP_CLAUSE_LASTPRIVATE:
11283           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11284             {
11285               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11286               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11287                            in_decl, /*integral_constant_expression_p=*/false);
11288               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11289                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11290             }
11291           /* FALLTHRU */
11292         case OMP_CLAUSE_PRIVATE:
11293         case OMP_CLAUSE_SHARED:
11294         case OMP_CLAUSE_FIRSTPRIVATE:
11295         case OMP_CLAUSE_REDUCTION:
11296         case OMP_CLAUSE_COPYIN:
11297         case OMP_CLAUSE_COPYPRIVATE:
11298         case OMP_CLAUSE_IF:
11299         case OMP_CLAUSE_NUM_THREADS:
11300         case OMP_CLAUSE_SCHEDULE:
11301         case OMP_CLAUSE_COLLAPSE:
11302           OMP_CLAUSE_OPERAND (nc, 0)
11303             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11304                            in_decl, /*integral_constant_expression_p=*/false);
11305           break;
11306         case OMP_CLAUSE_NOWAIT:
11307         case OMP_CLAUSE_ORDERED:
11308         case OMP_CLAUSE_DEFAULT:
11309         case OMP_CLAUSE_UNTIED:
11310           break;
11311         default:
11312           gcc_unreachable ();
11313         }
11314     }
11315
11316   return finish_omp_clauses (nreverse (new_clauses));
11317 }
11318
11319 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11320
11321 static tree
11322 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11323                           tree in_decl)
11324 {
11325 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11326
11327   tree purpose, value, chain;
11328
11329   if (t == NULL)
11330     return t;
11331
11332   if (TREE_CODE (t) != TREE_LIST)
11333     return tsubst_copy_and_build (t, args, complain, in_decl,
11334                                   /*function_p=*/false,
11335                                   /*integral_constant_expression_p=*/false);
11336
11337   if (t == void_list_node)
11338     return t;
11339
11340   purpose = TREE_PURPOSE (t);
11341   if (purpose)
11342     purpose = RECUR (purpose);
11343   value = TREE_VALUE (t);
11344   if (value && TREE_CODE (value) != LABEL_DECL)
11345     value = RECUR (value);
11346   chain = TREE_CHAIN (t);
11347   if (chain && chain != void_type_node)
11348     chain = RECUR (chain);
11349   return tree_cons (purpose, value, chain);
11350 #undef RECUR
11351 }
11352
11353 /* Substitute one OMP_FOR iterator.  */
11354
11355 static void
11356 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11357                          tree condv, tree incrv, tree *clauses,
11358                          tree args, tsubst_flags_t complain, tree in_decl,
11359                          bool integral_constant_expression_p)
11360 {
11361 #define RECUR(NODE)                             \
11362   tsubst_expr ((NODE), args, complain, in_decl, \
11363                integral_constant_expression_p)
11364   tree decl, init, cond, incr, auto_node;
11365
11366   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11367   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11368   decl = RECUR (TREE_OPERAND (init, 0));
11369   init = TREE_OPERAND (init, 1);
11370   auto_node = type_uses_auto (TREE_TYPE (decl));
11371   if (auto_node && init)
11372     {
11373       tree init_expr = init;
11374       if (TREE_CODE (init_expr) == DECL_EXPR)
11375         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11376       init_expr = RECUR (init_expr);
11377       TREE_TYPE (decl)
11378         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11379     }
11380   gcc_assert (!type_dependent_expression_p (decl));
11381
11382   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11383     {
11384       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11385       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11386       if (TREE_CODE (incr) == MODIFY_EXPR)
11387         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11388                                     RECUR (TREE_OPERAND (incr, 1)),
11389                                     complain);
11390       else
11391         incr = RECUR (incr);
11392       TREE_VEC_ELT (declv, i) = decl;
11393       TREE_VEC_ELT (initv, i) = init;
11394       TREE_VEC_ELT (condv, i) = cond;
11395       TREE_VEC_ELT (incrv, i) = incr;
11396       return;
11397     }
11398
11399   if (init && TREE_CODE (init) != DECL_EXPR)
11400     {
11401       tree c;
11402       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11403         {
11404           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11405                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11406               && OMP_CLAUSE_DECL (c) == decl)
11407             break;
11408           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11409                    && OMP_CLAUSE_DECL (c) == decl)
11410             error ("iteration variable %qD should not be firstprivate", decl);
11411           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11412                    && OMP_CLAUSE_DECL (c) == decl)
11413             error ("iteration variable %qD should not be reduction", decl);
11414         }
11415       if (c == NULL)
11416         {
11417           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11418           OMP_CLAUSE_DECL (c) = decl;
11419           c = finish_omp_clauses (c);
11420           if (c)
11421             {
11422               OMP_CLAUSE_CHAIN (c) = *clauses;
11423               *clauses = c;
11424             }
11425         }
11426     }
11427   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11428   if (COMPARISON_CLASS_P (cond))
11429     cond = build2 (TREE_CODE (cond), boolean_type_node,
11430                    RECUR (TREE_OPERAND (cond, 0)),
11431                    RECUR (TREE_OPERAND (cond, 1)));
11432   else
11433     cond = RECUR (cond);
11434   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11435   switch (TREE_CODE (incr))
11436     {
11437     case PREINCREMENT_EXPR:
11438     case PREDECREMENT_EXPR:
11439     case POSTINCREMENT_EXPR:
11440     case POSTDECREMENT_EXPR:
11441       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11442                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11443       break;
11444     case MODIFY_EXPR:
11445       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11446           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11447         {
11448           tree rhs = TREE_OPERAND (incr, 1);
11449           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11450                          RECUR (TREE_OPERAND (incr, 0)),
11451                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11452                                  RECUR (TREE_OPERAND (rhs, 0)),
11453                                  RECUR (TREE_OPERAND (rhs, 1))));
11454         }
11455       else
11456         incr = RECUR (incr);
11457       break;
11458     case MODOP_EXPR:
11459       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11460           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11461         {
11462           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11463           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11464                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11465                                  TREE_TYPE (decl), lhs,
11466                                  RECUR (TREE_OPERAND (incr, 2))));
11467         }
11468       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11469                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11470                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11471         {
11472           tree rhs = TREE_OPERAND (incr, 2);
11473           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11474                          RECUR (TREE_OPERAND (incr, 0)),
11475                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11476                                  RECUR (TREE_OPERAND (rhs, 0)),
11477                                  RECUR (TREE_OPERAND (rhs, 1))));
11478         }
11479       else
11480         incr = RECUR (incr);
11481       break;
11482     default:
11483       incr = RECUR (incr);
11484       break;
11485     }
11486
11487   TREE_VEC_ELT (declv, i) = decl;
11488   TREE_VEC_ELT (initv, i) = init;
11489   TREE_VEC_ELT (condv, i) = cond;
11490   TREE_VEC_ELT (incrv, i) = incr;
11491 #undef RECUR
11492 }
11493
11494 /* Like tsubst_copy for expressions, etc. but also does semantic
11495    processing.  */
11496
11497 static tree
11498 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11499              bool integral_constant_expression_p)
11500 {
11501 #define RECUR(NODE)                             \
11502   tsubst_expr ((NODE), args, complain, in_decl, \
11503                integral_constant_expression_p)
11504
11505   tree stmt, tmp;
11506
11507   if (t == NULL_TREE || t == error_mark_node)
11508     return t;
11509
11510   if (EXPR_HAS_LOCATION (t))
11511     input_location = EXPR_LOCATION (t);
11512   if (STATEMENT_CODE_P (TREE_CODE (t)))
11513     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11514
11515   switch (TREE_CODE (t))
11516     {
11517     case STATEMENT_LIST:
11518       {
11519         tree_stmt_iterator i;
11520         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11521           RECUR (tsi_stmt (i));
11522         break;
11523       }
11524
11525     case CTOR_INITIALIZER:
11526       finish_mem_initializers (tsubst_initializer_list
11527                                (TREE_OPERAND (t, 0), args));
11528       break;
11529
11530     case RETURN_EXPR:
11531       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11532       break;
11533
11534     case EXPR_STMT:
11535       tmp = RECUR (EXPR_STMT_EXPR (t));
11536       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11537         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11538       else
11539         finish_expr_stmt (tmp);
11540       break;
11541
11542     case USING_STMT:
11543       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11544       break;
11545
11546     case DECL_EXPR:
11547       {
11548         tree decl;
11549         tree init;
11550
11551         decl = DECL_EXPR_DECL (t);
11552         if (TREE_CODE (decl) == LABEL_DECL)
11553           finish_label_decl (DECL_NAME (decl));
11554         else if (TREE_CODE (decl) == USING_DECL)
11555           {
11556             tree scope = USING_DECL_SCOPE (decl);
11557             tree name = DECL_NAME (decl);
11558             tree decl;
11559
11560             scope = RECUR (scope);
11561             decl = lookup_qualified_name (scope, name,
11562                                           /*is_type_p=*/false,
11563                                           /*complain=*/false);
11564             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11565               qualified_name_lookup_error (scope, name, decl, input_location);
11566             else
11567               do_local_using_decl (decl, scope, name);
11568           }
11569         else
11570           {
11571             init = DECL_INITIAL (decl);
11572             decl = tsubst (decl, args, complain, in_decl);
11573             if (decl != error_mark_node)
11574               {
11575                 /* By marking the declaration as instantiated, we avoid
11576                    trying to instantiate it.  Since instantiate_decl can't
11577                    handle local variables, and since we've already done
11578                    all that needs to be done, that's the right thing to
11579                    do.  */
11580                 if (TREE_CODE (decl) == VAR_DECL)
11581                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11582                 if (TREE_CODE (decl) == VAR_DECL
11583                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11584                   /* Anonymous aggregates are a special case.  */
11585                   finish_anon_union (decl);
11586                 else
11587                   {
11588                     maybe_push_decl (decl);
11589                     if (TREE_CODE (decl) == VAR_DECL
11590                         && DECL_PRETTY_FUNCTION_P (decl))
11591                       {
11592                         /* For __PRETTY_FUNCTION__ we have to adjust the
11593                            initializer.  */
11594                         const char *const name
11595                           = cxx_printable_name (current_function_decl, 2);
11596                         init = cp_fname_init (name, &TREE_TYPE (decl));
11597                       }
11598                     else
11599                       {
11600                         tree t = RECUR (init);
11601
11602                         if (init && !t)
11603                           /* If we had an initializer but it
11604                              instantiated to nothing,
11605                              value-initialize the object.  This will
11606                              only occur when the initializer was a
11607                              pack expansion where the parameter packs
11608                              used in that expansion were of length
11609                              zero.  */
11610                           init = build_value_init (TREE_TYPE (decl));
11611                         else
11612                           init = t;
11613                       }
11614
11615                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11616                   }
11617               }
11618           }
11619
11620         /* A DECL_EXPR can also be used as an expression, in the condition
11621            clause of an if/for/while construct.  */
11622         return decl;
11623       }
11624
11625     case FOR_STMT:
11626       stmt = begin_for_stmt ();
11627                           RECUR (FOR_INIT_STMT (t));
11628       finish_for_init_stmt (stmt);
11629       tmp = RECUR (FOR_COND (t));
11630       finish_for_cond (tmp, stmt);
11631       tmp = RECUR (FOR_EXPR (t));
11632       finish_for_expr (tmp, stmt);
11633       RECUR (FOR_BODY (t));
11634       finish_for_stmt (stmt);
11635       break;
11636
11637     case WHILE_STMT:
11638       stmt = begin_while_stmt ();
11639       tmp = RECUR (WHILE_COND (t));
11640       finish_while_stmt_cond (tmp, stmt);
11641       RECUR (WHILE_BODY (t));
11642       finish_while_stmt (stmt);
11643       break;
11644
11645     case DO_STMT:
11646       stmt = begin_do_stmt ();
11647       RECUR (DO_BODY (t));
11648       finish_do_body (stmt);
11649       tmp = RECUR (DO_COND (t));
11650       finish_do_stmt (tmp, stmt);
11651       break;
11652
11653     case IF_STMT:
11654       stmt = begin_if_stmt ();
11655       tmp = RECUR (IF_COND (t));
11656       finish_if_stmt_cond (tmp, stmt);
11657       RECUR (THEN_CLAUSE (t));
11658       finish_then_clause (stmt);
11659
11660       if (ELSE_CLAUSE (t))
11661         {
11662           begin_else_clause (stmt);
11663           RECUR (ELSE_CLAUSE (t));
11664           finish_else_clause (stmt);
11665         }
11666
11667       finish_if_stmt (stmt);
11668       break;
11669
11670     case BIND_EXPR:
11671       if (BIND_EXPR_BODY_BLOCK (t))
11672         stmt = begin_function_body ();
11673       else
11674         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11675                                     ? BCS_TRY_BLOCK : 0);
11676
11677       RECUR (BIND_EXPR_BODY (t));
11678
11679       if (BIND_EXPR_BODY_BLOCK (t))
11680         finish_function_body (stmt);
11681       else
11682         finish_compound_stmt (stmt);
11683       break;
11684
11685     case BREAK_STMT:
11686       finish_break_stmt ();
11687       break;
11688
11689     case CONTINUE_STMT:
11690       finish_continue_stmt ();
11691       break;
11692
11693     case SWITCH_STMT:
11694       stmt = begin_switch_stmt ();
11695       tmp = RECUR (SWITCH_STMT_COND (t));
11696       finish_switch_cond (tmp, stmt);
11697       RECUR (SWITCH_STMT_BODY (t));
11698       finish_switch_stmt (stmt);
11699       break;
11700
11701     case CASE_LABEL_EXPR:
11702       finish_case_label (EXPR_LOCATION (t),
11703                          RECUR (CASE_LOW (t)),
11704                          RECUR (CASE_HIGH (t)));
11705       break;
11706
11707     case LABEL_EXPR:
11708       {
11709         tree decl = LABEL_EXPR_LABEL (t);
11710         tree label;
11711
11712         label = finish_label_stmt (DECL_NAME (decl));
11713         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11714           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11715       }
11716       break;
11717
11718     case GOTO_EXPR:
11719       tmp = GOTO_DESTINATION (t);
11720       if (TREE_CODE (tmp) != LABEL_DECL)
11721         /* Computed goto's must be tsubst'd into.  On the other hand,
11722            non-computed gotos must not be; the identifier in question
11723            will have no binding.  */
11724         tmp = RECUR (tmp);
11725       else
11726         tmp = DECL_NAME (tmp);
11727       finish_goto_stmt (tmp);
11728       break;
11729
11730     case ASM_EXPR:
11731       tmp = finish_asm_stmt
11732         (ASM_VOLATILE_P (t),
11733          RECUR (ASM_STRING (t)),
11734          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11735          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11736          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11737          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11738       {
11739         tree asm_expr = tmp;
11740         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11741           asm_expr = TREE_OPERAND (asm_expr, 0);
11742         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11743       }
11744       break;
11745
11746     case TRY_BLOCK:
11747       if (CLEANUP_P (t))
11748         {
11749           stmt = begin_try_block ();
11750           RECUR (TRY_STMTS (t));
11751           finish_cleanup_try_block (stmt);
11752           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11753         }
11754       else
11755         {
11756           tree compound_stmt = NULL_TREE;
11757
11758           if (FN_TRY_BLOCK_P (t))
11759             stmt = begin_function_try_block (&compound_stmt);
11760           else
11761             stmt = begin_try_block ();
11762
11763           RECUR (TRY_STMTS (t));
11764
11765           if (FN_TRY_BLOCK_P (t))
11766             finish_function_try_block (stmt);
11767           else
11768             finish_try_block (stmt);
11769
11770           RECUR (TRY_HANDLERS (t));
11771           if (FN_TRY_BLOCK_P (t))
11772             finish_function_handler_sequence (stmt, compound_stmt);
11773           else
11774             finish_handler_sequence (stmt);
11775         }
11776       break;
11777
11778     case HANDLER:
11779       {
11780         tree decl = HANDLER_PARMS (t);
11781
11782         if (decl)
11783           {
11784             decl = tsubst (decl, args, complain, in_decl);
11785             /* Prevent instantiate_decl from trying to instantiate
11786                this variable.  We've already done all that needs to be
11787                done.  */
11788             if (decl != error_mark_node)
11789               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11790           }
11791         stmt = begin_handler ();
11792         finish_handler_parms (decl, stmt);
11793         RECUR (HANDLER_BODY (t));
11794         finish_handler (stmt);
11795       }
11796       break;
11797
11798     case TAG_DEFN:
11799       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11800       break;
11801
11802     case STATIC_ASSERT:
11803       {
11804         tree condition = 
11805           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11806                        args,
11807                        complain, in_decl,
11808                        /*integral_constant_expression_p=*/true);
11809         finish_static_assert (condition,
11810                               STATIC_ASSERT_MESSAGE (t),
11811                               STATIC_ASSERT_SOURCE_LOCATION (t),
11812                               /*member_p=*/false);
11813       }
11814       break;
11815
11816     case OMP_PARALLEL:
11817       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11818                                 args, complain, in_decl);
11819       stmt = begin_omp_parallel ();
11820       RECUR (OMP_PARALLEL_BODY (t));
11821       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11822         = OMP_PARALLEL_COMBINED (t);
11823       break;
11824
11825     case OMP_TASK:
11826       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11827                                 args, complain, in_decl);
11828       stmt = begin_omp_task ();
11829       RECUR (OMP_TASK_BODY (t));
11830       finish_omp_task (tmp, stmt);
11831       break;
11832
11833     case OMP_FOR:
11834       {
11835         tree clauses, body, pre_body;
11836         tree declv, initv, condv, incrv;
11837         int i;
11838
11839         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11840                                       args, complain, in_decl);
11841         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11842         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11843         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11844         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11845
11846         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11847           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11848                                    &clauses, args, complain, in_decl,
11849                                    integral_constant_expression_p);
11850
11851         stmt = begin_omp_structured_block ();
11852
11853         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11854           if (TREE_VEC_ELT (initv, i) == NULL
11855               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11856             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11857           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11858             {
11859               tree init = RECUR (TREE_VEC_ELT (initv, i));
11860               gcc_assert (init == TREE_VEC_ELT (declv, i));
11861               TREE_VEC_ELT (initv, i) = NULL_TREE;
11862             }
11863           else
11864             {
11865               tree decl_expr = TREE_VEC_ELT (initv, i);
11866               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11867               gcc_assert (init != NULL);
11868               TREE_VEC_ELT (initv, i) = RECUR (init);
11869               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11870               RECUR (decl_expr);
11871               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11872             }
11873
11874         pre_body = push_stmt_list ();
11875         RECUR (OMP_FOR_PRE_BODY (t));
11876         pre_body = pop_stmt_list (pre_body);
11877
11878         body = push_stmt_list ();
11879         RECUR (OMP_FOR_BODY (t));
11880         body = pop_stmt_list (body);
11881
11882         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11883                             body, pre_body, clauses);
11884
11885         add_stmt (finish_omp_structured_block (stmt));
11886       }
11887       break;
11888
11889     case OMP_SECTIONS:
11890     case OMP_SINGLE:
11891       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11892       stmt = push_stmt_list ();
11893       RECUR (OMP_BODY (t));
11894       stmt = pop_stmt_list (stmt);
11895
11896       t = copy_node (t);
11897       OMP_BODY (t) = stmt;
11898       OMP_CLAUSES (t) = tmp;
11899       add_stmt (t);
11900       break;
11901
11902     case OMP_SECTION:
11903     case OMP_CRITICAL:
11904     case OMP_MASTER:
11905     case OMP_ORDERED:
11906       stmt = push_stmt_list ();
11907       RECUR (OMP_BODY (t));
11908       stmt = pop_stmt_list (stmt);
11909
11910       t = copy_node (t);
11911       OMP_BODY (t) = stmt;
11912       add_stmt (t);
11913       break;
11914
11915     case OMP_ATOMIC:
11916       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11917       {
11918         tree op1 = TREE_OPERAND (t, 1);
11919         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11920         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11921         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11922       }
11923       break;
11924
11925     case EXPR_PACK_EXPANSION:
11926       error ("invalid use of pack expansion expression");
11927       return error_mark_node;
11928
11929     case NONTYPE_ARGUMENT_PACK:
11930       error ("use %<...%> to expand argument pack");
11931       return error_mark_node;
11932
11933     default:
11934       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11935
11936       return tsubst_copy_and_build (t, args, complain, in_decl,
11937                                     /*function_p=*/false,
11938                                     integral_constant_expression_p);
11939     }
11940
11941   return NULL_TREE;
11942 #undef RECUR
11943 }
11944
11945 /* T is a postfix-expression that is not being used in a function
11946    call.  Return the substituted version of T.  */
11947
11948 static tree
11949 tsubst_non_call_postfix_expression (tree t, tree args,
11950                                     tsubst_flags_t complain,
11951                                     tree in_decl)
11952 {
11953   if (TREE_CODE (t) == SCOPE_REF)
11954     t = tsubst_qualified_id (t, args, complain, in_decl,
11955                              /*done=*/false, /*address_p=*/false);
11956   else
11957     t = tsubst_copy_and_build (t, args, complain, in_decl,
11958                                /*function_p=*/false,
11959                                /*integral_constant_expression_p=*/false);
11960
11961   return t;
11962 }
11963
11964 /* Like tsubst but deals with expressions and performs semantic
11965    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11966
11967 tree
11968 tsubst_copy_and_build (tree t,
11969                        tree args,
11970                        tsubst_flags_t complain,
11971                        tree in_decl,
11972                        bool function_p,
11973                        bool integral_constant_expression_p)
11974 {
11975 #define RECUR(NODE)                                             \
11976   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11977                          /*function_p=*/false,                  \
11978                          integral_constant_expression_p)
11979
11980   tree op1;
11981
11982   if (t == NULL_TREE || t == error_mark_node)
11983     return t;
11984
11985   switch (TREE_CODE (t))
11986     {
11987     case USING_DECL:
11988       t = DECL_NAME (t);
11989       /* Fall through.  */
11990     case IDENTIFIER_NODE:
11991       {
11992         tree decl;
11993         cp_id_kind idk;
11994         bool non_integral_constant_expression_p;
11995         const char *error_msg;
11996
11997         if (IDENTIFIER_TYPENAME_P (t))
11998           {
11999             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12000             t = mangle_conv_op_name_for_type (new_type);
12001           }
12002
12003         /* Look up the name.  */
12004         decl = lookup_name (t);
12005
12006         /* By convention, expressions use ERROR_MARK_NODE to indicate
12007            failure, not NULL_TREE.  */
12008         if (decl == NULL_TREE)
12009           decl = error_mark_node;
12010
12011         decl = finish_id_expression (t, decl, NULL_TREE,
12012                                      &idk,
12013                                      integral_constant_expression_p,
12014                                      /*allow_non_integral_constant_expression_p=*/false,
12015                                      &non_integral_constant_expression_p,
12016                                      /*template_p=*/false,
12017                                      /*done=*/true,
12018                                      /*address_p=*/false,
12019                                      /*template_arg_p=*/false,
12020                                      &error_msg,
12021                                      input_location);
12022         if (error_msg)
12023           error (error_msg);
12024         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12025           decl = unqualified_name_lookup_error (decl);
12026         return decl;
12027       }
12028
12029     case TEMPLATE_ID_EXPR:
12030       {
12031         tree object;
12032         tree templ = RECUR (TREE_OPERAND (t, 0));
12033         tree targs = TREE_OPERAND (t, 1);
12034
12035         if (targs)
12036           targs = tsubst_template_args (targs, args, complain, in_decl);
12037
12038         if (TREE_CODE (templ) == COMPONENT_REF)
12039           {
12040             object = TREE_OPERAND (templ, 0);
12041             templ = TREE_OPERAND (templ, 1);
12042           }
12043         else
12044           object = NULL_TREE;
12045         templ = lookup_template_function (templ, targs);
12046
12047         if (object)
12048           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12049                          object, templ, NULL_TREE);
12050         else
12051           return baselink_for_fns (templ);
12052       }
12053
12054     case INDIRECT_REF:
12055       {
12056         tree r = RECUR (TREE_OPERAND (t, 0));
12057
12058         if (REFERENCE_REF_P (t))
12059           {
12060             /* A type conversion to reference type will be enclosed in
12061                such an indirect ref, but the substitution of the cast
12062                will have also added such an indirect ref.  */
12063             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12064               r = convert_from_reference (r);
12065           }
12066         else
12067           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12068         return r;
12069       }
12070
12071     case NOP_EXPR:
12072       return build_nop
12073         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12074          RECUR (TREE_OPERAND (t, 0)));
12075
12076     case CAST_EXPR:
12077     case REINTERPRET_CAST_EXPR:
12078     case CONST_CAST_EXPR:
12079     case DYNAMIC_CAST_EXPR:
12080     case STATIC_CAST_EXPR:
12081       {
12082         tree type;
12083         tree op;
12084
12085         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12086         if (integral_constant_expression_p
12087             && !cast_valid_in_integral_constant_expression_p (type))
12088           {
12089             if (complain & tf_error)
12090               error ("a cast to a type other than an integral or "
12091                      "enumeration type cannot appear in a constant-expression");
12092             return error_mark_node; 
12093           }
12094
12095         op = RECUR (TREE_OPERAND (t, 0));
12096
12097         switch (TREE_CODE (t))
12098           {
12099           case CAST_EXPR:
12100             return build_functional_cast (type, op, complain);
12101           case REINTERPRET_CAST_EXPR:
12102             return build_reinterpret_cast (type, op, complain);
12103           case CONST_CAST_EXPR:
12104             return build_const_cast (type, op, complain);
12105           case DYNAMIC_CAST_EXPR:
12106             return build_dynamic_cast (type, op, complain);
12107           case STATIC_CAST_EXPR:
12108             return build_static_cast (type, op, complain);
12109           default:
12110             gcc_unreachable ();
12111           }
12112       }
12113
12114     case POSTDECREMENT_EXPR:
12115     case POSTINCREMENT_EXPR:
12116       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12117                                                 args, complain, in_decl);
12118       return build_x_unary_op (TREE_CODE (t), op1, complain);
12119
12120     case PREDECREMENT_EXPR:
12121     case PREINCREMENT_EXPR:
12122     case NEGATE_EXPR:
12123     case BIT_NOT_EXPR:
12124     case ABS_EXPR:
12125     case TRUTH_NOT_EXPR:
12126     case UNARY_PLUS_EXPR:  /* Unary + */
12127     case REALPART_EXPR:
12128     case IMAGPART_EXPR:
12129       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12130                                complain);
12131
12132     case ADDR_EXPR:
12133       op1 = TREE_OPERAND (t, 0);
12134       if (TREE_CODE (op1) == SCOPE_REF)
12135         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12136                                    /*done=*/true, /*address_p=*/true);
12137       else
12138         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12139                                                   in_decl);
12140       if (TREE_CODE (op1) == LABEL_DECL)
12141         return finish_label_address_expr (DECL_NAME (op1),
12142                                           EXPR_LOCATION (op1));
12143       return build_x_unary_op (ADDR_EXPR, op1, complain);
12144
12145     case PLUS_EXPR:
12146     case MINUS_EXPR:
12147     case MULT_EXPR:
12148     case TRUNC_DIV_EXPR:
12149     case CEIL_DIV_EXPR:
12150     case FLOOR_DIV_EXPR:
12151     case ROUND_DIV_EXPR:
12152     case EXACT_DIV_EXPR:
12153     case BIT_AND_EXPR:
12154     case BIT_IOR_EXPR:
12155     case BIT_XOR_EXPR:
12156     case TRUNC_MOD_EXPR:
12157     case FLOOR_MOD_EXPR:
12158     case TRUTH_ANDIF_EXPR:
12159     case TRUTH_ORIF_EXPR:
12160     case TRUTH_AND_EXPR:
12161     case TRUTH_OR_EXPR:
12162     case RSHIFT_EXPR:
12163     case LSHIFT_EXPR:
12164     case RROTATE_EXPR:
12165     case LROTATE_EXPR:
12166     case EQ_EXPR:
12167     case NE_EXPR:
12168     case MAX_EXPR:
12169     case MIN_EXPR:
12170     case LE_EXPR:
12171     case GE_EXPR:
12172     case LT_EXPR:
12173     case GT_EXPR:
12174     case MEMBER_REF:
12175     case DOTSTAR_EXPR:
12176       return build_x_binary_op
12177         (TREE_CODE (t),
12178          RECUR (TREE_OPERAND (t, 0)),
12179          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12180           ? ERROR_MARK
12181           : TREE_CODE (TREE_OPERAND (t, 0))),
12182          RECUR (TREE_OPERAND (t, 1)),
12183          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12184           ? ERROR_MARK
12185           : TREE_CODE (TREE_OPERAND (t, 1))),
12186          /*overloaded_p=*/NULL,
12187          complain);
12188
12189     case SCOPE_REF:
12190       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12191                                   /*address_p=*/false);
12192     case ARRAY_REF:
12193       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12194                                                 args, complain, in_decl);
12195       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12196
12197     case SIZEOF_EXPR:
12198       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12199         return tsubst_copy (t, args, complain, in_decl);
12200       /* Fall through */
12201       
12202     case ALIGNOF_EXPR:
12203       op1 = TREE_OPERAND (t, 0);
12204       if (!args)
12205         {
12206           /* When there are no ARGS, we are trying to evaluate a
12207              non-dependent expression from the parser.  Trying to do
12208              the substitutions may not work.  */
12209           if (!TYPE_P (op1))
12210             op1 = TREE_TYPE (op1);
12211         }
12212       else
12213         {
12214           ++cp_unevaluated_operand;
12215           ++c_inhibit_evaluation_warnings;
12216           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12217                                        /*function_p=*/false,
12218                                        /*integral_constant_expression_p=*/false);
12219           --cp_unevaluated_operand;
12220           --c_inhibit_evaluation_warnings;
12221         }
12222       if (TYPE_P (op1))
12223         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12224                                            complain & tf_error);
12225       else
12226         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12227                                            complain & tf_error);
12228
12229     case MODOP_EXPR:
12230       {
12231         tree r = build_x_modify_expr
12232           (RECUR (TREE_OPERAND (t, 0)),
12233            TREE_CODE (TREE_OPERAND (t, 1)),
12234            RECUR (TREE_OPERAND (t, 2)),
12235            complain);
12236         /* TREE_NO_WARNING must be set if either the expression was
12237            parenthesized or it uses an operator such as >>= rather
12238            than plain assignment.  In the former case, it was already
12239            set and must be copied.  In the latter case,
12240            build_x_modify_expr sets it and it must not be reset
12241            here.  */
12242         if (TREE_NO_WARNING (t))
12243           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12244         return r;
12245       }
12246
12247     case ARROW_EXPR:
12248       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12249                                                 args, complain, in_decl);
12250       /* Remember that there was a reference to this entity.  */
12251       if (DECL_P (op1))
12252         mark_used (op1);
12253       return build_x_arrow (op1);
12254
12255     case NEW_EXPR:
12256       {
12257         tree placement = RECUR (TREE_OPERAND (t, 0));
12258         tree init = RECUR (TREE_OPERAND (t, 3));
12259         VEC(tree,gc) *placement_vec;
12260         VEC(tree,gc) *init_vec;
12261         tree ret;
12262
12263         if (placement == NULL_TREE)
12264           placement_vec = NULL;
12265         else
12266           {
12267             placement_vec = make_tree_vector ();
12268             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12269               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12270           }
12271
12272         /* If there was an initializer in the original tree, but it
12273            instantiated to an empty list, then we should pass a
12274            non-NULL empty vector to tell build_new that it was an
12275            empty initializer() rather than no initializer.  This can
12276            only happen when the initializer is a pack expansion whose
12277            parameter packs are of length zero.  */
12278         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12279           init_vec = NULL;
12280         else
12281           {
12282             init_vec = make_tree_vector ();
12283             if (init == void_zero_node)
12284               gcc_assert (init_vec != NULL);
12285             else
12286               {
12287                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12288                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12289               }
12290           }
12291
12292         ret = build_new (&placement_vec,
12293                          RECUR (TREE_OPERAND (t, 1)),
12294                          RECUR (TREE_OPERAND (t, 2)),
12295                          &init_vec,
12296                          NEW_EXPR_USE_GLOBAL (t),
12297                          complain);
12298
12299         if (placement_vec != NULL)
12300           release_tree_vector (placement_vec);
12301         if (init_vec != NULL)
12302           release_tree_vector (init_vec);
12303
12304         return ret;
12305       }
12306
12307     case DELETE_EXPR:
12308      return delete_sanity
12309        (RECUR (TREE_OPERAND (t, 0)),
12310         RECUR (TREE_OPERAND (t, 1)),
12311         DELETE_EXPR_USE_VEC (t),
12312         DELETE_EXPR_USE_GLOBAL (t));
12313
12314     case COMPOUND_EXPR:
12315       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12316                                     RECUR (TREE_OPERAND (t, 1)),
12317                                     complain);
12318
12319     case CALL_EXPR:
12320       {
12321         tree function;
12322         VEC(tree,gc) *call_args;
12323         unsigned int nargs, i;
12324         bool qualified_p;
12325         bool koenig_p;
12326         tree ret;
12327
12328         function = CALL_EXPR_FN (t);
12329         /* When we parsed the expression,  we determined whether or
12330            not Koenig lookup should be performed.  */
12331         koenig_p = KOENIG_LOOKUP_P (t);
12332         if (TREE_CODE (function) == SCOPE_REF)
12333           {
12334             qualified_p = true;
12335             function = tsubst_qualified_id (function, args, complain, in_decl,
12336                                             /*done=*/false,
12337                                             /*address_p=*/false);
12338           }
12339         else
12340           {
12341             if (TREE_CODE (function) == COMPONENT_REF)
12342               {
12343                 tree op = TREE_OPERAND (function, 1);
12344
12345                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12346                                || (BASELINK_P (op)
12347                                    && BASELINK_QUALIFIED_P (op)));
12348               }
12349             else
12350               qualified_p = false;
12351
12352             function = tsubst_copy_and_build (function, args, complain,
12353                                               in_decl,
12354                                               !qualified_p,
12355                                               integral_constant_expression_p);
12356
12357             if (BASELINK_P (function))
12358               qualified_p = true;
12359           }
12360
12361         nargs = call_expr_nargs (t);
12362         call_args = make_tree_vector ();
12363         for (i = 0; i < nargs; ++i)
12364           {
12365             tree arg = CALL_EXPR_ARG (t, i);
12366
12367             if (!PACK_EXPANSION_P (arg))
12368               VEC_safe_push (tree, gc, call_args,
12369                              RECUR (CALL_EXPR_ARG (t, i)));
12370             else
12371               {
12372                 /* Expand the pack expansion and push each entry onto
12373                    CALL_ARGS.  */
12374                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12375                 if (TREE_CODE (arg) == TREE_VEC)
12376                   {
12377                     unsigned int len, j;
12378
12379                     len = TREE_VEC_LENGTH (arg);
12380                     for (j = 0; j < len; ++j)
12381                       {
12382                         tree value = TREE_VEC_ELT (arg, j);
12383                         if (value != NULL_TREE)
12384                           value = convert_from_reference (value);
12385                         VEC_safe_push (tree, gc, call_args, value);
12386                       }
12387                   }
12388                 else
12389                   {
12390                     /* A partial substitution.  Add one entry.  */
12391                     VEC_safe_push (tree, gc, call_args, arg);
12392                   }
12393               }
12394           }
12395
12396         /* We do not perform argument-dependent lookup if normal
12397            lookup finds a non-function, in accordance with the
12398            expected resolution of DR 218.  */
12399         if (koenig_p
12400             && ((is_overloaded_fn (function)
12401                  /* If lookup found a member function, the Koenig lookup is
12402                     not appropriate, even if an unqualified-name was used
12403                     to denote the function.  */
12404                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12405                 || TREE_CODE (function) == IDENTIFIER_NODE)
12406             /* Only do this when substitution turns a dependent call
12407                into a non-dependent call.  */
12408             && type_dependent_expression_p_push (t)
12409             && !any_type_dependent_arguments_p (call_args))
12410           function = perform_koenig_lookup (function, call_args);
12411
12412         if (TREE_CODE (function) == IDENTIFIER_NODE)
12413           {
12414             unqualified_name_lookup_error (function);
12415             release_tree_vector (call_args);
12416             return error_mark_node;
12417           }
12418
12419         /* Remember that there was a reference to this entity.  */
12420         if (DECL_P (function))
12421           mark_used (function);
12422
12423         if (TREE_CODE (function) == OFFSET_REF)
12424           ret = build_offset_ref_call_from_tree (function, &call_args);
12425         else if (TREE_CODE (function) == COMPONENT_REF)
12426           {
12427             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12428               ret = finish_call_expr (function, &call_args,
12429                                        /*disallow_virtual=*/false,
12430                                        /*koenig_p=*/false,
12431                                        complain);
12432             else
12433               ret = (build_new_method_call
12434                       (TREE_OPERAND (function, 0),
12435                        TREE_OPERAND (function, 1),
12436                        &call_args, NULL_TREE,
12437                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12438                        /*fn_p=*/NULL,
12439                        complain));
12440           }
12441         else
12442           ret = finish_call_expr (function, &call_args,
12443                                   /*disallow_virtual=*/qualified_p,
12444                                   koenig_p,
12445                                   complain);
12446
12447         release_tree_vector (call_args);
12448
12449         return ret;
12450       }
12451
12452     case COND_EXPR:
12453       return build_x_conditional_expr
12454         (RECUR (TREE_OPERAND (t, 0)),
12455          RECUR (TREE_OPERAND (t, 1)),
12456          RECUR (TREE_OPERAND (t, 2)),
12457          complain);
12458
12459     case PSEUDO_DTOR_EXPR:
12460       return finish_pseudo_destructor_expr
12461         (RECUR (TREE_OPERAND (t, 0)),
12462          RECUR (TREE_OPERAND (t, 1)),
12463          RECUR (TREE_OPERAND (t, 2)));
12464
12465     case TREE_LIST:
12466       {
12467         tree purpose, value, chain;
12468
12469         if (t == void_list_node)
12470           return t;
12471
12472         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12473             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12474           {
12475             /* We have pack expansions, so expand those and
12476                create a new list out of it.  */
12477             tree purposevec = NULL_TREE;
12478             tree valuevec = NULL_TREE;
12479             tree chain;
12480             int i, len = -1;
12481
12482             /* Expand the argument expressions.  */
12483             if (TREE_PURPOSE (t))
12484               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12485                                                  complain, in_decl);
12486             if (TREE_VALUE (t))
12487               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12488                                                complain, in_decl);
12489
12490             /* Build the rest of the list.  */
12491             chain = TREE_CHAIN (t);
12492             if (chain && chain != void_type_node)
12493               chain = RECUR (chain);
12494
12495             /* Determine the number of arguments.  */
12496             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12497               {
12498                 len = TREE_VEC_LENGTH (purposevec);
12499                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12500               }
12501             else if (TREE_CODE (valuevec) == TREE_VEC)
12502               len = TREE_VEC_LENGTH (valuevec);
12503             else
12504               {
12505                 /* Since we only performed a partial substitution into
12506                    the argument pack, we only return a single list
12507                    node.  */
12508                 if (purposevec == TREE_PURPOSE (t)
12509                     && valuevec == TREE_VALUE (t)
12510                     && chain == TREE_CHAIN (t))
12511                   return t;
12512
12513                 return tree_cons (purposevec, valuevec, chain);
12514               }
12515             
12516             /* Convert the argument vectors into a TREE_LIST */
12517             i = len;
12518             while (i > 0)
12519               {
12520                 /* Grab the Ith values.  */
12521                 i--;
12522                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12523                                      : NULL_TREE;
12524                 value 
12525                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12526                              : NULL_TREE;
12527
12528                 /* Build the list (backwards).  */
12529                 chain = tree_cons (purpose, value, chain);
12530               }
12531
12532             return chain;
12533           }
12534
12535         purpose = TREE_PURPOSE (t);
12536         if (purpose)
12537           purpose = RECUR (purpose);
12538         value = TREE_VALUE (t);
12539         if (value)
12540           value = RECUR (value);
12541         chain = TREE_CHAIN (t);
12542         if (chain && chain != void_type_node)
12543           chain = RECUR (chain);
12544         if (purpose == TREE_PURPOSE (t)
12545             && value == TREE_VALUE (t)
12546             && chain == TREE_CHAIN (t))
12547           return t;
12548         return tree_cons (purpose, value, chain);
12549       }
12550
12551     case COMPONENT_REF:
12552       {
12553         tree object;
12554         tree object_type;
12555         tree member;
12556
12557         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12558                                                      args, complain, in_decl);
12559         /* Remember that there was a reference to this entity.  */
12560         if (DECL_P (object))
12561           mark_used (object);
12562         object_type = TREE_TYPE (object);
12563
12564         member = TREE_OPERAND (t, 1);
12565         if (BASELINK_P (member))
12566           member = tsubst_baselink (member,
12567                                     non_reference (TREE_TYPE (object)),
12568                                     args, complain, in_decl);
12569         else
12570           member = tsubst_copy (member, args, complain, in_decl);
12571         if (member == error_mark_node)
12572           return error_mark_node;
12573
12574         if (object_type && !CLASS_TYPE_P (object_type))
12575           {
12576             if (SCALAR_TYPE_P (object_type))
12577               {
12578                 tree s = NULL_TREE;
12579                 tree dtor = member;
12580
12581                 if (TREE_CODE (dtor) == SCOPE_REF)
12582                   {
12583                     s = TREE_OPERAND (dtor, 0);
12584                     dtor = TREE_OPERAND (dtor, 1);
12585                   }
12586                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12587                   {
12588                     dtor = TREE_OPERAND (dtor, 0);
12589                     if (TYPE_P (dtor))
12590                       return finish_pseudo_destructor_expr (object, s, dtor);
12591                   }
12592               }
12593           }
12594         else if (TREE_CODE (member) == SCOPE_REF
12595                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12596           {
12597             tree tmpl;
12598             tree args;
12599
12600             /* Lookup the template functions now that we know what the
12601                scope is.  */
12602             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12603             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12604             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12605                                             /*is_type_p=*/false,
12606                                             /*complain=*/false);
12607             if (BASELINK_P (member))
12608               {
12609                 BASELINK_FUNCTIONS (member)
12610                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12611                               args);
12612                 member = (adjust_result_of_qualified_name_lookup
12613                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12614                            object_type));
12615               }
12616             else
12617               {
12618                 qualified_name_lookup_error (object_type, tmpl, member,
12619                                              input_location);
12620                 return error_mark_node;
12621               }
12622           }
12623         else if (TREE_CODE (member) == SCOPE_REF
12624                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12625                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12626           {
12627             if (complain & tf_error)
12628               {
12629                 if (TYPE_P (TREE_OPERAND (member, 0)))
12630                   error ("%qT is not a class or namespace",
12631                          TREE_OPERAND (member, 0));
12632                 else
12633                   error ("%qD is not a class or namespace",
12634                          TREE_OPERAND (member, 0));
12635               }
12636             return error_mark_node;
12637           }
12638         else if (TREE_CODE (member) == FIELD_DECL)
12639           return finish_non_static_data_member (member, object, NULL_TREE);
12640
12641         return finish_class_member_access_expr (object, member,
12642                                                 /*template_p=*/false,
12643                                                 complain);
12644       }
12645
12646     case THROW_EXPR:
12647       return build_throw
12648         (RECUR (TREE_OPERAND (t, 0)));
12649
12650     case CONSTRUCTOR:
12651       {
12652         VEC(constructor_elt,gc) *n;
12653         constructor_elt *ce;
12654         unsigned HOST_WIDE_INT idx;
12655         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12656         bool process_index_p;
12657         int newlen;
12658         bool need_copy_p = false;
12659         tree r;
12660
12661         if (type == error_mark_node)
12662           return error_mark_node;
12663
12664         /* digest_init will do the wrong thing if we let it.  */
12665         if (type && TYPE_PTRMEMFUNC_P (type))
12666           return t;
12667
12668         /* We do not want to process the index of aggregate
12669            initializers as they are identifier nodes which will be
12670            looked up by digest_init.  */
12671         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12672
12673         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12674         newlen = VEC_length (constructor_elt, n);
12675         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12676           {
12677             if (ce->index && process_index_p)
12678               ce->index = RECUR (ce->index);
12679
12680             if (PACK_EXPANSION_P (ce->value))
12681               {
12682                 /* Substitute into the pack expansion.  */
12683                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12684                                                   in_decl);
12685
12686                 if (ce->value == error_mark_node)
12687                   ;
12688                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12689                   /* Just move the argument into place.  */
12690                   ce->value = TREE_VEC_ELT (ce->value, 0);
12691                 else
12692                   {
12693                     /* Update the length of the final CONSTRUCTOR
12694                        arguments vector, and note that we will need to
12695                        copy.*/
12696                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12697                     need_copy_p = true;
12698                   }
12699               }
12700             else
12701               ce->value = RECUR (ce->value);
12702           }
12703
12704         if (need_copy_p)
12705           {
12706             VEC(constructor_elt,gc) *old_n = n;
12707
12708             n = VEC_alloc (constructor_elt, gc, newlen);
12709             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12710                  idx++)
12711               {
12712                 if (TREE_CODE (ce->value) == TREE_VEC)
12713                   {
12714                     int i, len = TREE_VEC_LENGTH (ce->value);
12715                     for (i = 0; i < len; ++i)
12716                       CONSTRUCTOR_APPEND_ELT (n, 0,
12717                                               TREE_VEC_ELT (ce->value, i));
12718                   }
12719                 else
12720                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12721               }
12722           }
12723
12724         r = build_constructor (init_list_type_node, n);
12725         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12726
12727         if (TREE_HAS_CONSTRUCTOR (t))
12728           return finish_compound_literal (type, r);
12729
12730         return r;
12731       }
12732
12733     case TYPEID_EXPR:
12734       {
12735         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12736         if (TYPE_P (operand_0))
12737           return get_typeid (operand_0);
12738         return build_typeid (operand_0);
12739       }
12740
12741     case VAR_DECL:
12742       if (!args)
12743         return t;
12744       /* Fall through */
12745
12746     case PARM_DECL:
12747       {
12748         tree r = tsubst_copy (t, args, complain, in_decl);
12749
12750         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12751           /* If the original type was a reference, we'll be wrapped in
12752              the appropriate INDIRECT_REF.  */
12753           r = convert_from_reference (r);
12754         return r;
12755       }
12756
12757     case VA_ARG_EXPR:
12758       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12759                              tsubst_copy (TREE_TYPE (t), args, complain,
12760                                           in_decl));
12761
12762     case OFFSETOF_EXPR:
12763       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12764
12765     case TRAIT_EXPR:
12766       {
12767         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12768                                   complain, in_decl);
12769
12770         tree type2 = TRAIT_EXPR_TYPE2 (t);
12771         if (type2)
12772           type2 = tsubst_copy (type2, args, complain, in_decl);
12773         
12774         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12775       }
12776
12777     case STMT_EXPR:
12778       {
12779         tree old_stmt_expr = cur_stmt_expr;
12780         tree stmt_expr = begin_stmt_expr ();
12781
12782         cur_stmt_expr = stmt_expr;
12783         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12784                      integral_constant_expression_p);
12785         stmt_expr = finish_stmt_expr (stmt_expr, false);
12786         cur_stmt_expr = old_stmt_expr;
12787
12788         /* If the resulting list of expression statement is empty,
12789            fold it further into void_zero_node.  */
12790         if (empty_expr_stmt_p (stmt_expr))
12791           stmt_expr = void_zero_node;
12792
12793         return stmt_expr;
12794       }
12795
12796     case CONST_DECL:
12797       t = tsubst_copy (t, args, complain, in_decl);
12798       /* As in finish_id_expression, we resolve enumeration constants
12799          to their underlying values.  */
12800       if (TREE_CODE (t) == CONST_DECL)
12801         {
12802           used_types_insert (TREE_TYPE (t));
12803           return DECL_INITIAL (t);
12804         }
12805       return t;
12806
12807     case LAMBDA_EXPR:
12808       {
12809         tree r = build_lambda_expr ();
12810
12811         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12812         TREE_TYPE (r) = type;
12813         CLASSTYPE_LAMBDA_EXPR (type) = r;
12814
12815         LAMBDA_EXPR_LOCATION (r)
12816           = LAMBDA_EXPR_LOCATION (t);
12817         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12818           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12819         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12820         LAMBDA_EXPR_DISCRIMINATOR (r)
12821           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12822         LAMBDA_EXPR_CAPTURE_LIST (r)
12823           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12824         LAMBDA_EXPR_THIS_CAPTURE (r)
12825           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12826         LAMBDA_EXPR_EXTRA_SCOPE (r)
12827           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12828
12829         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12830         determine_visibility (TYPE_NAME (type));
12831         /* Now that we know visibility, instantiate the type so we have a
12832            declaration of the op() for later calls to lambda_function.  */
12833         complete_type (type);
12834
12835         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12836         if (type)
12837           apply_lambda_return_type (r, type);
12838
12839         return build_lambda_object (r);
12840       }
12841
12842     default:
12843       /* Handle Objective-C++ constructs, if appropriate.  */
12844       {
12845         tree subst
12846           = objcp_tsubst_copy_and_build (t, args, complain,
12847                                          in_decl, /*function_p=*/false);
12848         if (subst)
12849           return subst;
12850       }
12851       return tsubst_copy (t, args, complain, in_decl);
12852     }
12853
12854 #undef RECUR
12855 }
12856
12857 /* Verify that the instantiated ARGS are valid. For type arguments,
12858    make sure that the type's linkage is ok. For non-type arguments,
12859    make sure they are constants if they are integral or enumerations.
12860    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12861
12862 static bool
12863 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12864 {
12865   if (ARGUMENT_PACK_P (t))
12866     {
12867       tree vec = ARGUMENT_PACK_ARGS (t);
12868       int len = TREE_VEC_LENGTH (vec);
12869       bool result = false;
12870       int i;
12871
12872       for (i = 0; i < len; ++i)
12873         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12874           result = true;
12875       return result;
12876     }
12877   else if (TYPE_P (t))
12878     {
12879       /* [basic.link]: A name with no linkage (notably, the name
12880          of a class or enumeration declared in a local scope)
12881          shall not be used to declare an entity with linkage.
12882          This implies that names with no linkage cannot be used as
12883          template arguments
12884
12885          DR 757 relaxes this restriction for C++0x.  */
12886       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12887                  : no_linkage_check (t, /*relaxed_p=*/false));
12888
12889       if (nt)
12890         {
12891           /* DR 488 makes use of a type with no linkage cause
12892              type deduction to fail.  */
12893           if (complain & tf_error)
12894             {
12895               if (TYPE_ANONYMOUS_P (nt))
12896                 error ("%qT is/uses anonymous type", t);
12897               else
12898                 error ("template argument for %qD uses local type %qT",
12899                        tmpl, t);
12900             }
12901           return true;
12902         }
12903       /* In order to avoid all sorts of complications, we do not
12904          allow variably-modified types as template arguments.  */
12905       else if (variably_modified_type_p (t, NULL_TREE))
12906         {
12907           if (complain & tf_error)
12908             error ("%qT is a variably modified type", t);
12909           return true;
12910         }
12911     }
12912   /* A non-type argument of integral or enumerated type must be a
12913      constant.  */
12914   else if (TREE_TYPE (t)
12915            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12916            && !TREE_CONSTANT (t))
12917     {
12918       if (complain & tf_error)
12919         error ("integral expression %qE is not constant", t);
12920       return true;
12921     }
12922   return false;
12923 }
12924
12925 static bool
12926 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12927 {
12928   int ix, len = DECL_NTPARMS (tmpl);
12929   bool result = false;
12930
12931   for (ix = 0; ix != len; ix++)
12932     {
12933       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12934         result = true;
12935     }
12936   if (result && (complain & tf_error))
12937     error ("  trying to instantiate %qD", tmpl);
12938   return result;
12939 }
12940
12941 /* Instantiate the indicated variable or function template TMPL with
12942    the template arguments in TARG_PTR.  */
12943
12944 tree
12945 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12946 {
12947   tree targ_ptr = orig_args;
12948   tree fndecl;
12949   tree gen_tmpl;
12950   tree spec;
12951   HOST_WIDE_INT saved_processing_template_decl;
12952
12953   if (tmpl == error_mark_node)
12954     return error_mark_node;
12955
12956   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12957
12958   /* If this function is a clone, handle it specially.  */
12959   if (DECL_CLONED_FUNCTION_P (tmpl))
12960     {
12961       tree spec;
12962       tree clone;
12963
12964       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12965          DECL_CLONED_FUNCTION.  */
12966       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12967                                    targ_ptr, complain);
12968       if (spec == error_mark_node)
12969         return error_mark_node;
12970
12971       /* Look for the clone.  */
12972       FOR_EACH_CLONE (clone, spec)
12973         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12974           return clone;
12975       /* We should always have found the clone by now.  */
12976       gcc_unreachable ();
12977       return NULL_TREE;
12978     }
12979
12980   /* Check to see if we already have this specialization.  */
12981   gen_tmpl = most_general_template (tmpl);
12982   if (tmpl != gen_tmpl)
12983     /* The TMPL is a partial instantiation.  To get a full set of
12984        arguments we must add the arguments used to perform the
12985        partial instantiation.  */
12986     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12987                                             targ_ptr);
12988
12989   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12990      but it doesn't seem to be on the hot path.  */
12991   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12992
12993   gcc_assert (tmpl == gen_tmpl
12994               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12995                   == spec)
12996               || fndecl == NULL_TREE);
12997
12998   if (spec != NULL_TREE)
12999     return spec;
13000
13001   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13002                                complain))
13003     return error_mark_node;
13004
13005   /* We are building a FUNCTION_DECL, during which the access of its
13006      parameters and return types have to be checked.  However this
13007      FUNCTION_DECL which is the desired context for access checking
13008      is not built yet.  We solve this chicken-and-egg problem by
13009      deferring all checks until we have the FUNCTION_DECL.  */
13010   push_deferring_access_checks (dk_deferred);
13011
13012   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13013      (because, for example, we have encountered a non-dependent
13014      function call in the body of a template function and must now
13015      determine which of several overloaded functions will be called),
13016      within the instantiation itself we are not processing a
13017      template.  */  
13018   saved_processing_template_decl = processing_template_decl;
13019   processing_template_decl = 0;
13020   /* Substitute template parameters to obtain the specialization.  */
13021   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13022                    targ_ptr, complain, gen_tmpl);
13023   processing_template_decl = saved_processing_template_decl;
13024   if (fndecl == error_mark_node)
13025     return error_mark_node;
13026
13027   /* Now we know the specialization, compute access previously
13028      deferred.  */
13029   push_access_scope (fndecl);
13030
13031   /* Some typedefs referenced from within the template code need to be access
13032      checked at template instantiation time, i.e now. These types were
13033      added to the template at parsing time. Let's get those and perfom
13034      the acces checks then.  */
13035   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13036   perform_deferred_access_checks ();
13037   pop_access_scope (fndecl);
13038   pop_deferring_access_checks ();
13039
13040   /* The DECL_TI_TEMPLATE should always be the immediate parent
13041      template, not the most general template.  */
13042   DECL_TI_TEMPLATE (fndecl) = tmpl;
13043
13044   /* If we've just instantiated the main entry point for a function,
13045      instantiate all the alternate entry points as well.  We do this
13046      by cloning the instantiation of the main entry point, not by
13047      instantiating the template clones.  */
13048   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13049     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13050
13051   return fndecl;
13052 }
13053
13054 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13055    NARGS elements of the arguments that are being used when calling
13056    it.  TARGS is a vector into which the deduced template arguments
13057    are placed.
13058
13059    Return zero for success, 2 for an incomplete match that doesn't resolve
13060    all the types, and 1 for complete failure.  An error message will be
13061    printed only for an incomplete match.
13062
13063    If FN is a conversion operator, or we are trying to produce a specific
13064    specialization, RETURN_TYPE is the return type desired.
13065
13066    The EXPLICIT_TARGS are explicit template arguments provided via a
13067    template-id.
13068
13069    The parameter STRICT is one of:
13070
13071    DEDUCE_CALL:
13072      We are deducing arguments for a function call, as in
13073      [temp.deduct.call].
13074
13075    DEDUCE_CONV:
13076      We are deducing arguments for a conversion function, as in
13077      [temp.deduct.conv].
13078
13079    DEDUCE_EXACT:
13080      We are deducing arguments when doing an explicit instantiation
13081      as in [temp.explicit], when determining an explicit specialization
13082      as in [temp.expl.spec], or when taking the address of a function
13083      template, as in [temp.deduct.funcaddr].  */
13084
13085 int
13086 fn_type_unification (tree fn,
13087                      tree explicit_targs,
13088                      tree targs,
13089                      const tree *args,
13090                      unsigned int nargs,
13091                      tree return_type,
13092                      unification_kind_t strict,
13093                      int flags)
13094 {
13095   tree parms;
13096   tree fntype;
13097   int result;
13098   bool incomplete_argument_packs_p = false;
13099
13100   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13101
13102   fntype = TREE_TYPE (fn);
13103   if (explicit_targs)
13104     {
13105       /* [temp.deduct]
13106
13107          The specified template arguments must match the template
13108          parameters in kind (i.e., type, nontype, template), and there
13109          must not be more arguments than there are parameters;
13110          otherwise type deduction fails.
13111
13112          Nontype arguments must match the types of the corresponding
13113          nontype template parameters, or must be convertible to the
13114          types of the corresponding nontype parameters as specified in
13115          _temp.arg.nontype_, otherwise type deduction fails.
13116
13117          All references in the function type of the function template
13118          to the corresponding template parameters are replaced by the
13119          specified template argument values.  If a substitution in a
13120          template parameter or in the function type of the function
13121          template results in an invalid type, type deduction fails.  */
13122       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13123       int i, len = TREE_VEC_LENGTH (tparms);
13124       tree converted_args;
13125       bool incomplete = false;
13126
13127       if (explicit_targs == error_mark_node)
13128         return 1;
13129
13130       converted_args
13131         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13132                                   /*require_all_args=*/false,
13133                                   /*use_default_args=*/false));
13134       if (converted_args == error_mark_node)
13135         return 1;
13136
13137       /* Substitute the explicit args into the function type.  This is
13138          necessary so that, for instance, explicitly declared function
13139          arguments can match null pointed constants.  If we were given
13140          an incomplete set of explicit args, we must not do semantic
13141          processing during substitution as we could create partial
13142          instantiations.  */
13143       for (i = 0; i < len; i++)
13144         {
13145           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13146           bool parameter_pack = false;
13147
13148           /* Dig out the actual parm.  */
13149           if (TREE_CODE (parm) == TYPE_DECL
13150               || TREE_CODE (parm) == TEMPLATE_DECL)
13151             {
13152               parm = TREE_TYPE (parm);
13153               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13154             }
13155           else if (TREE_CODE (parm) == PARM_DECL)
13156             {
13157               parm = DECL_INITIAL (parm);
13158               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13159             }
13160
13161           if (parameter_pack)
13162             {
13163               int level, idx;
13164               tree targ;
13165               template_parm_level_and_index (parm, &level, &idx);
13166
13167               /* Mark the argument pack as "incomplete". We could
13168                  still deduce more arguments during unification.  */
13169               targ = TMPL_ARG (converted_args, level, idx);
13170               if (targ)
13171                 {
13172                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13173                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13174                     = ARGUMENT_PACK_ARGS (targ);
13175                 }
13176
13177               /* We have some incomplete argument packs.  */
13178               incomplete_argument_packs_p = true;
13179             }
13180         }
13181
13182       if (incomplete_argument_packs_p)
13183         /* Any substitution is guaranteed to be incomplete if there
13184            are incomplete argument packs, because we can still deduce
13185            more arguments.  */
13186         incomplete = 1;
13187       else
13188         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13189
13190       processing_template_decl += incomplete;
13191       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13192       processing_template_decl -= incomplete;
13193
13194       if (fntype == error_mark_node)
13195         return 1;
13196
13197       /* Place the explicitly specified arguments in TARGS.  */
13198       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13199         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13200     }
13201
13202   /* Never do unification on the 'this' parameter.  */
13203   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13204
13205   if (return_type)
13206     {
13207       tree *new_args;
13208
13209       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13210       new_args = XALLOCAVEC (tree, nargs + 1);
13211       new_args[0] = return_type;
13212       memcpy (new_args + 1, args, nargs * sizeof (tree));
13213       args = new_args;
13214       ++nargs;
13215     }
13216
13217   /* We allow incomplete unification without an error message here
13218      because the standard doesn't seem to explicitly prohibit it.  Our
13219      callers must be ready to deal with unification failures in any
13220      event.  */
13221   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13222                                   targs, parms, args, nargs, /*subr=*/0,
13223                                   strict, flags);
13224
13225   if (result == 0 && incomplete_argument_packs_p)
13226     {
13227       int i, len = NUM_TMPL_ARGS (targs);
13228
13229       /* Clear the "incomplete" flags on all argument packs.  */
13230       for (i = 0; i < len; i++)
13231         {
13232           tree arg = TREE_VEC_ELT (targs, i);
13233           if (ARGUMENT_PACK_P (arg))
13234             {
13235               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13236               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13237             }
13238         }
13239     }
13240
13241   /* Now that we have bindings for all of the template arguments,
13242      ensure that the arguments deduced for the template template
13243      parameters have compatible template parameter lists.  We cannot
13244      check this property before we have deduced all template
13245      arguments, because the template parameter types of a template
13246      template parameter might depend on prior template parameters
13247      deduced after the template template parameter.  The following
13248      ill-formed example illustrates this issue:
13249
13250        template<typename T, template<T> class C> void f(C<5>, T);
13251
13252        template<int N> struct X {};
13253
13254        void g() {
13255          f(X<5>(), 5l); // error: template argument deduction fails
13256        }
13257
13258      The template parameter list of 'C' depends on the template type
13259      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13260      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13261      time that we deduce 'C'.  */
13262   if (result == 0
13263       && !template_template_parm_bindings_ok_p 
13264            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13265     return 1;
13266
13267   if (result == 0)
13268     /* All is well so far.  Now, check:
13269
13270        [temp.deduct]
13271
13272        When all template arguments have been deduced, all uses of
13273        template parameters in nondeduced contexts are replaced with
13274        the corresponding deduced argument values.  If the
13275        substitution results in an invalid type, as described above,
13276        type deduction fails.  */
13277     {
13278       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13279       if (substed == error_mark_node)
13280         return 1;
13281
13282       /* If we're looking for an exact match, check that what we got
13283          is indeed an exact match.  It might not be if some template
13284          parameters are used in non-deduced contexts.  */
13285       if (strict == DEDUCE_EXACT)
13286         {
13287           unsigned int i;
13288
13289           tree sarg
13290             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13291           if (return_type)
13292             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13293           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13294             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13295               return 1;
13296         }
13297     }
13298
13299   return result;
13300 }
13301
13302 /* Adjust types before performing type deduction, as described in
13303    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13304    sections are symmetric.  PARM is the type of a function parameter
13305    or the return type of the conversion function.  ARG is the type of
13306    the argument passed to the call, or the type of the value
13307    initialized with the result of the conversion function.
13308    ARG_EXPR is the original argument expression, which may be null.  */
13309
13310 static int
13311 maybe_adjust_types_for_deduction (unification_kind_t strict,
13312                                   tree* parm,
13313                                   tree* arg,
13314                                   tree arg_expr)
13315 {
13316   int result = 0;
13317
13318   switch (strict)
13319     {
13320     case DEDUCE_CALL:
13321       break;
13322
13323     case DEDUCE_CONV:
13324       {
13325         /* Swap PARM and ARG throughout the remainder of this
13326            function; the handling is precisely symmetric since PARM
13327            will initialize ARG rather than vice versa.  */
13328         tree* temp = parm;
13329         parm = arg;
13330         arg = temp;
13331         break;
13332       }
13333
13334     case DEDUCE_EXACT:
13335       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13336          too, but here handle it by stripping the reference from PARM
13337          rather than by adding it to ARG.  */
13338       if (TREE_CODE (*parm) == REFERENCE_TYPE
13339           && TYPE_REF_IS_RVALUE (*parm)
13340           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13341           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13342           && TREE_CODE (*arg) == REFERENCE_TYPE
13343           && !TYPE_REF_IS_RVALUE (*arg))
13344         *parm = TREE_TYPE (*parm);
13345       /* Nothing else to do in this case.  */
13346       return 0;
13347
13348     default:
13349       gcc_unreachable ();
13350     }
13351
13352   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13353     {
13354       /* [temp.deduct.call]
13355
13356          If P is not a reference type:
13357
13358          --If A is an array type, the pointer type produced by the
13359          array-to-pointer standard conversion (_conv.array_) is
13360          used in place of A for type deduction; otherwise,
13361
13362          --If A is a function type, the pointer type produced by
13363          the function-to-pointer standard conversion
13364          (_conv.func_) is used in place of A for type deduction;
13365          otherwise,
13366
13367          --If A is a cv-qualified type, the top level
13368          cv-qualifiers of A's type are ignored for type
13369          deduction.  */
13370       if (TREE_CODE (*arg) == ARRAY_TYPE)
13371         *arg = build_pointer_type (TREE_TYPE (*arg));
13372       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13373         *arg = build_pointer_type (*arg);
13374       else
13375         *arg = TYPE_MAIN_VARIANT (*arg);
13376     }
13377
13378   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13379      of the form T&&, where T is a template parameter, and the argument
13380      is an lvalue, T is deduced as A& */
13381   if (TREE_CODE (*parm) == REFERENCE_TYPE
13382       && TYPE_REF_IS_RVALUE (*parm)
13383       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13384       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13385       && arg_expr && real_lvalue_p (arg_expr))
13386     *arg = build_reference_type (*arg);
13387
13388   /* [temp.deduct.call]
13389
13390      If P is a cv-qualified type, the top level cv-qualifiers
13391      of P's type are ignored for type deduction.  If P is a
13392      reference type, the type referred to by P is used for
13393      type deduction.  */
13394   *parm = TYPE_MAIN_VARIANT (*parm);
13395   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13396     {
13397       *parm = TREE_TYPE (*parm);
13398       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13399     }
13400
13401   /* DR 322. For conversion deduction, remove a reference type on parm
13402      too (which has been swapped into ARG).  */
13403   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13404     *arg = TREE_TYPE (*arg);
13405
13406   return result;
13407 }
13408
13409 /* Most parms like fn_type_unification.
13410
13411    If SUBR is 1, we're being called recursively (to unify the
13412    arguments of a function or method parameter of a function
13413    template). */
13414
13415 static int
13416 type_unification_real (tree tparms,
13417                        tree targs,
13418                        tree xparms,
13419                        const tree *xargs,
13420                        unsigned int xnargs,
13421                        int subr,
13422                        unification_kind_t strict,
13423                        int flags)
13424 {
13425   tree parm, arg, arg_expr;
13426   int i;
13427   int ntparms = TREE_VEC_LENGTH (tparms);
13428   int sub_strict;
13429   int saw_undeduced = 0;
13430   tree parms;
13431   const tree *args;
13432   unsigned int nargs;
13433   unsigned int ia;
13434
13435   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13436   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13437   gcc_assert (ntparms > 0);
13438
13439   /* Reset the number of non-defaulted template arguments contained
13440      in in TARGS.  */
13441   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13442
13443   switch (strict)
13444     {
13445     case DEDUCE_CALL:
13446       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13447                     | UNIFY_ALLOW_DERIVED);
13448       break;
13449
13450     case DEDUCE_CONV:
13451       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13452       break;
13453
13454     case DEDUCE_EXACT:
13455       sub_strict = UNIFY_ALLOW_NONE;
13456       break;
13457
13458     default:
13459       gcc_unreachable ();
13460     }
13461
13462  again:
13463   parms = xparms;
13464   args = xargs;
13465   nargs = xnargs;
13466
13467   ia = 0;
13468   while (parms && parms != void_list_node
13469          && ia < nargs)
13470     {
13471       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13472         break;
13473
13474       parm = TREE_VALUE (parms);
13475       parms = TREE_CHAIN (parms);
13476       arg = args[ia];
13477       ++ia;
13478       arg_expr = NULL;
13479
13480       if (arg == error_mark_node)
13481         return 1;
13482       if (arg == unknown_type_node)
13483         /* We can't deduce anything from this, but we might get all the
13484            template args from other function args.  */
13485         continue;
13486
13487       /* Conversions will be performed on a function argument that
13488          corresponds with a function parameter that contains only
13489          non-deducible template parameters and explicitly specified
13490          template parameters.  */
13491       if (!uses_template_parms (parm))
13492         {
13493           tree type;
13494
13495           if (!TYPE_P (arg))
13496             type = TREE_TYPE (arg);
13497           else
13498             type = arg;
13499
13500           if (same_type_p (parm, type))
13501             continue;
13502           if (strict != DEDUCE_EXACT
13503               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13504                                   flags))
13505             continue;
13506
13507           return 1;
13508         }
13509
13510       if (!TYPE_P (arg))
13511         {
13512           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13513           if (type_unknown_p (arg))
13514             {
13515               /* [temp.deduct.type] 
13516
13517                  A template-argument can be deduced from a pointer to
13518                  function or pointer to member function argument if
13519                  the set of overloaded functions does not contain
13520                  function templates and at most one of a set of
13521                  overloaded functions provides a unique match.  */
13522               if (resolve_overloaded_unification
13523                   (tparms, targs, parm, arg, strict, sub_strict))
13524                 continue;
13525
13526               return 1;
13527             }
13528           arg_expr = arg;
13529           arg = unlowered_expr_type (arg);
13530           if (arg == error_mark_node)
13531             return 1;
13532         }
13533
13534       {
13535         int arg_strict = sub_strict;
13536
13537         if (!subr)
13538           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13539                                                           arg_expr);
13540
13541         if (arg == init_list_type_node && arg_expr)
13542           arg = arg_expr;
13543         if (unify (tparms, targs, parm, arg, arg_strict))
13544           return 1;
13545       }
13546     }
13547
13548
13549   if (parms 
13550       && parms != void_list_node
13551       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13552     {
13553       /* Unify the remaining arguments with the pack expansion type.  */
13554       tree argvec;
13555       tree parmvec = make_tree_vec (1);
13556
13557       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13558       argvec = make_tree_vec (nargs - ia);
13559       for (i = 0; ia < nargs; ++ia, ++i)
13560         TREE_VEC_ELT (argvec, i) = args[ia];
13561
13562       /* Copy the parameter into parmvec.  */
13563       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13564       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13565                                 /*call_args_p=*/true, /*subr=*/subr))
13566         return 1;
13567
13568       /* Advance to the end of the list of parameters.  */
13569       parms = TREE_CHAIN (parms);
13570     }
13571
13572   /* Fail if we've reached the end of the parm list, and more args
13573      are present, and the parm list isn't variadic.  */
13574   if (ia < nargs && parms == void_list_node)
13575     return 1;
13576   /* Fail if parms are left and they don't have default values.  */
13577   if (parms && parms != void_list_node
13578       && TREE_PURPOSE (parms) == NULL_TREE)
13579     return 1;
13580
13581   if (!subr)
13582     for (i = 0; i < ntparms; i++)
13583       if (!TREE_VEC_ELT (targs, i))
13584         {
13585           tree tparm;
13586
13587           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13588             continue;
13589
13590           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13591
13592           /* If this is an undeduced nontype parameter that depends on
13593              a type parameter, try another pass; its type may have been
13594              deduced from a later argument than the one from which
13595              this parameter can be deduced.  */
13596           if (TREE_CODE (tparm) == PARM_DECL
13597               && uses_template_parms (TREE_TYPE (tparm))
13598               && !saw_undeduced++)
13599             goto again;
13600
13601           /* Core issue #226 (C++0x) [temp.deduct]:
13602
13603                If a template argument has not been deduced, its
13604                default template argument, if any, is used. 
13605
13606              When we are in C++98 mode, TREE_PURPOSE will either
13607              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13608              to explicitly check cxx_dialect here.  */
13609           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13610             {
13611               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13612               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13613               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13614               arg = convert_template_argument (parm, arg, targs, tf_none,
13615                                                i, NULL_TREE);
13616               if (arg == error_mark_node)
13617                 return 1;
13618               else
13619                 {
13620                   TREE_VEC_ELT (targs, i) = arg;
13621                   /* The position of the first default template argument,
13622                      is also the number of non-defaulted arguments in TARGS.
13623                      Record that.  */
13624                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13625                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13626                   continue;
13627                 }
13628             }
13629
13630           /* If the type parameter is a parameter pack, then it will
13631              be deduced to an empty parameter pack.  */
13632           if (template_parameter_pack_p (tparm))
13633             {
13634               tree arg;
13635
13636               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13637                 {
13638                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13639                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13640                   TREE_CONSTANT (arg) = 1;
13641                 }
13642               else
13643                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13644
13645               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13646
13647               TREE_VEC_ELT (targs, i) = arg;
13648               continue;
13649             }
13650
13651           return 2;
13652         }
13653 #ifdef ENABLE_CHECKING
13654   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13655     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13656 #endif
13657
13658   return 0;
13659 }
13660
13661 /* Subroutine of type_unification_real.  Args are like the variables
13662    at the call site.  ARG is an overloaded function (or template-id);
13663    we try deducing template args from each of the overloads, and if
13664    only one succeeds, we go with that.  Modifies TARGS and returns
13665    true on success.  */
13666
13667 static bool
13668 resolve_overloaded_unification (tree tparms,
13669                                 tree targs,
13670                                 tree parm,
13671                                 tree arg,
13672                                 unification_kind_t strict,
13673                                 int sub_strict)
13674 {
13675   tree tempargs = copy_node (targs);
13676   int good = 0;
13677   tree goodfn = NULL_TREE;
13678   bool addr_p;
13679
13680   if (TREE_CODE (arg) == ADDR_EXPR)
13681     {
13682       arg = TREE_OPERAND (arg, 0);
13683       addr_p = true;
13684     }
13685   else
13686     addr_p = false;
13687
13688   if (TREE_CODE (arg) == COMPONENT_REF)
13689     /* Handle `&x' where `x' is some static or non-static member
13690        function name.  */
13691     arg = TREE_OPERAND (arg, 1);
13692
13693   if (TREE_CODE (arg) == OFFSET_REF)
13694     arg = TREE_OPERAND (arg, 1);
13695
13696   /* Strip baselink information.  */
13697   if (BASELINK_P (arg))
13698     arg = BASELINK_FUNCTIONS (arg);
13699
13700   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13701     {
13702       /* If we got some explicit template args, we need to plug them into
13703          the affected templates before we try to unify, in case the
13704          explicit args will completely resolve the templates in question.  */
13705
13706       tree expl_subargs = TREE_OPERAND (arg, 1);
13707       arg = TREE_OPERAND (arg, 0);
13708
13709       for (; arg; arg = OVL_NEXT (arg))
13710         {
13711           tree fn = OVL_CURRENT (arg);
13712           tree subargs, elem;
13713
13714           if (TREE_CODE (fn) != TEMPLATE_DECL)
13715             continue;
13716
13717           ++processing_template_decl;
13718           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13719                                   expl_subargs, /*check_ret=*/false);
13720           if (subargs)
13721             {
13722               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13723               if (try_one_overload (tparms, targs, tempargs, parm,
13724                                     elem, strict, sub_strict, addr_p)
13725                   && (!goodfn || !decls_match (goodfn, elem)))
13726                 {
13727                   goodfn = elem;
13728                   ++good;
13729                 }
13730             }
13731           --processing_template_decl;
13732         }
13733     }
13734   else if (TREE_CODE (arg) != OVERLOAD
13735            && TREE_CODE (arg) != FUNCTION_DECL)
13736     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13737        -- but the deduction does not succeed because the expression is
13738        not just the function on its own.  */
13739     return false;
13740   else
13741     for (; arg; arg = OVL_NEXT (arg))
13742       if (try_one_overload (tparms, targs, tempargs, parm,
13743                             TREE_TYPE (OVL_CURRENT (arg)),
13744                             strict, sub_strict, addr_p)
13745           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13746         {
13747           goodfn = OVL_CURRENT (arg);
13748           ++good;
13749         }
13750
13751   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13752      to function or pointer to member function argument if the set of
13753      overloaded functions does not contain function templates and at most
13754      one of a set of overloaded functions provides a unique match.
13755
13756      So if we found multiple possibilities, we return success but don't
13757      deduce anything.  */
13758
13759   if (good == 1)
13760     {
13761       int i = TREE_VEC_LENGTH (targs);
13762       for (; i--; )
13763         if (TREE_VEC_ELT (tempargs, i))
13764           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13765     }
13766   if (good)
13767     return true;
13768
13769   return false;
13770 }
13771
13772 /* Core DR 115: In contexts where deduction is done and fails, or in
13773    contexts where deduction is not done, if a template argument list is
13774    specified and it, along with any default template arguments, identifies
13775    a single function template specialization, then the template-id is an
13776    lvalue for the function template specialization.  */
13777
13778 tree
13779 resolve_nondeduced_context (tree orig_expr)
13780 {
13781   tree expr, offset, baselink;
13782   bool addr;
13783
13784   if (!type_unknown_p (orig_expr))
13785     return orig_expr;
13786
13787   expr = orig_expr;
13788   addr = false;
13789   offset = NULL_TREE;
13790   baselink = NULL_TREE;
13791
13792   if (TREE_CODE (expr) == ADDR_EXPR)
13793     {
13794       expr = TREE_OPERAND (expr, 0);
13795       addr = true;
13796     }
13797   if (TREE_CODE (expr) == OFFSET_REF)
13798     {
13799       offset = expr;
13800       expr = TREE_OPERAND (expr, 1);
13801     }
13802   if (TREE_CODE (expr) == BASELINK)
13803     {
13804       baselink = expr;
13805       expr = BASELINK_FUNCTIONS (expr);
13806     }
13807
13808   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13809     {
13810       int good = 0;
13811       tree goodfn = NULL_TREE;
13812
13813       /* If we got some explicit template args, we need to plug them into
13814          the affected templates before we try to unify, in case the
13815          explicit args will completely resolve the templates in question.  */
13816
13817       tree expl_subargs = TREE_OPERAND (expr, 1);
13818       tree arg = TREE_OPERAND (expr, 0);
13819       tree badfn = NULL_TREE;
13820       tree badargs = NULL_TREE;
13821
13822       for (; arg; arg = OVL_NEXT (arg))
13823         {
13824           tree fn = OVL_CURRENT (arg);
13825           tree subargs, elem;
13826
13827           if (TREE_CODE (fn) != TEMPLATE_DECL)
13828             continue;
13829
13830           ++processing_template_decl;
13831           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13832                                   expl_subargs, /*check_ret=*/false);
13833           if (subargs && !any_dependent_template_arguments_p (subargs))
13834             {
13835               elem = instantiate_template (fn, subargs, tf_none);
13836               if (elem == error_mark_node)
13837                 {
13838                   badfn = fn;
13839                   badargs = subargs;
13840                 }
13841               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13842                 {
13843                   goodfn = elem;
13844                   ++good;
13845                 }
13846             }
13847           --processing_template_decl;
13848         }
13849       if (good == 1)
13850         {
13851           expr = goodfn;
13852           if (baselink)
13853             expr = build_baselink (BASELINK_BINFO (baselink),
13854                                    BASELINK_ACCESS_BINFO (baselink),
13855                                    expr, BASELINK_OPTYPE (baselink));
13856           if (offset)
13857             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13858                            TREE_OPERAND (offset, 0), expr);
13859           if (addr)
13860             expr = build_address (expr);
13861           return expr;
13862         }
13863       else if (good == 0 && badargs)
13864         /* There were no good options and at least one bad one, so let the
13865            user know what the problem is.  */
13866         instantiate_template (badfn, badargs, tf_warning_or_error);
13867     }
13868   return orig_expr;
13869 }
13870
13871 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13872    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13873    different overloads deduce different arguments for a given parm.
13874    ADDR_P is true if the expression for which deduction is being
13875    performed was of the form "& fn" rather than simply "fn".
13876
13877    Returns 1 on success.  */
13878
13879 static int
13880 try_one_overload (tree tparms,
13881                   tree orig_targs,
13882                   tree targs,
13883                   tree parm,
13884                   tree arg,
13885                   unification_kind_t strict,
13886                   int sub_strict,
13887                   bool addr_p)
13888 {
13889   int nargs;
13890   tree tempargs;
13891   int i;
13892
13893   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13894      to function or pointer to member function argument if the set of
13895      overloaded functions does not contain function templates and at most
13896      one of a set of overloaded functions provides a unique match.
13897
13898      So if this is a template, just return success.  */
13899
13900   if (uses_template_parms (arg))
13901     return 1;
13902
13903   if (TREE_CODE (arg) == METHOD_TYPE)
13904     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13905   else if (addr_p)
13906     arg = build_pointer_type (arg);
13907
13908   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13909
13910   /* We don't copy orig_targs for this because if we have already deduced
13911      some template args from previous args, unify would complain when we
13912      try to deduce a template parameter for the same argument, even though
13913      there isn't really a conflict.  */
13914   nargs = TREE_VEC_LENGTH (targs);
13915   tempargs = make_tree_vec (nargs);
13916
13917   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13918     return 0;
13919
13920   /* First make sure we didn't deduce anything that conflicts with
13921      explicitly specified args.  */
13922   for (i = nargs; i--; )
13923     {
13924       tree elt = TREE_VEC_ELT (tempargs, i);
13925       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13926
13927       if (!elt)
13928         /*NOP*/;
13929       else if (uses_template_parms (elt))
13930         /* Since we're unifying against ourselves, we will fill in
13931            template args used in the function parm list with our own
13932            template parms.  Discard them.  */
13933         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13934       else if (oldelt && !template_args_equal (oldelt, elt))
13935         return 0;
13936     }
13937
13938   for (i = nargs; i--; )
13939     {
13940       tree elt = TREE_VEC_ELT (tempargs, i);
13941
13942       if (elt)
13943         TREE_VEC_ELT (targs, i) = elt;
13944     }
13945
13946   return 1;
13947 }
13948
13949 /* PARM is a template class (perhaps with unbound template
13950    parameters).  ARG is a fully instantiated type.  If ARG can be
13951    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13952    TARGS are as for unify.  */
13953
13954 static tree
13955 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13956 {
13957   tree copy_of_targs;
13958
13959   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13960       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13961           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13962     return NULL_TREE;
13963
13964   /* We need to make a new template argument vector for the call to
13965      unify.  If we used TARGS, we'd clutter it up with the result of
13966      the attempted unification, even if this class didn't work out.
13967      We also don't want to commit ourselves to all the unifications
13968      we've already done, since unification is supposed to be done on
13969      an argument-by-argument basis.  In other words, consider the
13970      following pathological case:
13971
13972        template <int I, int J, int K>
13973        struct S {};
13974
13975        template <int I, int J>
13976        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13977
13978        template <int I, int J, int K>
13979        void f(S<I, J, K>, S<I, I, I>);
13980
13981        void g() {
13982          S<0, 0, 0> s0;
13983          S<0, 1, 2> s2;
13984
13985          f(s0, s2);
13986        }
13987
13988      Now, by the time we consider the unification involving `s2', we
13989      already know that we must have `f<0, 0, 0>'.  But, even though
13990      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13991      because there are two ways to unify base classes of S<0, 1, 2>
13992      with S<I, I, I>.  If we kept the already deduced knowledge, we
13993      would reject the possibility I=1.  */
13994   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13995
13996   /* If unification failed, we're done.  */
13997   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13998              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13999     return NULL_TREE;
14000
14001   return arg;
14002 }
14003
14004 /* Given a template type PARM and a class type ARG, find the unique
14005    base type in ARG that is an instance of PARM.  We do not examine
14006    ARG itself; only its base-classes.  If there is not exactly one
14007    appropriate base class, return NULL_TREE.  PARM may be the type of
14008    a partial specialization, as well as a plain template type.  Used
14009    by unify.  */
14010
14011 static tree
14012 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14013 {
14014   tree rval = NULL_TREE;
14015   tree binfo;
14016
14017   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14018
14019   binfo = TYPE_BINFO (complete_type (arg));
14020   if (!binfo)
14021     /* The type could not be completed.  */
14022     return NULL_TREE;
14023
14024   /* Walk in inheritance graph order.  The search order is not
14025      important, and this avoids multiple walks of virtual bases.  */
14026   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14027     {
14028       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14029
14030       if (r)
14031         {
14032           /* If there is more than one satisfactory baseclass, then:
14033
14034                [temp.deduct.call]
14035
14036               If they yield more than one possible deduced A, the type
14037               deduction fails.
14038
14039              applies.  */
14040           if (rval && !same_type_p (r, rval))
14041             return NULL_TREE;
14042
14043           rval = r;
14044         }
14045     }
14046
14047   return rval;
14048 }
14049
14050 /* Returns the level of DECL, which declares a template parameter.  */
14051
14052 static int
14053 template_decl_level (tree decl)
14054 {
14055   switch (TREE_CODE (decl))
14056     {
14057     case TYPE_DECL:
14058     case TEMPLATE_DECL:
14059       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14060
14061     case PARM_DECL:
14062       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14063
14064     default:
14065       gcc_unreachable ();
14066     }
14067   return 0;
14068 }
14069
14070 /* Decide whether ARG can be unified with PARM, considering only the
14071    cv-qualifiers of each type, given STRICT as documented for unify.
14072    Returns nonzero iff the unification is OK on that basis.  */
14073
14074 static int
14075 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14076 {
14077   int arg_quals = cp_type_quals (arg);
14078   int parm_quals = cp_type_quals (parm);
14079
14080   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14081       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14082     {
14083       /*  Although a CVR qualifier is ignored when being applied to a
14084           substituted template parameter ([8.3.2]/1 for example), that
14085           does not apply during deduction [14.8.2.4]/1, (even though
14086           that is not explicitly mentioned, [14.8.2.4]/9 indicates
14087           this).  Except when we're allowing additional CV qualifiers
14088           at the outer level [14.8.2.1]/3,1st bullet.  */
14089       if ((TREE_CODE (arg) == REFERENCE_TYPE
14090            || TREE_CODE (arg) == FUNCTION_TYPE
14091            || TREE_CODE (arg) == METHOD_TYPE)
14092           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14093         return 0;
14094
14095       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14096           && (parm_quals & TYPE_QUAL_RESTRICT))
14097         return 0;
14098     }
14099
14100   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14101       && (arg_quals & parm_quals) != parm_quals)
14102     return 0;
14103
14104   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14105       && (parm_quals & arg_quals) != arg_quals)
14106     return 0;
14107
14108   return 1;
14109 }
14110
14111 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14112 void 
14113 template_parm_level_and_index (tree parm, int* level, int* index)
14114 {
14115   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14116       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14117       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14118     {
14119       *index = TEMPLATE_TYPE_IDX (parm);
14120       *level = TEMPLATE_TYPE_LEVEL (parm);
14121     }
14122   else
14123     {
14124       *index = TEMPLATE_PARM_IDX (parm);
14125       *level = TEMPLATE_PARM_LEVEL (parm);
14126     }
14127 }
14128
14129 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14130    expansion at the end of PACKED_PARMS. Returns 0 if the type
14131    deduction succeeds, 1 otherwise. STRICT is the same as in
14132    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14133    call argument list. We'll need to adjust the arguments to make them
14134    types. SUBR tells us if this is from a recursive call to
14135    type_unification_real.  */
14136 int
14137 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14138                       tree packed_args, int strict, bool call_args_p,
14139                       bool subr)
14140 {
14141   tree parm 
14142     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14143   tree pattern = PACK_EXPANSION_PATTERN (parm);
14144   tree pack, packs = NULL_TREE;
14145   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14146   int len = TREE_VEC_LENGTH (packed_args);
14147
14148   /* Determine the parameter packs we will be deducing from the
14149      pattern, and record their current deductions.  */
14150   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14151        pack; pack = TREE_CHAIN (pack))
14152     {
14153       tree parm_pack = TREE_VALUE (pack);
14154       int idx, level;
14155
14156       /* Determine the index and level of this parameter pack.  */
14157       template_parm_level_and_index (parm_pack, &level, &idx);
14158
14159       /* Keep track of the parameter packs and their corresponding
14160          argument packs.  */
14161       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14162       TREE_TYPE (packs) = make_tree_vec (len - start);
14163     }
14164   
14165   /* Loop through all of the arguments that have not yet been
14166      unified and unify each with the pattern.  */
14167   for (i = start; i < len; i++)
14168     {
14169       tree parm = pattern;
14170
14171       /* For each parameter pack, clear out the deduced value so that
14172          we can deduce it again.  */
14173       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14174         {
14175           int idx, level;
14176           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14177
14178           TMPL_ARG (targs, level, idx) = NULL_TREE;
14179         }
14180
14181       /* Unify the pattern with the current argument.  */
14182       {
14183         tree arg = TREE_VEC_ELT (packed_args, i);
14184         tree arg_expr = NULL_TREE;
14185         int arg_strict = strict;
14186         bool skip_arg_p = false;
14187
14188         if (call_args_p)
14189           {
14190             int sub_strict;
14191
14192             /* This mirrors what we do in type_unification_real.  */
14193             switch (strict)
14194               {
14195               case DEDUCE_CALL:
14196                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14197                               | UNIFY_ALLOW_MORE_CV_QUAL
14198                               | UNIFY_ALLOW_DERIVED);
14199                 break;
14200                 
14201               case DEDUCE_CONV:
14202                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14203                 break;
14204                 
14205               case DEDUCE_EXACT:
14206                 sub_strict = UNIFY_ALLOW_NONE;
14207                 break;
14208                 
14209               default:
14210                 gcc_unreachable ();
14211               }
14212
14213             if (!TYPE_P (arg))
14214               {
14215                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14216                 if (type_unknown_p (arg))
14217                   {
14218                     /* [temp.deduct.type] A template-argument can be
14219                        deduced from a pointer to function or pointer
14220                        to member function argument if the set of
14221                        overloaded functions does not contain function
14222                        templates and at most one of a set of
14223                        overloaded functions provides a unique
14224                        match.  */
14225
14226                     if (resolve_overloaded_unification
14227                         (tparms, targs, parm, arg,
14228                          (unification_kind_t) strict,
14229                          sub_strict)
14230                         != 0)
14231                       return 1;
14232                     skip_arg_p = true;
14233                   }
14234
14235                 if (!skip_arg_p)
14236                   {
14237                     arg_expr = arg;
14238                     arg = unlowered_expr_type (arg);
14239                     if (arg == error_mark_node)
14240                       return 1;
14241                   }
14242               }
14243       
14244             arg_strict = sub_strict;
14245
14246             if (!subr)
14247               arg_strict |= 
14248                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14249                                                   &parm, &arg, arg_expr);
14250           }
14251
14252         if (!skip_arg_p)
14253           {
14254             /* For deduction from an init-list we need the actual list.  */
14255             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14256               arg = arg_expr;
14257             if (unify (tparms, targs, parm, arg, arg_strict))
14258               return 1;
14259           }
14260       }
14261
14262       /* For each parameter pack, collect the deduced value.  */
14263       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14264         {
14265           int idx, level;
14266           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14267
14268           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14269             TMPL_ARG (targs, level, idx);
14270         }
14271     }
14272
14273   /* Verify that the results of unification with the parameter packs
14274      produce results consistent with what we've seen before, and make
14275      the deduced argument packs available.  */
14276   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14277     {
14278       tree old_pack = TREE_VALUE (pack);
14279       tree new_args = TREE_TYPE (pack);
14280       int i, len = TREE_VEC_LENGTH (new_args);
14281       int idx, level;
14282       bool nondeduced_p = false;
14283
14284       /* By default keep the original deduced argument pack.
14285          If necessary, more specific code is going to update the
14286          resulting deduced argument later down in this function.  */
14287       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14288       TMPL_ARG (targs, level, idx) = old_pack;
14289
14290       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14291          actually deduce anything.  */
14292       for (i = 0; i < len && !nondeduced_p; ++i)
14293         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14294           nondeduced_p = true;
14295       if (nondeduced_p)
14296         continue;
14297
14298       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14299         {
14300           /* Prepend the explicit arguments onto NEW_ARGS.  */
14301           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14302           tree old_args = new_args;
14303           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14304           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14305
14306           /* Copy the explicit arguments.  */
14307           new_args = make_tree_vec (len);
14308           for (i = 0; i < explicit_len; i++)
14309             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14310
14311           /* Copy the deduced arguments.  */
14312           for (; i < len; i++)
14313             TREE_VEC_ELT (new_args, i) =
14314               TREE_VEC_ELT (old_args, i - explicit_len);
14315         }
14316
14317       if (!old_pack)
14318         {
14319           tree result;
14320           /* Build the deduced *_ARGUMENT_PACK.  */
14321           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14322             {
14323               result = make_node (NONTYPE_ARGUMENT_PACK);
14324               TREE_TYPE (result) = 
14325                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14326               TREE_CONSTANT (result) = 1;
14327             }
14328           else
14329             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14330
14331           SET_ARGUMENT_PACK_ARGS (result, new_args);
14332
14333           /* Note the deduced argument packs for this parameter
14334              pack.  */
14335           TMPL_ARG (targs, level, idx) = result;
14336         }
14337       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14338                && (ARGUMENT_PACK_ARGS (old_pack) 
14339                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14340         {
14341           /* We only had the explicitly-provided arguments before, but
14342              now we have a complete set of arguments.  */
14343           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14344
14345           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14346           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14347           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14348         }
14349       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14350                                     new_args))
14351         /* Inconsistent unification of this parameter pack.  */
14352         return 1;
14353     }
14354
14355   return 0;
14356 }
14357
14358 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14359    set of template parameters to a template.  TARGS is the bindings
14360    for those template parameters, as determined thus far; TARGS may
14361    include template arguments for outer levels of template parameters
14362    as well.  PARM is a parameter to a template function, or a
14363    subcomponent of that parameter; ARG is the corresponding argument.
14364    This function attempts to match PARM with ARG in a manner
14365    consistent with the existing assignments in TARGS.  If more values
14366    are deduced, then TARGS is updated.
14367
14368    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14369    parameter STRICT is a bitwise or of the following flags:
14370
14371      UNIFY_ALLOW_NONE:
14372        Require an exact match between PARM and ARG.
14373      UNIFY_ALLOW_MORE_CV_QUAL:
14374        Allow the deduced ARG to be more cv-qualified (by qualification
14375        conversion) than ARG.
14376      UNIFY_ALLOW_LESS_CV_QUAL:
14377        Allow the deduced ARG to be less cv-qualified than ARG.
14378      UNIFY_ALLOW_DERIVED:
14379        Allow the deduced ARG to be a template base class of ARG,
14380        or a pointer to a template base class of the type pointed to by
14381        ARG.
14382      UNIFY_ALLOW_INTEGER:
14383        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14384        case for more information.
14385      UNIFY_ALLOW_OUTER_LEVEL:
14386        This is the outermost level of a deduction. Used to determine validity
14387        of qualification conversions. A valid qualification conversion must
14388        have const qualified pointers leading up to the inner type which
14389        requires additional CV quals, except at the outer level, where const
14390        is not required [conv.qual]. It would be normal to set this flag in
14391        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14392      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14393        This is the outermost level of a deduction, and PARM can be more CV
14394        qualified at this point.
14395      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14396        This is the outermost level of a deduction, and PARM can be less CV
14397        qualified at this point.  */
14398
14399 static int
14400 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14401 {
14402   int idx;
14403   tree targ;
14404   tree tparm;
14405   int strict_in = strict;
14406
14407   /* I don't think this will do the right thing with respect to types.
14408      But the only case I've seen it in so far has been array bounds, where
14409      signedness is the only information lost, and I think that will be
14410      okay.  */
14411   while (TREE_CODE (parm) == NOP_EXPR)
14412     parm = TREE_OPERAND (parm, 0);
14413
14414   if (arg == error_mark_node)
14415     return 1;
14416   if (arg == unknown_type_node
14417       || arg == init_list_type_node)
14418     /* We can't deduce anything from this, but we might get all the
14419        template args from other function args.  */
14420     return 0;
14421
14422   /* If PARM uses template parameters, then we can't bail out here,
14423      even if ARG == PARM, since we won't record unifications for the
14424      template parameters.  We might need them if we're trying to
14425      figure out which of two things is more specialized.  */
14426   if (arg == parm && !uses_template_parms (parm))
14427     return 0;
14428
14429   /* Handle init lists early, so the rest of the function can assume
14430      we're dealing with a type. */
14431   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14432     {
14433       tree elt, elttype;
14434       unsigned i;
14435       tree orig_parm = parm;
14436
14437       /* Replace T with std::initializer_list<T> for deduction.  */
14438       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14439           && flag_deduce_init_list)
14440         parm = listify (parm);
14441
14442       if (!is_std_init_list (parm))
14443         /* We can only deduce from an initializer list argument if the
14444            parameter is std::initializer_list; otherwise this is a
14445            non-deduced context. */
14446         return 0;
14447
14448       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14449
14450       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14451         {
14452           int elt_strict = strict;
14453           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14454             {
14455               tree type = TREE_TYPE (elt);
14456               /* It should only be possible to get here for a call.  */
14457               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14458               elt_strict |= maybe_adjust_types_for_deduction
14459                 (DEDUCE_CALL, &elttype, &type, elt);
14460               elt = type;
14461             }
14462
14463           if (unify (tparms, targs, elttype, elt, elt_strict))
14464             return 1;
14465         }
14466
14467       /* If the std::initializer_list<T> deduction worked, replace the
14468          deduced A with std::initializer_list<A>.  */
14469       if (orig_parm != parm)
14470         {
14471           idx = TEMPLATE_TYPE_IDX (orig_parm);
14472           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14473           targ = listify (targ);
14474           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14475         }
14476       return 0;
14477     }
14478
14479   /* Immediately reject some pairs that won't unify because of
14480      cv-qualification mismatches.  */
14481   if (TREE_CODE (arg) == TREE_CODE (parm)
14482       && TYPE_P (arg)
14483       /* It is the elements of the array which hold the cv quals of an array
14484          type, and the elements might be template type parms. We'll check
14485          when we recurse.  */
14486       && TREE_CODE (arg) != ARRAY_TYPE
14487       /* We check the cv-qualifiers when unifying with template type
14488          parameters below.  We want to allow ARG `const T' to unify with
14489          PARM `T' for example, when computing which of two templates
14490          is more specialized, for example.  */
14491       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14492       && !check_cv_quals_for_unify (strict_in, arg, parm))
14493     return 1;
14494
14495   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14496       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14497     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14498   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14499   strict &= ~UNIFY_ALLOW_DERIVED;
14500   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14501   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14502
14503   switch (TREE_CODE (parm))
14504     {
14505     case TYPENAME_TYPE:
14506     case SCOPE_REF:
14507     case UNBOUND_CLASS_TEMPLATE:
14508       /* In a type which contains a nested-name-specifier, template
14509          argument values cannot be deduced for template parameters used
14510          within the nested-name-specifier.  */
14511       return 0;
14512
14513     case TEMPLATE_TYPE_PARM:
14514     case TEMPLATE_TEMPLATE_PARM:
14515     case BOUND_TEMPLATE_TEMPLATE_PARM:
14516       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14517       if (tparm == error_mark_node)
14518         return 1;
14519
14520       if (TEMPLATE_TYPE_LEVEL (parm)
14521           != template_decl_level (tparm))
14522         /* The PARM is not one we're trying to unify.  Just check
14523            to see if it matches ARG.  */
14524         return (TREE_CODE (arg) == TREE_CODE (parm)
14525                 && same_type_p (parm, arg)) ? 0 : 1;
14526       idx = TEMPLATE_TYPE_IDX (parm);
14527       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14528       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14529
14530       /* Check for mixed types and values.  */
14531       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14532            && TREE_CODE (tparm) != TYPE_DECL)
14533           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14534               && TREE_CODE (tparm) != TEMPLATE_DECL))
14535         return 1;
14536
14537       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14538         {
14539           /* ARG must be constructed from a template class or a template
14540              template parameter.  */
14541           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14542               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14543             return 1;
14544
14545           {
14546             tree parmvec = TYPE_TI_ARGS (parm);
14547             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14548             tree parm_parms 
14549               = DECL_INNERMOST_TEMPLATE_PARMS
14550                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14551             int i, len;
14552             int parm_variadic_p = 0;
14553
14554             /* The resolution to DR150 makes clear that default
14555                arguments for an N-argument may not be used to bind T
14556                to a template template parameter with fewer than N
14557                parameters.  It is not safe to permit the binding of
14558                default arguments as an extension, as that may change
14559                the meaning of a conforming program.  Consider:
14560
14561                   struct Dense { static const unsigned int dim = 1; };
14562
14563                   template <template <typename> class View,
14564                             typename Block>
14565                   void operator+(float, View<Block> const&);
14566
14567                   template <typename Block,
14568                             unsigned int Dim = Block::dim>
14569                   struct Lvalue_proxy { operator float() const; };
14570
14571                   void
14572                   test_1d (void) {
14573                     Lvalue_proxy<Dense> p;
14574                     float b;
14575                     b + p;
14576                   }
14577
14578               Here, if Lvalue_proxy is permitted to bind to View, then
14579               the global operator+ will be used; if they are not, the
14580               Lvalue_proxy will be converted to float.  */
14581             if (coerce_template_parms (parm_parms,
14582                                        argvec,
14583                                        TYPE_TI_TEMPLATE (parm),
14584                                        tf_none,
14585                                        /*require_all_args=*/true,
14586                                        /*use_default_args=*/false)
14587                 == error_mark_node)
14588               return 1;
14589
14590             /* Deduce arguments T, i from TT<T> or TT<i>.
14591                We check each element of PARMVEC and ARGVEC individually
14592                rather than the whole TREE_VEC since they can have
14593                different number of elements.  */
14594
14595             parmvec = expand_template_argument_pack (parmvec);
14596             argvec = expand_template_argument_pack (argvec);
14597
14598             len = TREE_VEC_LENGTH (parmvec);
14599
14600             /* Check if the parameters end in a pack, making them
14601                variadic.  */
14602             if (len > 0
14603                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14604               parm_variadic_p = 1;
14605             
14606             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14607               return 1;
14608
14609              for (i = 0; i < len - parm_variadic_p; ++i)
14610               {
14611                 if (unify (tparms, targs,
14612                            TREE_VEC_ELT (parmvec, i),
14613                            TREE_VEC_ELT (argvec, i),
14614                            UNIFY_ALLOW_NONE))
14615                   return 1;
14616               }
14617
14618             if (parm_variadic_p
14619                 && unify_pack_expansion (tparms, targs,
14620                                          parmvec, argvec,
14621                                          UNIFY_ALLOW_NONE,
14622                                          /*call_args_p=*/false,
14623                                          /*subr=*/false))
14624               return 1;
14625           }
14626           arg = TYPE_TI_TEMPLATE (arg);
14627
14628           /* Fall through to deduce template name.  */
14629         }
14630
14631       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14632           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14633         {
14634           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14635
14636           /* Simple cases: Value already set, does match or doesn't.  */
14637           if (targ != NULL_TREE && template_args_equal (targ, arg))
14638             return 0;
14639           else if (targ)
14640             return 1;
14641         }
14642       else
14643         {
14644           /* If PARM is `const T' and ARG is only `int', we don't have
14645              a match unless we are allowing additional qualification.
14646              If ARG is `const int' and PARM is just `T' that's OK;
14647              that binds `const int' to `T'.  */
14648           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14649                                          arg, parm))
14650             return 1;
14651
14652           /* Consider the case where ARG is `const volatile int' and
14653              PARM is `const T'.  Then, T should be `volatile int'.  */
14654           arg = cp_build_qualified_type_real
14655             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14656           if (arg == error_mark_node)
14657             return 1;
14658
14659           /* Simple cases: Value already set, does match or doesn't.  */
14660           if (targ != NULL_TREE && same_type_p (targ, arg))
14661             return 0;
14662           else if (targ)
14663             return 1;
14664
14665           /* Make sure that ARG is not a variable-sized array.  (Note
14666              that were talking about variable-sized arrays (like
14667              `int[n]'), rather than arrays of unknown size (like
14668              `int[]').)  We'll get very confused by such a type since
14669              the bound of the array will not be computable in an
14670              instantiation.  Besides, such types are not allowed in
14671              ISO C++, so we can do as we please here.  */
14672           if (variably_modified_type_p (arg, NULL_TREE))
14673             return 1;
14674
14675           /* Strip typedefs as in convert_template_argument.  */
14676           arg = strip_typedefs (arg);
14677         }
14678
14679       /* If ARG is a parameter pack or an expansion, we cannot unify
14680          against it unless PARM is also a parameter pack.  */
14681       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14682           && !template_parameter_pack_p (parm))
14683         return 1;
14684
14685       /* If the argument deduction results is a METHOD_TYPE,
14686          then there is a problem.
14687          METHOD_TYPE doesn't map to any real C++ type the result of
14688          the deduction can not be of that type.  */
14689       if (TREE_CODE (arg) == METHOD_TYPE)
14690         return 1;
14691
14692       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14693       return 0;
14694
14695     case TEMPLATE_PARM_INDEX:
14696       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14697       if (tparm == error_mark_node)
14698         return 1;
14699
14700       if (TEMPLATE_PARM_LEVEL (parm)
14701           != template_decl_level (tparm))
14702         /* The PARM is not one we're trying to unify.  Just check
14703            to see if it matches ARG.  */
14704         return !(TREE_CODE (arg) == TREE_CODE (parm)
14705                  && cp_tree_equal (parm, arg));
14706
14707       idx = TEMPLATE_PARM_IDX (parm);
14708       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14709
14710       if (targ)
14711         return !cp_tree_equal (targ, arg);
14712
14713       /* [temp.deduct.type] If, in the declaration of a function template
14714          with a non-type template-parameter, the non-type
14715          template-parameter is used in an expression in the function
14716          parameter-list and, if the corresponding template-argument is
14717          deduced, the template-argument type shall match the type of the
14718          template-parameter exactly, except that a template-argument
14719          deduced from an array bound may be of any integral type.
14720          The non-type parameter might use already deduced type parameters.  */
14721       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14722       if (!TREE_TYPE (arg))
14723         /* Template-parameter dependent expression.  Just accept it for now.
14724            It will later be processed in convert_template_argument.  */
14725         ;
14726       else if (same_type_p (TREE_TYPE (arg), tparm))
14727         /* OK */;
14728       else if ((strict & UNIFY_ALLOW_INTEGER)
14729                && (TREE_CODE (tparm) == INTEGER_TYPE
14730                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14731         /* Convert the ARG to the type of PARM; the deduced non-type
14732            template argument must exactly match the types of the
14733            corresponding parameter.  */
14734         arg = fold (build_nop (tparm, arg));
14735       else if (uses_template_parms (tparm))
14736         /* We haven't deduced the type of this parameter yet.  Try again
14737            later.  */
14738         return 0;
14739       else
14740         return 1;
14741
14742       /* If ARG is a parameter pack or an expansion, we cannot unify
14743          against it unless PARM is also a parameter pack.  */
14744       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14745           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14746         return 1;
14747
14748       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14749       return 0;
14750
14751     case PTRMEM_CST:
14752      {
14753         /* A pointer-to-member constant can be unified only with
14754          another constant.  */
14755       if (TREE_CODE (arg) != PTRMEM_CST)
14756         return 1;
14757
14758       /* Just unify the class member. It would be useless (and possibly
14759          wrong, depending on the strict flags) to unify also
14760          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14761          arg refer to the same variable, even if through different
14762          classes. For instance:
14763
14764          struct A { int x; };
14765          struct B : A { };
14766
14767          Unification of &A::x and &B::x must succeed.  */
14768       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14769                     PTRMEM_CST_MEMBER (arg), strict);
14770      }
14771
14772     case POINTER_TYPE:
14773       {
14774         if (TREE_CODE (arg) != POINTER_TYPE)
14775           return 1;
14776
14777         /* [temp.deduct.call]
14778
14779            A can be another pointer or pointer to member type that can
14780            be converted to the deduced A via a qualification
14781            conversion (_conv.qual_).
14782
14783            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14784            This will allow for additional cv-qualification of the
14785            pointed-to types if appropriate.  */
14786
14787         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14788           /* The derived-to-base conversion only persists through one
14789              level of pointers.  */
14790           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14791
14792         return unify (tparms, targs, TREE_TYPE (parm),
14793                       TREE_TYPE (arg), strict);
14794       }
14795
14796     case REFERENCE_TYPE:
14797       if (TREE_CODE (arg) != REFERENCE_TYPE)
14798         return 1;
14799       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14800                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14801
14802     case ARRAY_TYPE:
14803       if (TREE_CODE (arg) != ARRAY_TYPE)
14804         return 1;
14805       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14806           != (TYPE_DOMAIN (arg) == NULL_TREE))
14807         return 1;
14808       if (TYPE_DOMAIN (parm) != NULL_TREE)
14809         {
14810           tree parm_max;
14811           tree arg_max;
14812           bool parm_cst;
14813           bool arg_cst;
14814
14815           /* Our representation of array types uses "N - 1" as the
14816              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14817              not an integer constant.  We cannot unify arbitrarily
14818              complex expressions, so we eliminate the MINUS_EXPRs
14819              here.  */
14820           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14821           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14822           if (!parm_cst)
14823             {
14824               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14825               parm_max = TREE_OPERAND (parm_max, 0);
14826             }
14827           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14828           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14829           if (!arg_cst)
14830             {
14831               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14832                  trying to unify the type of a variable with the type
14833                  of a template parameter.  For example:
14834
14835                    template <unsigned int N>
14836                    void f (char (&) [N]);
14837                    int g(); 
14838                    void h(int i) {
14839                      char a[g(i)];
14840                      f(a); 
14841                    }
14842
14843                 Here, the type of the ARG will be "int [g(i)]", and
14844                 may be a SAVE_EXPR, etc.  */
14845               if (TREE_CODE (arg_max) != MINUS_EXPR)
14846                 return 1;
14847               arg_max = TREE_OPERAND (arg_max, 0);
14848             }
14849
14850           /* If only one of the bounds used a MINUS_EXPR, compensate
14851              by adding one to the other bound.  */
14852           if (parm_cst && !arg_cst)
14853             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14854                                     integer_type_node,
14855                                     parm_max,
14856                                     integer_one_node);
14857           else if (arg_cst && !parm_cst)
14858             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14859                                    integer_type_node,
14860                                    arg_max,
14861                                    integer_one_node);
14862
14863           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14864             return 1;
14865         }
14866       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14867                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14868
14869     case REAL_TYPE:
14870     case COMPLEX_TYPE:
14871     case VECTOR_TYPE:
14872     case INTEGER_TYPE:
14873     case BOOLEAN_TYPE:
14874     case ENUMERAL_TYPE:
14875     case VOID_TYPE:
14876       if (TREE_CODE (arg) != TREE_CODE (parm))
14877         return 1;
14878
14879       /* We have already checked cv-qualification at the top of the
14880          function.  */
14881       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14882         return 1;
14883
14884       /* As far as unification is concerned, this wins.  Later checks
14885          will invalidate it if necessary.  */
14886       return 0;
14887
14888       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14889       /* Type INTEGER_CST can come from ordinary constant template args.  */
14890     case INTEGER_CST:
14891       while (TREE_CODE (arg) == NOP_EXPR)
14892         arg = TREE_OPERAND (arg, 0);
14893
14894       if (TREE_CODE (arg) != INTEGER_CST)
14895         return 1;
14896       return !tree_int_cst_equal (parm, arg);
14897
14898     case TREE_VEC:
14899       {
14900         int i;
14901         if (TREE_CODE (arg) != TREE_VEC)
14902           return 1;
14903         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14904           return 1;
14905         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14906           if (unify (tparms, targs,
14907                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14908                      UNIFY_ALLOW_NONE))
14909             return 1;
14910         return 0;
14911       }
14912
14913     case RECORD_TYPE:
14914     case UNION_TYPE:
14915       if (TREE_CODE (arg) != TREE_CODE (parm))
14916         return 1;
14917
14918       if (TYPE_PTRMEMFUNC_P (parm))
14919         {
14920           if (!TYPE_PTRMEMFUNC_P (arg))
14921             return 1;
14922
14923           return unify (tparms, targs,
14924                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14925                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14926                         strict);
14927         }
14928
14929       if (CLASSTYPE_TEMPLATE_INFO (parm))
14930         {
14931           tree t = NULL_TREE;
14932
14933           if (strict_in & UNIFY_ALLOW_DERIVED)
14934             {
14935               /* First, we try to unify the PARM and ARG directly.  */
14936               t = try_class_unification (tparms, targs,
14937                                          parm, arg);
14938
14939               if (!t)
14940                 {
14941                   /* Fallback to the special case allowed in
14942                      [temp.deduct.call]:
14943
14944                        If P is a class, and P has the form
14945                        template-id, then A can be a derived class of
14946                        the deduced A.  Likewise, if P is a pointer to
14947                        a class of the form template-id, A can be a
14948                        pointer to a derived class pointed to by the
14949                        deduced A.  */
14950                   t = get_template_base (tparms, targs, parm, arg);
14951
14952                   if (!t)
14953                     return 1;
14954                 }
14955             }
14956           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14957                    && (CLASSTYPE_TI_TEMPLATE (parm)
14958                        == CLASSTYPE_TI_TEMPLATE (arg)))
14959             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14960                Then, we should unify `int' and `U'.  */
14961             t = arg;
14962           else
14963             /* There's no chance of unification succeeding.  */
14964             return 1;
14965
14966           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14967                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14968         }
14969       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14970         return 1;
14971       return 0;
14972
14973     case METHOD_TYPE:
14974     case FUNCTION_TYPE:
14975       {
14976         unsigned int nargs;
14977         tree *args;
14978         tree a;
14979         unsigned int i;
14980
14981         if (TREE_CODE (arg) != TREE_CODE (parm))
14982           return 1;
14983
14984         /* CV qualifications for methods can never be deduced, they must
14985            match exactly.  We need to check them explicitly here,
14986            because type_unification_real treats them as any other
14987            cv-qualified parameter.  */
14988         if (TREE_CODE (parm) == METHOD_TYPE
14989             && (!check_cv_quals_for_unify
14990                 (UNIFY_ALLOW_NONE,
14991                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14992                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14993           return 1;
14994
14995         if (unify (tparms, targs, TREE_TYPE (parm),
14996                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14997           return 1;
14998
14999         nargs = list_length (TYPE_ARG_TYPES (arg));
15000         args = XALLOCAVEC (tree, nargs);
15001         for (a = TYPE_ARG_TYPES (arg), i = 0;
15002              a != NULL_TREE && a != void_list_node;
15003              a = TREE_CHAIN (a), ++i)
15004           args[i] = TREE_VALUE (a);
15005         nargs = i;
15006
15007         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15008                                       args, nargs, 1, DEDUCE_EXACT,
15009                                       LOOKUP_NORMAL);
15010       }
15011
15012     case OFFSET_TYPE:
15013       /* Unify a pointer to member with a pointer to member function, which
15014          deduces the type of the member as a function type. */
15015       if (TYPE_PTRMEMFUNC_P (arg))
15016         {
15017           tree method_type;
15018           tree fntype;
15019           cp_cv_quals cv_quals;
15020
15021           /* Check top-level cv qualifiers */
15022           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15023             return 1;
15024
15025           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15026                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15027             return 1;
15028
15029           /* Determine the type of the function we are unifying against. */
15030           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15031           fntype =
15032             build_function_type (TREE_TYPE (method_type),
15033                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15034
15035           /* Extract the cv-qualifiers of the member function from the
15036              implicit object parameter and place them on the function
15037              type to be restored later. */
15038           cv_quals =
15039             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15040           fntype = build_qualified_type (fntype, cv_quals);
15041           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15042         }
15043
15044       if (TREE_CODE (arg) != OFFSET_TYPE)
15045         return 1;
15046       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15047                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15048         return 1;
15049       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15050                     strict);
15051
15052     case CONST_DECL:
15053       if (DECL_TEMPLATE_PARM_P (parm))
15054         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15055       if (arg != integral_constant_value (parm))
15056         return 1;
15057       return 0;
15058
15059     case FIELD_DECL:
15060     case TEMPLATE_DECL:
15061       /* Matched cases are handled by the ARG == PARM test above.  */
15062       return 1;
15063
15064     case VAR_DECL:
15065       /* A non-type template parameter that is a variable should be a
15066          an integral constant, in which case, it whould have been
15067          folded into its (constant) value. So we should not be getting
15068          a variable here.  */
15069       gcc_unreachable ();
15070
15071     case TYPE_ARGUMENT_PACK:
15072     case NONTYPE_ARGUMENT_PACK:
15073       {
15074         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15075         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15076         int i, len = TREE_VEC_LENGTH (packed_parms);
15077         int argslen = TREE_VEC_LENGTH (packed_args);
15078         int parm_variadic_p = 0;
15079
15080         for (i = 0; i < len; ++i)
15081           {
15082             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15083               {
15084                 if (i == len - 1)
15085                   /* We can unify against something with a trailing
15086                      parameter pack.  */
15087                   parm_variadic_p = 1;
15088                 else
15089                   /* Since there is something following the pack
15090                      expansion, we cannot unify this template argument
15091                      list.  */
15092                   return 0;
15093               }
15094           }
15095           
15096
15097         /* If we don't have enough arguments to satisfy the parameters
15098            (not counting the pack expression at the end), or we have
15099            too many arguments for a parameter list that doesn't end in
15100            a pack expression, we can't unify.  */
15101         if (argslen < (len - parm_variadic_p)
15102             || (argslen > len && !parm_variadic_p))
15103           return 1;
15104
15105         /* Unify all of the parameters that precede the (optional)
15106            pack expression.  */
15107         for (i = 0; i < len - parm_variadic_p; ++i)
15108           {
15109             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15110                        TREE_VEC_ELT (packed_args, i), strict))
15111               return 1;
15112           }
15113
15114         if (parm_variadic_p)
15115           return unify_pack_expansion (tparms, targs, 
15116                                        packed_parms, packed_args,
15117                                        strict, /*call_args_p=*/false,
15118                                        /*subr=*/false);
15119         return 0;
15120       }
15121
15122       break;
15123
15124     case TYPEOF_TYPE:
15125     case DECLTYPE_TYPE:
15126       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15127          nodes.  */
15128       return 0;
15129
15130     case ERROR_MARK:
15131       /* Unification fails if we hit an error node.  */
15132       return 1;
15133
15134     default:
15135       gcc_assert (EXPR_P (parm));
15136
15137       /* We must be looking at an expression.  This can happen with
15138          something like:
15139
15140            template <int I>
15141            void foo(S<I>, S<I + 2>);
15142
15143          This is a "nondeduced context":
15144
15145            [deduct.type]
15146
15147            The nondeduced contexts are:
15148
15149            --A type that is a template-id in which one or more of
15150              the template-arguments is an expression that references
15151              a template-parameter.
15152
15153          In these cases, we assume deduction succeeded, but don't
15154          actually infer any unifications.  */
15155
15156       if (!uses_template_parms (parm)
15157           && !template_args_equal (parm, arg))
15158         return 1;
15159       else
15160         return 0;
15161     }
15162 }
15163 \f
15164 /* Note that DECL can be defined in this translation unit, if
15165    required.  */
15166
15167 static void
15168 mark_definable (tree decl)
15169 {
15170   tree clone;
15171   DECL_NOT_REALLY_EXTERN (decl) = 1;
15172   FOR_EACH_CLONE (clone, decl)
15173     DECL_NOT_REALLY_EXTERN (clone) = 1;
15174 }
15175
15176 /* Called if RESULT is explicitly instantiated, or is a member of an
15177    explicitly instantiated class.  */
15178
15179 void
15180 mark_decl_instantiated (tree result, int extern_p)
15181 {
15182   SET_DECL_EXPLICIT_INSTANTIATION (result);
15183
15184   /* If this entity has already been written out, it's too late to
15185      make any modifications.  */
15186   if (TREE_ASM_WRITTEN (result))
15187     return;
15188
15189   if (TREE_CODE (result) != FUNCTION_DECL)
15190     /* The TREE_PUBLIC flag for function declarations will have been
15191        set correctly by tsubst.  */
15192     TREE_PUBLIC (result) = 1;
15193
15194   /* This might have been set by an earlier implicit instantiation.  */
15195   DECL_COMDAT (result) = 0;
15196
15197   if (extern_p)
15198     DECL_NOT_REALLY_EXTERN (result) = 0;
15199   else
15200     {
15201       mark_definable (result);
15202       /* Always make artificials weak.  */
15203       if (DECL_ARTIFICIAL (result) && flag_weak)
15204         comdat_linkage (result);
15205       /* For WIN32 we also want to put explicit instantiations in
15206          linkonce sections.  */
15207       else if (TREE_PUBLIC (result))
15208         maybe_make_one_only (result);
15209     }
15210
15211   /* If EXTERN_P, then this function will not be emitted -- unless
15212      followed by an explicit instantiation, at which point its linkage
15213      will be adjusted.  If !EXTERN_P, then this function will be
15214      emitted here.  In neither circumstance do we want
15215      import_export_decl to adjust the linkage.  */
15216   DECL_INTERFACE_KNOWN (result) = 1;
15217 }
15218
15219 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15220    important template arguments.  If any are missing, we check whether
15221    they're important by using error_mark_node for substituting into any
15222    args that were used for partial ordering (the ones between ARGS and END)
15223    and seeing if it bubbles up.  */
15224
15225 static bool
15226 check_undeduced_parms (tree targs, tree args, tree end)
15227 {
15228   bool found = false;
15229   int i;
15230   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15231     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15232       {
15233         found = true;
15234         TREE_VEC_ELT (targs, i) = error_mark_node;
15235       }
15236   if (found)
15237     {
15238       for (; args != end; args = TREE_CHAIN (args))
15239         {
15240           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15241           if (substed == error_mark_node)
15242             return true;
15243         }
15244     }
15245   return false;
15246 }
15247
15248 /* Given two function templates PAT1 and PAT2, return:
15249
15250    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15251    -1 if PAT2 is more specialized than PAT1.
15252    0 if neither is more specialized.
15253
15254    LEN indicates the number of parameters we should consider
15255    (defaulted parameters should not be considered).
15256
15257    The 1998 std underspecified function template partial ordering, and
15258    DR214 addresses the issue.  We take pairs of arguments, one from
15259    each of the templates, and deduce them against each other.  One of
15260    the templates will be more specialized if all the *other*
15261    template's arguments deduce against its arguments and at least one
15262    of its arguments *does* *not* deduce against the other template's
15263    corresponding argument.  Deduction is done as for class templates.
15264    The arguments used in deduction have reference and top level cv
15265    qualifiers removed.  Iff both arguments were originally reference
15266    types *and* deduction succeeds in both directions, the template
15267    with the more cv-qualified argument wins for that pairing (if
15268    neither is more cv-qualified, they both are equal).  Unlike regular
15269    deduction, after all the arguments have been deduced in this way,
15270    we do *not* verify the deduced template argument values can be
15271    substituted into non-deduced contexts.
15272
15273    The logic can be a bit confusing here, because we look at deduce1 and
15274    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15275    can find template arguments for pat1 to make arg1 look like arg2, that
15276    means that arg2 is at least as specialized as arg1.  */
15277
15278 int
15279 more_specialized_fn (tree pat1, tree pat2, int len)
15280 {
15281   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15282   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15283   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15284   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15285   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15286   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15287   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15288   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15289   tree origs1, origs2;
15290   bool lose1 = false;
15291   bool lose2 = false;
15292
15293   /* Remove the this parameter from non-static member functions.  If
15294      one is a non-static member function and the other is not a static
15295      member function, remove the first parameter from that function
15296      also.  This situation occurs for operator functions where we
15297      locate both a member function (with this pointer) and non-member
15298      operator (with explicit first operand).  */
15299   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15300     {
15301       len--; /* LEN is the number of significant arguments for DECL1 */
15302       args1 = TREE_CHAIN (args1);
15303       if (!DECL_STATIC_FUNCTION_P (decl2))
15304         args2 = TREE_CHAIN (args2);
15305     }
15306   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15307     {
15308       args2 = TREE_CHAIN (args2);
15309       if (!DECL_STATIC_FUNCTION_P (decl1))
15310         {
15311           len--;
15312           args1 = TREE_CHAIN (args1);
15313         }
15314     }
15315
15316   /* If only one is a conversion operator, they are unordered.  */
15317   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15318     return 0;
15319
15320   /* Consider the return type for a conversion function */
15321   if (DECL_CONV_FN_P (decl1))
15322     {
15323       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15324       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15325       len++;
15326     }
15327
15328   processing_template_decl++;
15329
15330   origs1 = args1;
15331   origs2 = args2;
15332
15333   while (len--
15334          /* Stop when an ellipsis is seen.  */
15335          && args1 != NULL_TREE && args2 != NULL_TREE)
15336     {
15337       tree arg1 = TREE_VALUE (args1);
15338       tree arg2 = TREE_VALUE (args2);
15339       int deduce1, deduce2;
15340       int quals1 = -1;
15341       int quals2 = -1;
15342
15343       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15344           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15345         {
15346           /* When both arguments are pack expansions, we need only
15347              unify the patterns themselves.  */
15348           arg1 = PACK_EXPANSION_PATTERN (arg1);
15349           arg2 = PACK_EXPANSION_PATTERN (arg2);
15350
15351           /* This is the last comparison we need to do.  */
15352           len = 0;
15353         }
15354
15355       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15356         {
15357           arg1 = TREE_TYPE (arg1);
15358           quals1 = cp_type_quals (arg1);
15359         }
15360
15361       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15362         {
15363           arg2 = TREE_TYPE (arg2);
15364           quals2 = cp_type_quals (arg2);
15365         }
15366
15367       if ((quals1 < 0) != (quals2 < 0))
15368         {
15369           /* Only of the args is a reference, see if we should apply
15370              array/function pointer decay to it.  This is not part of
15371              DR214, but is, IMHO, consistent with the deduction rules
15372              for the function call itself, and with our earlier
15373              implementation of the underspecified partial ordering
15374              rules.  (nathan).  */
15375           if (quals1 >= 0)
15376             {
15377               switch (TREE_CODE (arg1))
15378                 {
15379                 case ARRAY_TYPE:
15380                   arg1 = TREE_TYPE (arg1);
15381                   /* FALLTHROUGH. */
15382                 case FUNCTION_TYPE:
15383                   arg1 = build_pointer_type (arg1);
15384                   break;
15385
15386                 default:
15387                   break;
15388                 }
15389             }
15390           else
15391             {
15392               switch (TREE_CODE (arg2))
15393                 {
15394                 case ARRAY_TYPE:
15395                   arg2 = TREE_TYPE (arg2);
15396                   /* FALLTHROUGH. */
15397                 case FUNCTION_TYPE:
15398                   arg2 = build_pointer_type (arg2);
15399                   break;
15400
15401                 default:
15402                   break;
15403                 }
15404             }
15405         }
15406
15407       arg1 = TYPE_MAIN_VARIANT (arg1);
15408       arg2 = TYPE_MAIN_VARIANT (arg2);
15409
15410       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15411         {
15412           int i, len2 = list_length (args2);
15413           tree parmvec = make_tree_vec (1);
15414           tree argvec = make_tree_vec (len2);
15415           tree ta = args2;
15416
15417           /* Setup the parameter vector, which contains only ARG1.  */
15418           TREE_VEC_ELT (parmvec, 0) = arg1;
15419
15420           /* Setup the argument vector, which contains the remaining
15421              arguments.  */
15422           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15423             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15424
15425           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15426                                            argvec, UNIFY_ALLOW_NONE, 
15427                                            /*call_args_p=*/false, 
15428                                            /*subr=*/0);
15429
15430           /* We cannot deduce in the other direction, because ARG1 is
15431              a pack expansion but ARG2 is not.  */
15432           deduce2 = 0;
15433         }
15434       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15435         {
15436           int i, len1 = list_length (args1);
15437           tree parmvec = make_tree_vec (1);
15438           tree argvec = make_tree_vec (len1);
15439           tree ta = args1;
15440
15441           /* Setup the parameter vector, which contains only ARG1.  */
15442           TREE_VEC_ELT (parmvec, 0) = arg2;
15443
15444           /* Setup the argument vector, which contains the remaining
15445              arguments.  */
15446           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15447             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15448
15449           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15450                                            argvec, UNIFY_ALLOW_NONE, 
15451                                            /*call_args_p=*/false, 
15452                                            /*subr=*/0);
15453
15454           /* We cannot deduce in the other direction, because ARG2 is
15455              a pack expansion but ARG1 is not.*/
15456           deduce1 = 0;
15457         }
15458
15459       else
15460         {
15461           /* The normal case, where neither argument is a pack
15462              expansion.  */
15463           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15464           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15465         }
15466
15467       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15468          arg2, then arg2 is not as specialized as arg1.  */
15469       if (!deduce1)
15470         lose2 = true;
15471       if (!deduce2)
15472         lose1 = true;
15473
15474       /* "If, for a given type, deduction succeeds in both directions
15475          (i.e., the types are identical after the transformations above)
15476          and if the type from the argument template is more cv-qualified
15477          than the type from the parameter template (as described above)
15478          that type is considered to be more specialized than the other. If
15479          neither type is more cv-qualified than the other then neither type
15480          is more specialized than the other."  */
15481
15482       if (deduce1 && deduce2
15483           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15484         {
15485           if ((quals1 & quals2) == quals2)
15486             lose2 = true;
15487           if ((quals1 & quals2) == quals1)
15488             lose1 = true;
15489         }
15490
15491       if (lose1 && lose2)
15492         /* We've failed to deduce something in either direction.
15493            These must be unordered.  */
15494         break;
15495
15496       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15497           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15498         /* We have already processed all of the arguments in our
15499            handing of the pack expansion type.  */
15500         len = 0;
15501
15502       args1 = TREE_CHAIN (args1);
15503       args2 = TREE_CHAIN (args2);
15504     }
15505
15506   /* "In most cases, all template parameters must have values in order for
15507      deduction to succeed, but for partial ordering purposes a template
15508      parameter may remain without a value provided it is not used in the
15509      types being used for partial ordering."
15510
15511      Thus, if we are missing any of the targs1 we need to substitute into
15512      origs1, then pat2 is not as specialized as pat1.  This can happen when
15513      there is a nondeduced context.  */
15514   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15515     lose2 = true;
15516   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15517     lose1 = true;
15518
15519   processing_template_decl--;
15520
15521   /* All things being equal, if the next argument is a pack expansion
15522      for one function but not for the other, prefer the
15523      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15524   if (lose1 == lose2
15525       && args1 && TREE_VALUE (args1)
15526       && args2 && TREE_VALUE (args2))
15527     {
15528       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15529       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15530     }
15531
15532   if (lose1 == lose2)
15533     return 0;
15534   else if (!lose1)
15535     return 1;
15536   else
15537     return -1;
15538 }
15539
15540 /* Determine which of two partial specializations is more specialized.
15541
15542    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15543    to the first partial specialization.  The TREE_VALUE is the
15544    innermost set of template parameters for the partial
15545    specialization.  PAT2 is similar, but for the second template.
15546
15547    Return 1 if the first partial specialization is more specialized;
15548    -1 if the second is more specialized; 0 if neither is more
15549    specialized.
15550
15551    See [temp.class.order] for information about determining which of
15552    two templates is more specialized.  */
15553
15554 static int
15555 more_specialized_class (tree pat1, tree pat2)
15556 {
15557   tree targs;
15558   tree tmpl1, tmpl2;
15559   int winner = 0;
15560   bool any_deductions = false;
15561
15562   tmpl1 = TREE_TYPE (pat1);
15563   tmpl2 = TREE_TYPE (pat2);
15564
15565   /* Just like what happens for functions, if we are ordering between
15566      different class template specializations, we may encounter dependent
15567      types in the arguments, and we need our dependency check functions
15568      to behave correctly.  */
15569   ++processing_template_decl;
15570   targs = get_class_bindings (TREE_VALUE (pat1),
15571                               CLASSTYPE_TI_ARGS (tmpl1),
15572                               CLASSTYPE_TI_ARGS (tmpl2));
15573   if (targs)
15574     {
15575       --winner;
15576       any_deductions = true;
15577     }
15578
15579   targs = get_class_bindings (TREE_VALUE (pat2),
15580                               CLASSTYPE_TI_ARGS (tmpl2),
15581                               CLASSTYPE_TI_ARGS (tmpl1));
15582   if (targs)
15583     {
15584       ++winner;
15585       any_deductions = true;
15586     }
15587   --processing_template_decl;
15588
15589   /* In the case of a tie where at least one of the class templates
15590      has a parameter pack at the end, the template with the most
15591      non-packed parameters wins.  */
15592   if (winner == 0
15593       && any_deductions
15594       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15595           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15596     {
15597       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15598       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15599       int len1 = TREE_VEC_LENGTH (args1);
15600       int len2 = TREE_VEC_LENGTH (args2);
15601
15602       /* We don't count the pack expansion at the end.  */
15603       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15604         --len1;
15605       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15606         --len2;
15607
15608       if (len1 > len2)
15609         return 1;
15610       else if (len1 < len2)
15611         return -1;
15612     }
15613
15614   return winner;
15615 }
15616
15617 /* Return the template arguments that will produce the function signature
15618    DECL from the function template FN, with the explicit template
15619    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15620    also match.  Return NULL_TREE if no satisfactory arguments could be
15621    found.  */
15622
15623 static tree
15624 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15625 {
15626   int ntparms = DECL_NTPARMS (fn);
15627   tree targs = make_tree_vec (ntparms);
15628   tree decl_type;
15629   tree decl_arg_types;
15630   tree *args;
15631   unsigned int nargs, ix;
15632   tree arg;
15633
15634   /* Substitute the explicit template arguments into the type of DECL.
15635      The call to fn_type_unification will handle substitution into the
15636      FN.  */
15637   decl_type = TREE_TYPE (decl);
15638   if (explicit_args && uses_template_parms (decl_type))
15639     {
15640       tree tmpl;
15641       tree converted_args;
15642
15643       if (DECL_TEMPLATE_INFO (decl))
15644         tmpl = DECL_TI_TEMPLATE (decl);
15645       else
15646         /* We can get here for some invalid specializations.  */
15647         return NULL_TREE;
15648
15649       converted_args
15650         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15651                                  explicit_args, NULL_TREE,
15652                                  tf_none,
15653                                  /*require_all_args=*/false,
15654                                  /*use_default_args=*/false);
15655       if (converted_args == error_mark_node)
15656         return NULL_TREE;
15657
15658       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15659       if (decl_type == error_mark_node)
15660         return NULL_TREE;
15661     }
15662
15663   /* Never do unification on the 'this' parameter.  */
15664   decl_arg_types = skip_artificial_parms_for (decl, 
15665                                               TYPE_ARG_TYPES (decl_type));
15666
15667   nargs = list_length (decl_arg_types);
15668   args = XALLOCAVEC (tree, nargs);
15669   for (arg = decl_arg_types, ix = 0;
15670        arg != NULL_TREE && arg != void_list_node;
15671        arg = TREE_CHAIN (arg), ++ix)
15672     args[ix] = TREE_VALUE (arg);
15673
15674   if (fn_type_unification (fn, explicit_args, targs,
15675                            args, ix,
15676                            (check_rettype || DECL_CONV_FN_P (fn)
15677                             ? TREE_TYPE (decl_type) : NULL_TREE),
15678                            DEDUCE_EXACT, LOOKUP_NORMAL))
15679     return NULL_TREE;
15680
15681   return targs;
15682 }
15683
15684 /* Return the innermost template arguments that, when applied to a
15685    template specialization whose innermost template parameters are
15686    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15687    ARGS.
15688
15689    For example, suppose we have:
15690
15691      template <class T, class U> struct S {};
15692      template <class T> struct S<T*, int> {};
15693
15694    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15695    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15696    int}.  The resulting vector will be {double}, indicating that `T'
15697    is bound to `double'.  */
15698
15699 static tree
15700 get_class_bindings (tree tparms, tree spec_args, tree args)
15701 {
15702   int i, ntparms = TREE_VEC_LENGTH (tparms);
15703   tree deduced_args;
15704   tree innermost_deduced_args;
15705
15706   innermost_deduced_args = make_tree_vec (ntparms);
15707   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15708     {
15709       deduced_args = copy_node (args);
15710       SET_TMPL_ARGS_LEVEL (deduced_args,
15711                            TMPL_ARGS_DEPTH (deduced_args),
15712                            innermost_deduced_args);
15713     }
15714   else
15715     deduced_args = innermost_deduced_args;
15716
15717   if (unify (tparms, deduced_args,
15718              INNERMOST_TEMPLATE_ARGS (spec_args),
15719              INNERMOST_TEMPLATE_ARGS (args),
15720              UNIFY_ALLOW_NONE))
15721     return NULL_TREE;
15722
15723   for (i =  0; i < ntparms; ++i)
15724     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15725       return NULL_TREE;
15726
15727   /* Verify that nondeduced template arguments agree with the type
15728      obtained from argument deduction.
15729
15730      For example:
15731
15732        struct A { typedef int X; };
15733        template <class T, class U> struct C {};
15734        template <class T> struct C<T, typename T::X> {};
15735
15736      Then with the instantiation `C<A, int>', we can deduce that
15737      `T' is `A' but unify () does not check whether `typename T::X'
15738      is `int'.  */
15739   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15740   if (spec_args == error_mark_node
15741       /* We only need to check the innermost arguments; the other
15742          arguments will always agree.  */
15743       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15744                               INNERMOST_TEMPLATE_ARGS (args)))
15745     return NULL_TREE;
15746
15747   /* Now that we have bindings for all of the template arguments,
15748      ensure that the arguments deduced for the template template
15749      parameters have compatible template parameter lists.  See the use
15750      of template_template_parm_bindings_ok_p in fn_type_unification
15751      for more information.  */
15752   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15753     return NULL_TREE;
15754
15755   return deduced_args;
15756 }
15757
15758 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15759    Return the TREE_LIST node with the most specialized template, if
15760    any.  If there is no most specialized template, the error_mark_node
15761    is returned.
15762
15763    Note that this function does not look at, or modify, the
15764    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15765    returned is one of the elements of INSTANTIATIONS, callers may
15766    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15767    and retrieve it from the value returned.  */
15768
15769 tree
15770 most_specialized_instantiation (tree templates)
15771 {
15772   tree fn, champ;
15773
15774   ++processing_template_decl;
15775
15776   champ = templates;
15777   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15778     {
15779       int fate = 0;
15780
15781       if (get_bindings (TREE_VALUE (champ),
15782                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15783                         NULL_TREE, /*check_ret=*/false))
15784         fate--;
15785
15786       if (get_bindings (TREE_VALUE (fn),
15787                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15788                         NULL_TREE, /*check_ret=*/false))
15789         fate++;
15790
15791       if (fate == -1)
15792         champ = fn;
15793       else if (!fate)
15794         {
15795           /* Equally specialized, move to next function.  If there
15796              is no next function, nothing's most specialized.  */
15797           fn = TREE_CHAIN (fn);
15798           champ = fn;
15799           if (!fn)
15800             break;
15801         }
15802     }
15803
15804   if (champ)
15805     /* Now verify that champ is better than everything earlier in the
15806        instantiation list.  */
15807     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15808       if (get_bindings (TREE_VALUE (champ),
15809                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15810                         NULL_TREE, /*check_ret=*/false)
15811           || !get_bindings (TREE_VALUE (fn),
15812                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15813                             NULL_TREE, /*check_ret=*/false))
15814         {
15815           champ = NULL_TREE;
15816           break;
15817         }
15818
15819   processing_template_decl--;
15820
15821   if (!champ)
15822     return error_mark_node;
15823
15824   return champ;
15825 }
15826
15827 /* If DECL is a specialization of some template, return the most
15828    general such template.  Otherwise, returns NULL_TREE.
15829
15830    For example, given:
15831
15832      template <class T> struct S { template <class U> void f(U); };
15833
15834    if TMPL is `template <class U> void S<int>::f(U)' this will return
15835    the full template.  This function will not trace past partial
15836    specializations, however.  For example, given in addition:
15837
15838      template <class T> struct S<T*> { template <class U> void f(U); };
15839
15840    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15841    `template <class T> template <class U> S<T*>::f(U)'.  */
15842
15843 tree
15844 most_general_template (tree decl)
15845 {
15846   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15847      an immediate specialization.  */
15848   if (TREE_CODE (decl) == FUNCTION_DECL)
15849     {
15850       if (DECL_TEMPLATE_INFO (decl)) {
15851         decl = DECL_TI_TEMPLATE (decl);
15852
15853         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15854            template friend.  */
15855         if (TREE_CODE (decl) != TEMPLATE_DECL)
15856           return NULL_TREE;
15857       } else
15858         return NULL_TREE;
15859     }
15860
15861   /* Look for more and more general templates.  */
15862   while (DECL_TEMPLATE_INFO (decl))
15863     {
15864       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15865          (See cp-tree.h for details.)  */
15866       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15867         break;
15868
15869       if (CLASS_TYPE_P (TREE_TYPE (decl))
15870           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15871         break;
15872
15873       /* Stop if we run into an explicitly specialized class template.  */
15874       if (!DECL_NAMESPACE_SCOPE_P (decl)
15875           && DECL_CONTEXT (decl)
15876           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15877         break;
15878
15879       decl = DECL_TI_TEMPLATE (decl);
15880     }
15881
15882   return decl;
15883 }
15884
15885 /* Return the most specialized of the class template partial
15886    specializations of TMPL which can produce TYPE, a specialization of
15887    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15888    a _TYPE node corresponding to the partial specialization, while the
15889    TREE_PURPOSE is the set of template arguments that must be
15890    substituted into the TREE_TYPE in order to generate TYPE.
15891
15892    If the choice of partial specialization is ambiguous, a diagnostic
15893    is issued, and the error_mark_node is returned.  If there are no
15894    partial specializations of TMPL matching TYPE, then NULL_TREE is
15895    returned.  */
15896
15897 static tree
15898 most_specialized_class (tree type, tree tmpl)
15899 {
15900   tree list = NULL_TREE;
15901   tree t;
15902   tree champ;
15903   int fate;
15904   bool ambiguous_p;
15905   tree args;
15906   tree outer_args = NULL_TREE;
15907
15908   tmpl = most_general_template (tmpl);
15909   args = CLASSTYPE_TI_ARGS (type);
15910
15911   /* For determining which partial specialization to use, only the
15912      innermost args are interesting.  */
15913   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15914     {
15915       outer_args = strip_innermost_template_args (args, 1);
15916       args = INNERMOST_TEMPLATE_ARGS (args);
15917     }
15918
15919   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15920     {
15921       tree partial_spec_args;
15922       tree spec_args;
15923       tree parms = TREE_VALUE (t);
15924
15925       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15926       if (outer_args)
15927         {
15928           int i;
15929
15930           ++processing_template_decl;
15931
15932           /* Discard the outer levels of args, and then substitute in the
15933              template args from the enclosing class.  */
15934           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15935           partial_spec_args = tsubst_template_args
15936             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15937
15938           /* PARMS already refers to just the innermost parms, but the
15939              template parms in partial_spec_args had their levels lowered
15940              by tsubst, so we need to do the same for the parm list.  We
15941              can't just tsubst the TREE_VEC itself, as tsubst wants to
15942              treat a TREE_VEC as an argument vector.  */
15943           parms = copy_node (parms);
15944           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15945             TREE_VEC_ELT (parms, i) =
15946               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15947
15948           --processing_template_decl;
15949         }
15950
15951       partial_spec_args =
15952           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15953                                  add_to_template_args (outer_args,
15954                                                        partial_spec_args),
15955                                  tmpl, tf_none,
15956                                  /*require_all_args=*/true,
15957                                  /*use_default_args=*/true);
15958
15959       if (partial_spec_args == error_mark_node)
15960         return error_mark_node;
15961
15962       spec_args = get_class_bindings (parms,
15963                                       partial_spec_args,
15964                                       args);
15965       if (spec_args)
15966         {
15967           if (outer_args)
15968             spec_args = add_to_template_args (outer_args, spec_args);
15969           list = tree_cons (spec_args, TREE_VALUE (t), list);
15970           TREE_TYPE (list) = TREE_TYPE (t);
15971         }
15972     }
15973
15974   if (! list)
15975     return NULL_TREE;
15976
15977   ambiguous_p = false;
15978   t = list;
15979   champ = t;
15980   t = TREE_CHAIN (t);
15981   for (; t; t = TREE_CHAIN (t))
15982     {
15983       fate = more_specialized_class (champ, t);
15984       if (fate == 1)
15985         ;
15986       else
15987         {
15988           if (fate == 0)
15989             {
15990               t = TREE_CHAIN (t);
15991               if (! t)
15992                 {
15993                   ambiguous_p = true;
15994                   break;
15995                 }
15996             }
15997           champ = t;
15998         }
15999     }
16000
16001   if (!ambiguous_p)
16002     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16003       {
16004         fate = more_specialized_class (champ, t);
16005         if (fate != 1)
16006           {
16007             ambiguous_p = true;
16008             break;
16009           }
16010       }
16011
16012   if (ambiguous_p)
16013     {
16014       const char *str;
16015       char *spaces = NULL;
16016       error ("ambiguous class template instantiation for %q#T", type);
16017       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16018       for (t = list; t; t = TREE_CHAIN (t))
16019         {
16020           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16021           spaces = spaces ? spaces : get_spaces (str);
16022         }
16023       free (spaces);
16024       return error_mark_node;
16025     }
16026
16027   return champ;
16028 }
16029
16030 /* Explicitly instantiate DECL.  */
16031
16032 void
16033 do_decl_instantiation (tree decl, tree storage)
16034 {
16035   tree result = NULL_TREE;
16036   int extern_p = 0;
16037
16038   if (!decl || decl == error_mark_node)
16039     /* An error occurred, for which grokdeclarator has already issued
16040        an appropriate message.  */
16041     return;
16042   else if (! DECL_LANG_SPECIFIC (decl))
16043     {
16044       error ("explicit instantiation of non-template %q#D", decl);
16045       return;
16046     }
16047   else if (TREE_CODE (decl) == VAR_DECL)
16048     {
16049       /* There is an asymmetry here in the way VAR_DECLs and
16050          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16051          the latter, the DECL we get back will be marked as a
16052          template instantiation, and the appropriate
16053          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16054          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16055          should handle VAR_DECLs as it currently handles
16056          FUNCTION_DECLs.  */
16057       if (!DECL_CLASS_SCOPE_P (decl))
16058         {
16059           error ("%qD is not a static data member of a class template", decl);
16060           return;
16061         }
16062       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16063       if (!result || TREE_CODE (result) != VAR_DECL)
16064         {
16065           error ("no matching template for %qD found", decl);
16066           return;
16067         }
16068       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16069         {
16070           error ("type %qT for explicit instantiation %qD does not match "
16071                  "declared type %qT", TREE_TYPE (result), decl,
16072                  TREE_TYPE (decl));
16073           return;
16074         }
16075     }
16076   else if (TREE_CODE (decl) != FUNCTION_DECL)
16077     {
16078       error ("explicit instantiation of %q#D", decl);
16079       return;
16080     }
16081   else
16082     result = decl;
16083
16084   /* Check for various error cases.  Note that if the explicit
16085      instantiation is valid the RESULT will currently be marked as an
16086      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16087      until we get here.  */
16088
16089   if (DECL_TEMPLATE_SPECIALIZATION (result))
16090     {
16091       /* DR 259 [temp.spec].
16092
16093          Both an explicit instantiation and a declaration of an explicit
16094          specialization shall not appear in a program unless the explicit
16095          instantiation follows a declaration of the explicit specialization.
16096
16097          For a given set of template parameters, if an explicit
16098          instantiation of a template appears after a declaration of an
16099          explicit specialization for that template, the explicit
16100          instantiation has no effect.  */
16101       return;
16102     }
16103   else if (DECL_EXPLICIT_INSTANTIATION (result))
16104     {
16105       /* [temp.spec]
16106
16107          No program shall explicitly instantiate any template more
16108          than once.
16109
16110          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16111          the first instantiation was `extern' and the second is not,
16112          and EXTERN_P for the opposite case.  */
16113       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16114         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16115       /* If an "extern" explicit instantiation follows an ordinary
16116          explicit instantiation, the template is instantiated.  */
16117       if (extern_p)
16118         return;
16119     }
16120   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16121     {
16122       error ("no matching template for %qD found", result);
16123       return;
16124     }
16125   else if (!DECL_TEMPLATE_INFO (result))
16126     {
16127       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16128       return;
16129     }
16130
16131   if (storage == NULL_TREE)
16132     ;
16133   else if (storage == ridpointers[(int) RID_EXTERN])
16134     {
16135       if (!in_system_header && (cxx_dialect == cxx98))
16136         pedwarn (input_location, OPT_pedantic, 
16137                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16138                  "instantiations");
16139       extern_p = 1;
16140     }
16141   else
16142     error ("storage class %qD applied to template instantiation", storage);
16143
16144   check_explicit_instantiation_namespace (result);
16145   mark_decl_instantiated (result, extern_p);
16146   if (! extern_p)
16147     instantiate_decl (result, /*defer_ok=*/1,
16148                       /*expl_inst_class_mem_p=*/false);
16149 }
16150
16151 static void
16152 mark_class_instantiated (tree t, int extern_p)
16153 {
16154   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16155   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16156   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16157   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16158   if (! extern_p)
16159     {
16160       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16161       rest_of_type_compilation (t, 1);
16162     }
16163 }
16164
16165 /* Called from do_type_instantiation through binding_table_foreach to
16166    do recursive instantiation for the type bound in ENTRY.  */
16167 static void
16168 bt_instantiate_type_proc (binding_entry entry, void *data)
16169 {
16170   tree storage = *(tree *) data;
16171
16172   if (MAYBE_CLASS_TYPE_P (entry->type)
16173       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16174     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16175 }
16176
16177 /* Called from do_type_instantiation to instantiate a member
16178    (a member function or a static member variable) of an
16179    explicitly instantiated class template.  */
16180 static void
16181 instantiate_class_member (tree decl, int extern_p)
16182 {
16183   mark_decl_instantiated (decl, extern_p);
16184   if (! extern_p)
16185     instantiate_decl (decl, /*defer_ok=*/1,
16186                       /*expl_inst_class_mem_p=*/true);
16187 }
16188
16189 /* Perform an explicit instantiation of template class T.  STORAGE, if
16190    non-null, is the RID for extern, inline or static.  COMPLAIN is
16191    nonzero if this is called from the parser, zero if called recursively,
16192    since the standard is unclear (as detailed below).  */
16193
16194 void
16195 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16196 {
16197   int extern_p = 0;
16198   int nomem_p = 0;
16199   int static_p = 0;
16200   int previous_instantiation_extern_p = 0;
16201
16202   if (TREE_CODE (t) == TYPE_DECL)
16203     t = TREE_TYPE (t);
16204
16205   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16206     {
16207       error ("explicit instantiation of non-template type %qT", t);
16208       return;
16209     }
16210
16211   complete_type (t);
16212
16213   if (!COMPLETE_TYPE_P (t))
16214     {
16215       if (complain & tf_error)
16216         error ("explicit instantiation of %q#T before definition of template",
16217                t);
16218       return;
16219     }
16220
16221   if (storage != NULL_TREE)
16222     {
16223       if (!in_system_header)
16224         {
16225           if (storage == ridpointers[(int) RID_EXTERN])
16226             {
16227               if (cxx_dialect == cxx98)
16228                 pedwarn (input_location, OPT_pedantic, 
16229                          "ISO C++ 1998 forbids the use of %<extern%> on "
16230                          "explicit instantiations");
16231             }
16232           else
16233             pedwarn (input_location, OPT_pedantic, 
16234                      "ISO C++ forbids the use of %qE"
16235                      " on explicit instantiations", storage);
16236         }
16237
16238       if (storage == ridpointers[(int) RID_INLINE])
16239         nomem_p = 1;
16240       else if (storage == ridpointers[(int) RID_EXTERN])
16241         extern_p = 1;
16242       else if (storage == ridpointers[(int) RID_STATIC])
16243         static_p = 1;
16244       else
16245         {
16246           error ("storage class %qD applied to template instantiation",
16247                  storage);
16248           extern_p = 0;
16249         }
16250     }
16251
16252   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16253     {
16254       /* DR 259 [temp.spec].
16255
16256          Both an explicit instantiation and a declaration of an explicit
16257          specialization shall not appear in a program unless the explicit
16258          instantiation follows a declaration of the explicit specialization.
16259
16260          For a given set of template parameters, if an explicit
16261          instantiation of a template appears after a declaration of an
16262          explicit specialization for that template, the explicit
16263          instantiation has no effect.  */
16264       return;
16265     }
16266   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16267     {
16268       /* [temp.spec]
16269
16270          No program shall explicitly instantiate any template more
16271          than once.
16272
16273          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16274          instantiation was `extern'.  If EXTERN_P then the second is.
16275          These cases are OK.  */
16276       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16277
16278       if (!previous_instantiation_extern_p && !extern_p
16279           && (complain & tf_error))
16280         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16281
16282       /* If we've already instantiated the template, just return now.  */
16283       if (!CLASSTYPE_INTERFACE_ONLY (t))
16284         return;
16285     }
16286
16287   check_explicit_instantiation_namespace (TYPE_NAME (t));
16288   mark_class_instantiated (t, extern_p);
16289
16290   if (nomem_p)
16291     return;
16292
16293   {
16294     tree tmp;
16295
16296     /* In contrast to implicit instantiation, where only the
16297        declarations, and not the definitions, of members are
16298        instantiated, we have here:
16299
16300          [temp.explicit]
16301
16302          The explicit instantiation of a class template specialization
16303          implies the instantiation of all of its members not
16304          previously explicitly specialized in the translation unit
16305          containing the explicit instantiation.
16306
16307        Of course, we can't instantiate member template classes, since
16308        we don't have any arguments for them.  Note that the standard
16309        is unclear on whether the instantiation of the members are
16310        *explicit* instantiations or not.  However, the most natural
16311        interpretation is that it should be an explicit instantiation.  */
16312
16313     if (! static_p)
16314       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16315         if (TREE_CODE (tmp) == FUNCTION_DECL
16316             && DECL_TEMPLATE_INSTANTIATION (tmp))
16317           instantiate_class_member (tmp, extern_p);
16318
16319     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16320       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16321         instantiate_class_member (tmp, extern_p);
16322
16323     if (CLASSTYPE_NESTED_UTDS (t))
16324       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16325                              bt_instantiate_type_proc, &storage);
16326   }
16327 }
16328
16329 /* Given a function DECL, which is a specialization of TMPL, modify
16330    DECL to be a re-instantiation of TMPL with the same template
16331    arguments.  TMPL should be the template into which tsubst'ing
16332    should occur for DECL, not the most general template.
16333
16334    One reason for doing this is a scenario like this:
16335
16336      template <class T>
16337      void f(const T&, int i);
16338
16339      void g() { f(3, 7); }
16340
16341      template <class T>
16342      void f(const T& t, const int i) { }
16343
16344    Note that when the template is first instantiated, with
16345    instantiate_template, the resulting DECL will have no name for the
16346    first parameter, and the wrong type for the second.  So, when we go
16347    to instantiate the DECL, we regenerate it.  */
16348
16349 static void
16350 regenerate_decl_from_template (tree decl, tree tmpl)
16351 {
16352   /* The arguments used to instantiate DECL, from the most general
16353      template.  */
16354   tree args;
16355   tree code_pattern;
16356
16357   args = DECL_TI_ARGS (decl);
16358   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16359
16360   /* Make sure that we can see identifiers, and compute access
16361      correctly.  */
16362   push_access_scope (decl);
16363
16364   if (TREE_CODE (decl) == FUNCTION_DECL)
16365     {
16366       tree decl_parm;
16367       tree pattern_parm;
16368       tree specs;
16369       int args_depth;
16370       int parms_depth;
16371
16372       args_depth = TMPL_ARGS_DEPTH (args);
16373       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16374       if (args_depth > parms_depth)
16375         args = get_innermost_template_args (args, parms_depth);
16376
16377       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16378                                               args, tf_error, NULL_TREE);
16379       if (specs)
16380         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16381                                                     specs);
16382
16383       /* Merge parameter declarations.  */
16384       decl_parm = skip_artificial_parms_for (decl,
16385                                              DECL_ARGUMENTS (decl));
16386       pattern_parm
16387         = skip_artificial_parms_for (code_pattern,
16388                                      DECL_ARGUMENTS (code_pattern));
16389       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16390         {
16391           tree parm_type;
16392           tree attributes;
16393           
16394           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16395             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16396           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16397                               NULL_TREE);
16398           parm_type = type_decays_to (parm_type);
16399           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16400             TREE_TYPE (decl_parm) = parm_type;
16401           attributes = DECL_ATTRIBUTES (pattern_parm);
16402           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16403             {
16404               DECL_ATTRIBUTES (decl_parm) = attributes;
16405               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16406             }
16407           decl_parm = TREE_CHAIN (decl_parm);
16408           pattern_parm = TREE_CHAIN (pattern_parm);
16409         }
16410       /* Merge any parameters that match with the function parameter
16411          pack.  */
16412       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16413         {
16414           int i, len;
16415           tree expanded_types;
16416           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16417              the parameters in this function parameter pack.  */
16418           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16419                                                  args, tf_error, NULL_TREE);
16420           len = TREE_VEC_LENGTH (expanded_types);
16421           for (i = 0; i < len; i++)
16422             {
16423               tree parm_type;
16424               tree attributes;
16425           
16426               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16427                 /* Rename the parameter to include the index.  */
16428                 DECL_NAME (decl_parm) = 
16429                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16430               parm_type = TREE_VEC_ELT (expanded_types, i);
16431               parm_type = type_decays_to (parm_type);
16432               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16433                 TREE_TYPE (decl_parm) = parm_type;
16434               attributes = DECL_ATTRIBUTES (pattern_parm);
16435               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16436                 {
16437                   DECL_ATTRIBUTES (decl_parm) = attributes;
16438                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16439                 }
16440               decl_parm = TREE_CHAIN (decl_parm);
16441             }
16442         }
16443       /* Merge additional specifiers from the CODE_PATTERN.  */
16444       if (DECL_DECLARED_INLINE_P (code_pattern)
16445           && !DECL_DECLARED_INLINE_P (decl))
16446         DECL_DECLARED_INLINE_P (decl) = 1;
16447     }
16448   else if (TREE_CODE (decl) == VAR_DECL)
16449     DECL_INITIAL (decl) =
16450       tsubst_expr (DECL_INITIAL (code_pattern), args,
16451                    tf_error, DECL_TI_TEMPLATE (decl),
16452                    /*integral_constant_expression_p=*/false);
16453   else
16454     gcc_unreachable ();
16455
16456   pop_access_scope (decl);
16457 }
16458
16459 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16460    substituted to get DECL.  */
16461
16462 tree
16463 template_for_substitution (tree decl)
16464 {
16465   tree tmpl = DECL_TI_TEMPLATE (decl);
16466
16467   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16468      for the instantiation.  This is not always the most general
16469      template.  Consider, for example:
16470
16471         template <class T>
16472         struct S { template <class U> void f();
16473                    template <> void f<int>(); };
16474
16475      and an instantiation of S<double>::f<int>.  We want TD to be the
16476      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16477   while (/* An instantiation cannot have a definition, so we need a
16478             more general template.  */
16479          DECL_TEMPLATE_INSTANTIATION (tmpl)
16480            /* We must also deal with friend templates.  Given:
16481
16482                 template <class T> struct S {
16483                   template <class U> friend void f() {};
16484                 };
16485
16486               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16487               so far as the language is concerned, but that's still
16488               where we get the pattern for the instantiation from.  On
16489               other hand, if the definition comes outside the class, say:
16490
16491                 template <class T> struct S {
16492                   template <class U> friend void f();
16493                 };
16494                 template <class U> friend void f() {}
16495
16496               we don't need to look any further.  That's what the check for
16497               DECL_INITIAL is for.  */
16498           || (TREE_CODE (decl) == FUNCTION_DECL
16499               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16500               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16501     {
16502       /* The present template, TD, should not be a definition.  If it
16503          were a definition, we should be using it!  Note that we
16504          cannot restructure the loop to just keep going until we find
16505          a template with a definition, since that might go too far if
16506          a specialization was declared, but not defined.  */
16507       gcc_assert (TREE_CODE (decl) != VAR_DECL
16508                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16509
16510       /* Fetch the more general template.  */
16511       tmpl = DECL_TI_TEMPLATE (tmpl);
16512     }
16513
16514   return tmpl;
16515 }
16516
16517 /* Returns true if we need to instantiate this template instance even if we
16518    know we aren't going to emit it..  */
16519
16520 bool
16521 always_instantiate_p (tree decl)
16522 {
16523   /* We always instantiate inline functions so that we can inline them.  An
16524      explicit instantiation declaration prohibits implicit instantiation of
16525      non-inline functions.  With high levels of optimization, we would
16526      normally inline non-inline functions -- but we're not allowed to do
16527      that for "extern template" functions.  Therefore, we check
16528      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16529   return ((TREE_CODE (decl) == FUNCTION_DECL
16530            && DECL_DECLARED_INLINE_P (decl))
16531           /* And we need to instantiate static data members so that
16532              their initializers are available in integral constant
16533              expressions.  */
16534           || (TREE_CODE (decl) == VAR_DECL
16535               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16536 }
16537
16538 /* Produce the definition of D, a _DECL generated from a template.  If
16539    DEFER_OK is nonzero, then we don't have to actually do the
16540    instantiation now; we just have to do it sometime.  Normally it is
16541    an error if this is an explicit instantiation but D is undefined.
16542    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16543    explicitly instantiated class template.  */
16544
16545 tree
16546 instantiate_decl (tree d, int defer_ok,
16547                   bool expl_inst_class_mem_p)
16548 {
16549   tree tmpl = DECL_TI_TEMPLATE (d);
16550   tree gen_args;
16551   tree args;
16552   tree td;
16553   tree code_pattern;
16554   tree spec;
16555   tree gen_tmpl;
16556   bool pattern_defined;
16557   int need_push;
16558   location_t saved_loc = input_location;
16559   bool external_p;
16560
16561   /* This function should only be used to instantiate templates for
16562      functions and static member variables.  */
16563   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16564               || TREE_CODE (d) == VAR_DECL);
16565
16566   /* Variables are never deferred; if instantiation is required, they
16567      are instantiated right away.  That allows for better code in the
16568      case that an expression refers to the value of the variable --
16569      if the variable has a constant value the referring expression can
16570      take advantage of that fact.  */
16571   if (TREE_CODE (d) == VAR_DECL)
16572     defer_ok = 0;
16573
16574   /* Don't instantiate cloned functions.  Instead, instantiate the
16575      functions they cloned.  */
16576   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16577     d = DECL_CLONED_FUNCTION (d);
16578
16579   if (DECL_TEMPLATE_INSTANTIATED (d)
16580       || DECL_TEMPLATE_SPECIALIZATION (d))
16581     /* D has already been instantiated or explicitly specialized, so
16582        there's nothing for us to do here.
16583
16584        It might seem reasonable to check whether or not D is an explicit
16585        instantiation, and, if so, stop here.  But when an explicit
16586        instantiation is deferred until the end of the compilation,
16587        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16588        the instantiation.  */
16589     return d;
16590
16591   /* Check to see whether we know that this template will be
16592      instantiated in some other file, as with "extern template"
16593      extension.  */
16594   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16595
16596   /* In general, we do not instantiate such templates.  */
16597   if (external_p && !always_instantiate_p (d))
16598     return d;
16599
16600   gen_tmpl = most_general_template (tmpl);
16601   gen_args = DECL_TI_ARGS (d);
16602
16603   if (tmpl != gen_tmpl)
16604     /* We should already have the extra args.  */
16605     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16606                 == TMPL_ARGS_DEPTH (gen_args));
16607   /* And what's in the hash table should match D.  */
16608   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16609               || spec == NULL_TREE);
16610
16611   /* This needs to happen before any tsubsting.  */
16612   if (! push_tinst_level (d))
16613     return d;
16614
16615   timevar_push (TV_PARSE);
16616
16617   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16618      for the instantiation.  */
16619   td = template_for_substitution (d);
16620   code_pattern = DECL_TEMPLATE_RESULT (td);
16621
16622   /* We should never be trying to instantiate a member of a class
16623      template or partial specialization.  */
16624   gcc_assert (d != code_pattern);
16625
16626   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16627       || DECL_TEMPLATE_SPECIALIZATION (td))
16628     /* In the case of a friend template whose definition is provided
16629        outside the class, we may have too many arguments.  Drop the
16630        ones we don't need.  The same is true for specializations.  */
16631     args = get_innermost_template_args
16632       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16633   else
16634     args = gen_args;
16635
16636   if (TREE_CODE (d) == FUNCTION_DECL)
16637     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16638   else
16639     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16640
16641   /* We may be in the middle of deferred access check.  Disable it now.  */
16642   push_deferring_access_checks (dk_no_deferred);
16643
16644   /* Unless an explicit instantiation directive has already determined
16645      the linkage of D, remember that a definition is available for
16646      this entity.  */
16647   if (pattern_defined
16648       && !DECL_INTERFACE_KNOWN (d)
16649       && !DECL_NOT_REALLY_EXTERN (d))
16650     mark_definable (d);
16651
16652   input_location = DECL_SOURCE_LOCATION (d);
16653
16654   /* If D is a member of an explicitly instantiated class template,
16655      and no definition is available, treat it like an implicit
16656      instantiation.  */
16657   if (!pattern_defined && expl_inst_class_mem_p
16658       && DECL_EXPLICIT_INSTANTIATION (d))
16659     {
16660       DECL_NOT_REALLY_EXTERN (d) = 0;
16661       DECL_INTERFACE_KNOWN (d) = 0;
16662       SET_DECL_IMPLICIT_INSTANTIATION (d);
16663     }
16664
16665   /* Recheck the substitutions to obtain any warning messages
16666      about ignoring cv qualifiers.  Don't do this for artificial decls,
16667      as it breaks the context-sensitive substitution for lambda op(). */
16668   if (!defer_ok && !DECL_ARTIFICIAL (d))
16669     {
16670       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16671       tree type = TREE_TYPE (gen);
16672
16673       /* Make sure that we can see identifiers, and compute access
16674          correctly.  D is already the target FUNCTION_DECL with the
16675          right context.  */
16676       push_access_scope (d);
16677
16678       if (TREE_CODE (gen) == FUNCTION_DECL)
16679         {
16680           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16681           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16682                                           d);
16683           /* Don't simply tsubst the function type, as that will give
16684              duplicate warnings about poor parameter qualifications.
16685              The function arguments are the same as the decl_arguments
16686              without the top level cv qualifiers.  */
16687           type = TREE_TYPE (type);
16688         }
16689       tsubst (type, gen_args, tf_warning_or_error, d);
16690
16691       pop_access_scope (d);
16692     }
16693
16694   /* Defer all other templates, unless we have been explicitly
16695      forbidden from doing so.  */
16696   if (/* If there is no definition, we cannot instantiate the
16697          template.  */
16698       ! pattern_defined
16699       /* If it's OK to postpone instantiation, do so.  */
16700       || defer_ok
16701       /* If this is a static data member that will be defined
16702          elsewhere, we don't want to instantiate the entire data
16703          member, but we do want to instantiate the initializer so that
16704          we can substitute that elsewhere.  */
16705       || (external_p && TREE_CODE (d) == VAR_DECL))
16706     {
16707       /* The definition of the static data member is now required so
16708          we must substitute the initializer.  */
16709       if (TREE_CODE (d) == VAR_DECL
16710           && !DECL_INITIAL (d)
16711           && DECL_INITIAL (code_pattern))
16712         {
16713           tree ns;
16714           tree init;
16715
16716           ns = decl_namespace_context (d);
16717           push_nested_namespace (ns);
16718           push_nested_class (DECL_CONTEXT (d));
16719           init = tsubst_expr (DECL_INITIAL (code_pattern),
16720                               args,
16721                               tf_warning_or_error, NULL_TREE,
16722                               /*integral_constant_expression_p=*/false);
16723           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16724                           /*asmspec_tree=*/NULL_TREE,
16725                           LOOKUP_ONLYCONVERTING);
16726           pop_nested_class ();
16727           pop_nested_namespace (ns);
16728         }
16729
16730       /* We restore the source position here because it's used by
16731          add_pending_template.  */
16732       input_location = saved_loc;
16733
16734       if (at_eof && !pattern_defined
16735           && DECL_EXPLICIT_INSTANTIATION (d)
16736           && DECL_NOT_REALLY_EXTERN (d))
16737         /* [temp.explicit]
16738
16739            The definition of a non-exported function template, a
16740            non-exported member function template, or a non-exported
16741            member function or static data member of a class template
16742            shall be present in every translation unit in which it is
16743            explicitly instantiated.  */
16744         permerror (input_location,  "explicit instantiation of %qD "
16745                    "but no definition available", d);
16746
16747       /* ??? Historically, we have instantiated inline functions, even
16748          when marked as "extern template".  */
16749       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16750         add_pending_template (d);
16751       goto out;
16752     }
16753   /* Tell the repository that D is available in this translation unit
16754      -- and see if it is supposed to be instantiated here.  */
16755   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16756     {
16757       /* In a PCH file, despite the fact that the repository hasn't
16758          requested instantiation in the PCH it is still possible that
16759          an instantiation will be required in a file that includes the
16760          PCH.  */
16761       if (pch_file)
16762         add_pending_template (d);
16763       /* Instantiate inline functions so that the inliner can do its
16764          job, even though we'll not be emitting a copy of this
16765          function.  */
16766       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16767         goto out;
16768     }
16769
16770   need_push = !cfun || !global_bindings_p ();
16771   if (need_push)
16772     push_to_top_level ();
16773
16774   /* Mark D as instantiated so that recursive calls to
16775      instantiate_decl do not try to instantiate it again.  */
16776   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16777
16778   /* Regenerate the declaration in case the template has been modified
16779      by a subsequent redeclaration.  */
16780   regenerate_decl_from_template (d, td);
16781
16782   /* We already set the file and line above.  Reset them now in case
16783      they changed as a result of calling regenerate_decl_from_template.  */
16784   input_location = DECL_SOURCE_LOCATION (d);
16785
16786   if (TREE_CODE (d) == VAR_DECL)
16787     {
16788       tree init;
16789
16790       /* Clear out DECL_RTL; whatever was there before may not be right
16791          since we've reset the type of the declaration.  */
16792       SET_DECL_RTL (d, NULL_RTX);
16793       DECL_IN_AGGR_P (d) = 0;
16794
16795       /* The initializer is placed in DECL_INITIAL by
16796          regenerate_decl_from_template.  Pull it out so that
16797          cp_finish_decl can process it.  */
16798       init = DECL_INITIAL (d);
16799       DECL_INITIAL (d) = NULL_TREE;
16800       DECL_INITIALIZED_P (d) = 0;
16801
16802       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16803          initializer.  That function will defer actual emission until
16804          we have a chance to determine linkage.  */
16805       DECL_EXTERNAL (d) = 0;
16806
16807       /* Enter the scope of D so that access-checking works correctly.  */
16808       push_nested_class (DECL_CONTEXT (d));
16809       cp_finish_decl (d, init, false, NULL_TREE, 0);
16810       pop_nested_class ();
16811     }
16812   else if (TREE_CODE (d) == FUNCTION_DECL)
16813     {
16814       htab_t saved_local_specializations;
16815       tree subst_decl;
16816       tree tmpl_parm;
16817       tree spec_parm;
16818
16819       /* Save away the current list, in case we are instantiating one
16820          template from within the body of another.  */
16821       saved_local_specializations = local_specializations;
16822
16823       /* Set up the list of local specializations.  */
16824       local_specializations = htab_create (37,
16825                                            hash_local_specialization,
16826                                            eq_local_specializations,
16827                                            NULL);
16828
16829       /* Set up context.  */
16830       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16831
16832       /* Create substitution entries for the parameters.  */
16833       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16834       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16835       spec_parm = DECL_ARGUMENTS (d);
16836       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16837         {
16838           register_local_specialization (spec_parm, tmpl_parm);
16839           spec_parm = skip_artificial_parms_for (d, spec_parm);
16840           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16841         }
16842       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16843         {
16844           register_local_specialization (spec_parm, tmpl_parm);
16845           tmpl_parm = TREE_CHAIN (tmpl_parm);
16846           spec_parm = TREE_CHAIN (spec_parm);
16847         }
16848       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16849         {
16850           /* Register the (value) argument pack as a specialization of
16851              TMPL_PARM, then move on.  */
16852           tree argpack = make_fnparm_pack (spec_parm);
16853           register_local_specialization (argpack, tmpl_parm);
16854           tmpl_parm = TREE_CHAIN (tmpl_parm);
16855           spec_parm = NULL_TREE;
16856         }
16857       gcc_assert (!spec_parm);
16858
16859       /* Substitute into the body of the function.  */
16860       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16861                    tf_warning_or_error, tmpl,
16862                    /*integral_constant_expression_p=*/false);
16863
16864       /* Set the current input_location to the end of the function
16865          so that finish_function knows where we are.  */
16866       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16867
16868       /* We don't need the local specializations any more.  */
16869       htab_delete (local_specializations);
16870       local_specializations = saved_local_specializations;
16871
16872       /* Finish the function.  */
16873       d = finish_function (0);
16874       expand_or_defer_fn (d);
16875     }
16876
16877   /* We're not deferring instantiation any more.  */
16878   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16879
16880   if (need_push)
16881     pop_from_top_level ();
16882
16883 out:
16884   input_location = saved_loc;
16885   pop_deferring_access_checks ();
16886   pop_tinst_level ();
16887
16888   timevar_pop (TV_PARSE);
16889
16890   return d;
16891 }
16892
16893 /* Run through the list of templates that we wish we could
16894    instantiate, and instantiate any we can.  RETRIES is the
16895    number of times we retry pending template instantiation.  */
16896
16897 void
16898 instantiate_pending_templates (int retries)
16899 {
16900   int reconsider;
16901   location_t saved_loc = input_location;
16902
16903   /* Instantiating templates may trigger vtable generation.  This in turn
16904      may require further template instantiations.  We place a limit here
16905      to avoid infinite loop.  */
16906   if (pending_templates && retries >= max_tinst_depth)
16907     {
16908       tree decl = pending_templates->tinst->decl;
16909
16910       error ("template instantiation depth exceeds maximum of %d"
16911              " instantiating %q+D, possibly from virtual table generation"
16912              " (use -ftemplate-depth= to increase the maximum)",
16913              max_tinst_depth, decl);
16914       if (TREE_CODE (decl) == FUNCTION_DECL)
16915         /* Pretend that we defined it.  */
16916         DECL_INITIAL (decl) = error_mark_node;
16917       return;
16918     }
16919
16920   do
16921     {
16922       struct pending_template **t = &pending_templates;
16923       struct pending_template *last = NULL;
16924       reconsider = 0;
16925       while (*t)
16926         {
16927           tree instantiation = reopen_tinst_level ((*t)->tinst);
16928           bool complete = false;
16929
16930           if (TYPE_P (instantiation))
16931             {
16932               tree fn;
16933
16934               if (!COMPLETE_TYPE_P (instantiation))
16935                 {
16936                   instantiate_class_template (instantiation);
16937                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16938                     for (fn = TYPE_METHODS (instantiation);
16939                          fn;
16940                          fn = TREE_CHAIN (fn))
16941                       if (! DECL_ARTIFICIAL (fn))
16942                         instantiate_decl (fn,
16943                                           /*defer_ok=*/0,
16944                                           /*expl_inst_class_mem_p=*/false);
16945                   if (COMPLETE_TYPE_P (instantiation))
16946                     reconsider = 1;
16947                 }
16948
16949               complete = COMPLETE_TYPE_P (instantiation);
16950             }
16951           else
16952             {
16953               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16954                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16955                 {
16956                   instantiation
16957                     = instantiate_decl (instantiation,
16958                                         /*defer_ok=*/0,
16959                                         /*expl_inst_class_mem_p=*/false);
16960                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16961                     reconsider = 1;
16962                 }
16963
16964               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16965                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16966             }
16967
16968           if (complete)
16969             /* If INSTANTIATION has been instantiated, then we don't
16970                need to consider it again in the future.  */
16971             *t = (*t)->next;
16972           else
16973             {
16974               last = *t;
16975               t = &(*t)->next;
16976             }
16977           tinst_depth = 0;
16978           current_tinst_level = NULL;
16979         }
16980       last_pending_template = last;
16981     }
16982   while (reconsider);
16983
16984   input_location = saved_loc;
16985 }
16986
16987 /* Substitute ARGVEC into T, which is a list of initializers for
16988    either base class or a non-static data member.  The TREE_PURPOSEs
16989    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16990    instantiate_decl.  */
16991
16992 static tree
16993 tsubst_initializer_list (tree t, tree argvec)
16994 {
16995   tree inits = NULL_TREE;
16996
16997   for (; t; t = TREE_CHAIN (t))
16998     {
16999       tree decl;
17000       tree init;
17001       tree expanded_bases = NULL_TREE;
17002       tree expanded_arguments = NULL_TREE;
17003       int i, len = 1;
17004
17005       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17006         {
17007           tree expr;
17008           tree arg;
17009
17010           /* Expand the base class expansion type into separate base
17011              classes.  */
17012           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17013                                                  tf_warning_or_error,
17014                                                  NULL_TREE);
17015           if (expanded_bases == error_mark_node)
17016             continue;
17017           
17018           /* We'll be building separate TREE_LISTs of arguments for
17019              each base.  */
17020           len = TREE_VEC_LENGTH (expanded_bases);
17021           expanded_arguments = make_tree_vec (len);
17022           for (i = 0; i < len; i++)
17023             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17024
17025           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17026              expand each argument in the TREE_VALUE of t.  */
17027           expr = make_node (EXPR_PACK_EXPANSION);
17028           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17029             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17030
17031           if (TREE_VALUE (t) == void_type_node)
17032             /* VOID_TYPE_NODE is used to indicate
17033                value-initialization.  */
17034             {
17035               for (i = 0; i < len; i++)
17036                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17037             }
17038           else
17039             {
17040               /* Substitute parameter packs into each argument in the
17041                  TREE_LIST.  */
17042               in_base_initializer = 1;
17043               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17044                 {
17045                   tree expanded_exprs;
17046
17047                   /* Expand the argument.  */
17048                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17049                   expanded_exprs 
17050                     = tsubst_pack_expansion (expr, argvec,
17051                                              tf_warning_or_error,
17052                                              NULL_TREE);
17053                   if (expanded_exprs == error_mark_node)
17054                     continue;
17055
17056                   /* Prepend each of the expanded expressions to the
17057                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17058                   for (i = 0; i < len; i++)
17059                     {
17060                       TREE_VEC_ELT (expanded_arguments, i) = 
17061                         tree_cons (NULL_TREE, 
17062                                    TREE_VEC_ELT (expanded_exprs, i),
17063                                    TREE_VEC_ELT (expanded_arguments, i));
17064                     }
17065                 }
17066               in_base_initializer = 0;
17067
17068               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17069                  since we built them backwards.  */
17070               for (i = 0; i < len; i++)
17071                 {
17072                   TREE_VEC_ELT (expanded_arguments, i) = 
17073                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17074                 }
17075             }
17076         }
17077
17078       for (i = 0; i < len; ++i)
17079         {
17080           if (expanded_bases)
17081             {
17082               decl = TREE_VEC_ELT (expanded_bases, i);
17083               decl = expand_member_init (decl);
17084               init = TREE_VEC_ELT (expanded_arguments, i);
17085             }
17086           else
17087             {
17088               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17089                                   tf_warning_or_error, NULL_TREE);
17090
17091               decl = expand_member_init (decl);
17092               if (decl && !DECL_P (decl))
17093                 in_base_initializer = 1;
17094
17095               init = tsubst_expr (TREE_VALUE (t), argvec, 
17096                                   tf_warning_or_error, NULL_TREE,
17097                                   /*integral_constant_expression_p=*/false);
17098               in_base_initializer = 0;
17099             }
17100
17101           if (decl)
17102             {
17103               init = build_tree_list (decl, init);
17104               TREE_CHAIN (init) = inits;
17105               inits = init;
17106             }
17107         }
17108     }
17109   return inits;
17110 }
17111
17112 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17113
17114 static void
17115 set_current_access_from_decl (tree decl)
17116 {
17117   if (TREE_PRIVATE (decl))
17118     current_access_specifier = access_private_node;
17119   else if (TREE_PROTECTED (decl))
17120     current_access_specifier = access_protected_node;
17121   else
17122     current_access_specifier = access_public_node;
17123 }
17124
17125 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17126    is the instantiation (which should have been created with
17127    start_enum) and ARGS are the template arguments to use.  */
17128
17129 static void
17130 tsubst_enum (tree tag, tree newtag, tree args)
17131 {
17132   tree e;
17133
17134   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17135     {
17136       tree value;
17137       tree decl;
17138
17139       decl = TREE_VALUE (e);
17140       /* Note that in a template enum, the TREE_VALUE is the
17141          CONST_DECL, not the corresponding INTEGER_CST.  */
17142       value = tsubst_expr (DECL_INITIAL (decl),
17143                            args, tf_warning_or_error, NULL_TREE,
17144                            /*integral_constant_expression_p=*/true);
17145
17146       /* Give this enumeration constant the correct access.  */
17147       set_current_access_from_decl (decl);
17148
17149       /* Actually build the enumerator itself.  */
17150       build_enumerator (DECL_NAME (decl), value, newtag);
17151     }
17152
17153   finish_enum (newtag);
17154   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17155     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17156 }
17157
17158 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17159    its type -- but without substituting the innermost set of template
17160    arguments.  So, innermost set of template parameters will appear in
17161    the type.  */
17162
17163 tree
17164 get_mostly_instantiated_function_type (tree decl)
17165 {
17166   tree fn_type;
17167   tree tmpl;
17168   tree targs;
17169   tree tparms;
17170   int parm_depth;
17171
17172   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17173   targs = DECL_TI_ARGS (decl);
17174   tparms = DECL_TEMPLATE_PARMS (tmpl);
17175   parm_depth = TMPL_PARMS_DEPTH (tparms);
17176
17177   /* There should be as many levels of arguments as there are levels
17178      of parameters.  */
17179   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17180
17181   fn_type = TREE_TYPE (tmpl);
17182
17183   if (parm_depth == 1)
17184     /* No substitution is necessary.  */
17185     ;
17186   else
17187     {
17188       int i, save_access_control;
17189       tree partial_args;
17190
17191       /* Replace the innermost level of the TARGS with NULL_TREEs to
17192          let tsubst know not to substitute for those parameters.  */
17193       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17194       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17195         SET_TMPL_ARGS_LEVEL (partial_args, i,
17196                              TMPL_ARGS_LEVEL (targs, i));
17197       SET_TMPL_ARGS_LEVEL (partial_args,
17198                            TMPL_ARGS_DEPTH (targs),
17199                            make_tree_vec (DECL_NTPARMS (tmpl)));
17200
17201       /* Disable access control as this function is used only during
17202          name-mangling.  */
17203       save_access_control = flag_access_control;
17204       flag_access_control = 0;
17205
17206       ++processing_template_decl;
17207       /* Now, do the (partial) substitution to figure out the
17208          appropriate function type.  */
17209       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17210       --processing_template_decl;
17211
17212       /* Substitute into the template parameters to obtain the real
17213          innermost set of parameters.  This step is important if the
17214          innermost set of template parameters contains value
17215          parameters whose types depend on outer template parameters.  */
17216       TREE_VEC_LENGTH (partial_args)--;
17217       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17218
17219       flag_access_control = save_access_control;
17220     }
17221
17222   return fn_type;
17223 }
17224
17225 /* Return truthvalue if we're processing a template different from
17226    the last one involved in diagnostics.  */
17227 int
17228 problematic_instantiation_changed (void)
17229 {
17230   return last_template_error_tick != tinst_level_tick;
17231 }
17232
17233 /* Remember current template involved in diagnostics.  */
17234 void
17235 record_last_problematic_instantiation (void)
17236 {
17237   last_template_error_tick = tinst_level_tick;
17238 }
17239
17240 struct tinst_level *
17241 current_instantiation (void)
17242 {
17243   return current_tinst_level;
17244 }
17245
17246 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17247    type. Return zero for ok, nonzero for disallowed. Issue error and
17248    warning messages under control of COMPLAIN.  */
17249
17250 static int
17251 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17252 {
17253   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17254     return 0;
17255   else if (POINTER_TYPE_P (type))
17256     return 0;
17257   else if (TYPE_PTR_TO_MEMBER_P (type))
17258     return 0;
17259   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17260     return 0;
17261   else if (TREE_CODE (type) == TYPENAME_TYPE)
17262     return 0;
17263
17264   if (complain & tf_error)
17265     error ("%q#T is not a valid type for a template constant parameter", type);
17266   return 1;
17267 }
17268
17269 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17270    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17271
17272 static bool
17273 dependent_type_p_r (tree type)
17274 {
17275   tree scope;
17276
17277   /* [temp.dep.type]
17278
17279      A type is dependent if it is:
17280
17281      -- a template parameter. Template template parameters are types
17282         for us (since TYPE_P holds true for them) so we handle
17283         them here.  */
17284   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17285       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17286     return true;
17287   /* -- a qualified-id with a nested-name-specifier which contains a
17288         class-name that names a dependent type or whose unqualified-id
17289         names a dependent type.  */
17290   if (TREE_CODE (type) == TYPENAME_TYPE)
17291     return true;
17292   /* -- a cv-qualified type where the cv-unqualified type is
17293         dependent.  */
17294   type = TYPE_MAIN_VARIANT (type);
17295   /* -- a compound type constructed from any dependent type.  */
17296   if (TYPE_PTR_TO_MEMBER_P (type))
17297     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17298             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17299                                            (type)));
17300   else if (TREE_CODE (type) == POINTER_TYPE
17301            || TREE_CODE (type) == REFERENCE_TYPE)
17302     return dependent_type_p (TREE_TYPE (type));
17303   else if (TREE_CODE (type) == FUNCTION_TYPE
17304            || TREE_CODE (type) == METHOD_TYPE)
17305     {
17306       tree arg_type;
17307
17308       if (dependent_type_p (TREE_TYPE (type)))
17309         return true;
17310       for (arg_type = TYPE_ARG_TYPES (type);
17311            arg_type;
17312            arg_type = TREE_CHAIN (arg_type))
17313         if (dependent_type_p (TREE_VALUE (arg_type)))
17314           return true;
17315       return false;
17316     }
17317   /* -- an array type constructed from any dependent type or whose
17318         size is specified by a constant expression that is
17319         value-dependent.  */
17320   if (TREE_CODE (type) == ARRAY_TYPE)
17321     {
17322       if (TYPE_DOMAIN (type)
17323           && dependent_type_p (TYPE_DOMAIN (type)))
17324         return true;
17325       return dependent_type_p (TREE_TYPE (type));
17326     }
17327   else if (TREE_CODE (type) == INTEGER_TYPE
17328            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17329     {
17330       /* If this is the TYPE_DOMAIN of an array type, consider it
17331          dependent.  We already checked for value-dependence in
17332          compute_array_index_type.  */
17333       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17334     }
17335
17336   /* -- a template-id in which either the template name is a template
17337      parameter ...  */
17338   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17339     return true;
17340   /* ... or any of the template arguments is a dependent type or
17341         an expression that is type-dependent or value-dependent.  */
17342   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17343            && (any_dependent_template_arguments_p
17344                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17345     return true;
17346
17347   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17348      argument of the `typeof' expression is not type-dependent, then
17349      it should already been have resolved.  */
17350   if (TREE_CODE (type) == TYPEOF_TYPE
17351       || TREE_CODE (type) == DECLTYPE_TYPE)
17352     return true;
17353
17354   /* A template argument pack is dependent if any of its packed
17355      arguments are.  */
17356   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17357     {
17358       tree args = ARGUMENT_PACK_ARGS (type);
17359       int i, len = TREE_VEC_LENGTH (args);
17360       for (i = 0; i < len; ++i)
17361         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17362           return true;
17363     }
17364
17365   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17366      be template parameters.  */
17367   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17368     return true;
17369
17370   /* The standard does not specifically mention types that are local
17371      to template functions or local classes, but they should be
17372      considered dependent too.  For example:
17373
17374        template <int I> void f() {
17375          enum E { a = I };
17376          S<sizeof (E)> s;
17377        }
17378
17379      The size of `E' cannot be known until the value of `I' has been
17380      determined.  Therefore, `E' must be considered dependent.  */
17381   scope = TYPE_CONTEXT (type);
17382   if (scope && TYPE_P (scope))
17383     return dependent_type_p (scope);
17384   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17385     return type_dependent_expression_p (scope);
17386
17387   /* Other types are non-dependent.  */
17388   return false;
17389 }
17390
17391 /* Returns TRUE if TYPE is dependent, in the sense of
17392    [temp.dep.type].  */
17393
17394 bool
17395 dependent_type_p (tree type)
17396 {
17397   /* If there are no template parameters in scope, then there can't be
17398      any dependent types.  */
17399   if (!processing_template_decl)
17400     {
17401       /* If we are not processing a template, then nobody should be
17402          providing us with a dependent type.  */
17403       gcc_assert (type);
17404       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17405       return false;
17406     }
17407
17408   /* If the type is NULL, we have not computed a type for the entity
17409      in question; in that case, the type is dependent.  */
17410   if (!type)
17411     return true;
17412
17413   /* Erroneous types can be considered non-dependent.  */
17414   if (type == error_mark_node)
17415     return false;
17416
17417   /* If we have not already computed the appropriate value for TYPE,
17418      do so now.  */
17419   if (!TYPE_DEPENDENT_P_VALID (type))
17420     {
17421       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17422       TYPE_DEPENDENT_P_VALID (type) = 1;
17423     }
17424
17425   return TYPE_DEPENDENT_P (type);
17426 }
17427
17428 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17429    lookup.  In other words, a dependent type that is not the current
17430    instantiation.  */
17431
17432 bool
17433 dependent_scope_p (tree scope)
17434 {
17435   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17436           && !currently_open_class (scope));
17437 }
17438
17439 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17440
17441 static bool
17442 dependent_scope_ref_p (tree expression, bool criterion (tree))
17443 {
17444   tree scope;
17445   tree name;
17446
17447   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17448
17449   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17450     return true;
17451
17452   scope = TREE_OPERAND (expression, 0);
17453   name = TREE_OPERAND (expression, 1);
17454
17455   /* [temp.dep.expr]
17456
17457      An id-expression is type-dependent if it contains a
17458      nested-name-specifier that contains a class-name that names a
17459      dependent type.  */
17460   /* The suggested resolution to Core Issue 224 implies that if the
17461      qualifying type is the current class, then we must peek
17462      inside it.  */
17463   if (DECL_P (name)
17464       && currently_open_class (scope)
17465       && !criterion (name))
17466     return false;
17467   if (dependent_type_p (scope))
17468     return true;
17469
17470   return false;
17471 }
17472
17473 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17474    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17475    expression.  */
17476
17477 bool
17478 value_dependent_expression_p (tree expression)
17479 {
17480   if (!processing_template_decl)
17481     return false;
17482
17483   /* A name declared with a dependent type.  */
17484   if (DECL_P (expression) && type_dependent_expression_p (expression))
17485     return true;
17486
17487   switch (TREE_CODE (expression))
17488     {
17489     case IDENTIFIER_NODE:
17490       /* A name that has not been looked up -- must be dependent.  */
17491       return true;
17492
17493     case TEMPLATE_PARM_INDEX:
17494       /* A non-type template parm.  */
17495       return true;
17496
17497     case CONST_DECL:
17498       /* A non-type template parm.  */
17499       if (DECL_TEMPLATE_PARM_P (expression))
17500         return true;
17501       return value_dependent_expression_p (DECL_INITIAL (expression));
17502
17503     case VAR_DECL:
17504        /* A constant with integral or enumeration type and is initialized
17505           with an expression that is value-dependent.  */
17506       if (DECL_INITIAL (expression)
17507           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17508           && value_dependent_expression_p (DECL_INITIAL (expression)))
17509         return true;
17510       return false;
17511
17512     case DYNAMIC_CAST_EXPR:
17513     case STATIC_CAST_EXPR:
17514     case CONST_CAST_EXPR:
17515     case REINTERPRET_CAST_EXPR:
17516     case CAST_EXPR:
17517       /* These expressions are value-dependent if the type to which
17518          the cast occurs is dependent or the expression being casted
17519          is value-dependent.  */
17520       {
17521         tree type = TREE_TYPE (expression);
17522
17523         if (dependent_type_p (type))
17524           return true;
17525
17526         /* A functional cast has a list of operands.  */
17527         expression = TREE_OPERAND (expression, 0);
17528         if (!expression)
17529           {
17530             /* If there are no operands, it must be an expression such
17531                as "int()". This should not happen for aggregate types
17532                because it would form non-constant expressions.  */
17533             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17534
17535             return false;
17536           }
17537
17538         if (TREE_CODE (expression) == TREE_LIST)
17539           return any_value_dependent_elements_p (expression);
17540
17541         return value_dependent_expression_p (expression);
17542       }
17543
17544     case SIZEOF_EXPR:
17545     case ALIGNOF_EXPR:
17546       /* A `sizeof' expression is value-dependent if the operand is
17547          type-dependent or is a pack expansion.  */
17548       expression = TREE_OPERAND (expression, 0);
17549       if (PACK_EXPANSION_P (expression))
17550         return true;
17551       else if (TYPE_P (expression))
17552         return dependent_type_p (expression);
17553       return type_dependent_expression_p (expression);
17554
17555     case SCOPE_REF:
17556       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17557
17558     case COMPONENT_REF:
17559       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17560               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17561
17562     case CALL_EXPR:
17563       /* A CALL_EXPR may appear in a constant expression if it is a
17564          call to a builtin function, e.g., __builtin_constant_p.  All
17565          such calls are value-dependent.  */
17566       return true;
17567
17568     case NONTYPE_ARGUMENT_PACK:
17569       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17570          is value-dependent.  */
17571       {
17572         tree values = ARGUMENT_PACK_ARGS (expression);
17573         int i, len = TREE_VEC_LENGTH (values);
17574         
17575         for (i = 0; i < len; ++i)
17576           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17577             return true;
17578         
17579         return false;
17580       }
17581
17582     case TRAIT_EXPR:
17583       {
17584         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17585         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17586                 || (type2 ? dependent_type_p (type2) : false));
17587       }
17588
17589     case MODOP_EXPR:
17590       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17591               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17592
17593     default:
17594       /* A constant expression is value-dependent if any subexpression is
17595          value-dependent.  */
17596       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17597         {
17598         case tcc_reference:
17599         case tcc_unary:
17600           return (value_dependent_expression_p
17601                   (TREE_OPERAND (expression, 0)));
17602
17603         case tcc_comparison:
17604         case tcc_binary:
17605           return ((value_dependent_expression_p
17606                    (TREE_OPERAND (expression, 0)))
17607                   || (value_dependent_expression_p
17608                       (TREE_OPERAND (expression, 1))));
17609
17610         case tcc_expression:
17611         case tcc_vl_exp:
17612           {
17613             int i;
17614             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17615               /* In some cases, some of the operands may be missing.
17616                  (For example, in the case of PREDECREMENT_EXPR, the
17617                  amount to increment by may be missing.)  That doesn't
17618                  make the expression dependent.  */
17619               if (TREE_OPERAND (expression, i)
17620                   && (value_dependent_expression_p
17621                       (TREE_OPERAND (expression, i))))
17622                 return true;
17623             return false;
17624           }
17625
17626         default:
17627           break;
17628         }
17629     }
17630
17631   /* The expression is not value-dependent.  */
17632   return false;
17633 }
17634
17635 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17636    [temp.dep.expr].  */
17637
17638 bool
17639 type_dependent_expression_p (tree expression)
17640 {
17641   if (!processing_template_decl)
17642     return false;
17643
17644   if (expression == error_mark_node)
17645     return false;
17646
17647   /* An unresolved name is always dependent.  */
17648   if (TREE_CODE (expression) == IDENTIFIER_NODE
17649       || TREE_CODE (expression) == USING_DECL)
17650     return true;
17651
17652   /* Some expression forms are never type-dependent.  */
17653   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17654       || TREE_CODE (expression) == SIZEOF_EXPR
17655       || TREE_CODE (expression) == ALIGNOF_EXPR
17656       || TREE_CODE (expression) == TRAIT_EXPR
17657       || TREE_CODE (expression) == TYPEID_EXPR
17658       || TREE_CODE (expression) == DELETE_EXPR
17659       || TREE_CODE (expression) == VEC_DELETE_EXPR
17660       || TREE_CODE (expression) == THROW_EXPR)
17661     return false;
17662
17663   /* The types of these expressions depends only on the type to which
17664      the cast occurs.  */
17665   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17666       || TREE_CODE (expression) == STATIC_CAST_EXPR
17667       || TREE_CODE (expression) == CONST_CAST_EXPR
17668       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17669       || TREE_CODE (expression) == CAST_EXPR)
17670     return dependent_type_p (TREE_TYPE (expression));
17671
17672   /* The types of these expressions depends only on the type created
17673      by the expression.  */
17674   if (TREE_CODE (expression) == NEW_EXPR
17675       || TREE_CODE (expression) == VEC_NEW_EXPR)
17676     {
17677       /* For NEW_EXPR tree nodes created inside a template, either
17678          the object type itself or a TREE_LIST may appear as the
17679          operand 1.  */
17680       tree type = TREE_OPERAND (expression, 1);
17681       if (TREE_CODE (type) == TREE_LIST)
17682         /* This is an array type.  We need to check array dimensions
17683            as well.  */
17684         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17685                || value_dependent_expression_p
17686                     (TREE_OPERAND (TREE_VALUE (type), 1));
17687       else
17688         return dependent_type_p (type);
17689     }
17690
17691   if (TREE_CODE (expression) == SCOPE_REF
17692       && dependent_scope_ref_p (expression,
17693                                 type_dependent_expression_p))
17694     return true;
17695
17696   if (TREE_CODE (expression) == FUNCTION_DECL
17697       && DECL_LANG_SPECIFIC (expression)
17698       && DECL_TEMPLATE_INFO (expression)
17699       && (any_dependent_template_arguments_p
17700           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17701     return true;
17702
17703   if (TREE_CODE (expression) == TEMPLATE_DECL
17704       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17705     return false;
17706
17707   if (TREE_CODE (expression) == STMT_EXPR)
17708     expression = stmt_expr_value_expr (expression);
17709
17710   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17711     {
17712       tree elt;
17713       unsigned i;
17714
17715       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17716         {
17717           if (type_dependent_expression_p (elt))
17718             return true;
17719         }
17720       return false;
17721     }
17722
17723   if (TREE_TYPE (expression) == unknown_type_node)
17724     {
17725       if (TREE_CODE (expression) == ADDR_EXPR)
17726         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17727       if (TREE_CODE (expression) == COMPONENT_REF
17728           || TREE_CODE (expression) == OFFSET_REF)
17729         {
17730           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17731             return true;
17732           expression = TREE_OPERAND (expression, 1);
17733           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17734             return false;
17735         }
17736       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17737       if (TREE_CODE (expression) == SCOPE_REF)
17738         return false;
17739
17740       if (TREE_CODE (expression) == BASELINK)
17741         expression = BASELINK_FUNCTIONS (expression);
17742
17743       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17744         {
17745           if (any_dependent_template_arguments_p
17746               (TREE_OPERAND (expression, 1)))
17747             return true;
17748           expression = TREE_OPERAND (expression, 0);
17749         }
17750       gcc_assert (TREE_CODE (expression) == OVERLOAD
17751                   || TREE_CODE (expression) == FUNCTION_DECL);
17752
17753       while (expression)
17754         {
17755           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17756             return true;
17757           expression = OVL_NEXT (expression);
17758         }
17759       return false;
17760     }
17761
17762   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17763
17764   return (dependent_type_p (TREE_TYPE (expression)));
17765 }
17766
17767 /* Like type_dependent_expression_p, but it also works while not processing
17768    a template definition, i.e. during substitution or mangling.  */
17769
17770 bool
17771 type_dependent_expression_p_push (tree expr)
17772 {
17773   bool b;
17774   ++processing_template_decl;
17775   b = type_dependent_expression_p (expr);
17776   --processing_template_decl;
17777   return b;
17778 }
17779
17780 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17781
17782 bool
17783 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17784 {
17785   unsigned int i;
17786   tree arg;
17787
17788   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17789     {
17790       if (type_dependent_expression_p (arg))
17791         return true;
17792     }
17793   return false;
17794 }
17795
17796 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17797    expressions) contains any value-dependent expressions.  */
17798
17799 bool
17800 any_value_dependent_elements_p (const_tree list)
17801 {
17802   for (; list; list = TREE_CHAIN (list))
17803     if (value_dependent_expression_p (TREE_VALUE (list)))
17804       return true;
17805
17806   return false;
17807 }
17808
17809 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17810
17811 bool
17812 dependent_template_arg_p (tree arg)
17813 {
17814   if (!processing_template_decl)
17815     return false;
17816
17817   if (TREE_CODE (arg) == TEMPLATE_DECL
17818       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17819     return dependent_template_p (arg);
17820   else if (ARGUMENT_PACK_P (arg))
17821     {
17822       tree args = ARGUMENT_PACK_ARGS (arg);
17823       int i, len = TREE_VEC_LENGTH (args);
17824       for (i = 0; i < len; ++i)
17825         {
17826           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17827             return true;
17828         }
17829
17830       return false;
17831     }
17832   else if (TYPE_P (arg))
17833     return dependent_type_p (arg);
17834   else
17835     return (type_dependent_expression_p (arg)
17836             || value_dependent_expression_p (arg));
17837 }
17838
17839 /* Returns true if ARGS (a collection of template arguments) contains
17840    any types that require structural equality testing.  */
17841
17842 bool
17843 any_template_arguments_need_structural_equality_p (tree args)
17844 {
17845   int i;
17846   int j;
17847
17848   if (!args)
17849     return false;
17850   if (args == error_mark_node)
17851     return true;
17852
17853   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17854     {
17855       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17856       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17857         {
17858           tree arg = TREE_VEC_ELT (level, j);
17859           tree packed_args = NULL_TREE;
17860           int k, len = 1;
17861
17862           if (ARGUMENT_PACK_P (arg))
17863             {
17864               /* Look inside the argument pack.  */
17865               packed_args = ARGUMENT_PACK_ARGS (arg);
17866               len = TREE_VEC_LENGTH (packed_args);
17867             }
17868
17869           for (k = 0; k < len; ++k)
17870             {
17871               if (packed_args)
17872                 arg = TREE_VEC_ELT (packed_args, k);
17873
17874               if (error_operand_p (arg))
17875                 return true;
17876               else if (TREE_CODE (arg) == TEMPLATE_DECL
17877                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17878                 continue;
17879               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17880                 return true;
17881               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17882                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17883                 return true;
17884             }
17885         }
17886     }
17887
17888   return false;
17889 }
17890
17891 /* Returns true if ARGS (a collection of template arguments) contains
17892    any dependent arguments.  */
17893
17894 bool
17895 any_dependent_template_arguments_p (const_tree args)
17896 {
17897   int i;
17898   int j;
17899
17900   if (!args)
17901     return false;
17902   if (args == error_mark_node)
17903     return true;
17904
17905   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17906     {
17907       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17908       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17909         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17910           return true;
17911     }
17912
17913   return false;
17914 }
17915
17916 /* Returns TRUE if the template TMPL is dependent.  */
17917
17918 bool
17919 dependent_template_p (tree tmpl)
17920 {
17921   if (TREE_CODE (tmpl) == OVERLOAD)
17922     {
17923       while (tmpl)
17924         {
17925           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17926             return true;
17927           tmpl = OVL_CHAIN (tmpl);
17928         }
17929       return false;
17930     }
17931
17932   /* Template template parameters are dependent.  */
17933   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17934       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17935     return true;
17936   /* So are names that have not been looked up.  */
17937   if (TREE_CODE (tmpl) == SCOPE_REF
17938       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17939     return true;
17940   /* So are member templates of dependent classes.  */
17941   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17942     return dependent_type_p (DECL_CONTEXT (tmpl));
17943   return false;
17944 }
17945
17946 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17947
17948 bool
17949 dependent_template_id_p (tree tmpl, tree args)
17950 {
17951   return (dependent_template_p (tmpl)
17952           || any_dependent_template_arguments_p (args));
17953 }
17954
17955 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17956    is dependent.  */
17957
17958 bool
17959 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17960 {
17961   int i;
17962
17963   if (!processing_template_decl)
17964     return false;
17965
17966   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17967     {
17968       tree decl = TREE_VEC_ELT (declv, i);
17969       tree init = TREE_VEC_ELT (initv, i);
17970       tree cond = TREE_VEC_ELT (condv, i);
17971       tree incr = TREE_VEC_ELT (incrv, i);
17972
17973       if (type_dependent_expression_p (decl))
17974         return true;
17975
17976       if (init && type_dependent_expression_p (init))
17977         return true;
17978
17979       if (type_dependent_expression_p (cond))
17980         return true;
17981
17982       if (COMPARISON_CLASS_P (cond)
17983           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17984               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17985         return true;
17986
17987       if (TREE_CODE (incr) == MODOP_EXPR)
17988         {
17989           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17990               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17991             return true;
17992         }
17993       else if (type_dependent_expression_p (incr))
17994         return true;
17995       else if (TREE_CODE (incr) == MODIFY_EXPR)
17996         {
17997           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17998             return true;
17999           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18000             {
18001               tree t = TREE_OPERAND (incr, 1);
18002               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18003                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18004                 return true;
18005             }
18006         }
18007     }
18008
18009   return false;
18010 }
18011
18012 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18013    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18014    no such TYPE can be found.  Note that this function peers inside
18015    uninstantiated templates and therefore should be used only in
18016    extremely limited situations.  ONLY_CURRENT_P restricts this
18017    peering to the currently open classes hierarchy (which is required
18018    when comparing types).  */
18019
18020 tree
18021 resolve_typename_type (tree type, bool only_current_p)
18022 {
18023   tree scope;
18024   tree name;
18025   tree decl;
18026   int quals;
18027   tree pushed_scope;
18028   tree result;
18029
18030   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18031
18032   scope = TYPE_CONTEXT (type);
18033   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18034      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18035      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18036      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18037      identifier  of the TYPENAME_TYPE anymore.
18038      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18039      TYPENAME_TYPE instead, we avoid messing up with a possible
18040      typedef variant case.  */
18041   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18042
18043   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18044      it first before we can figure out what NAME refers to.  */
18045   if (TREE_CODE (scope) == TYPENAME_TYPE)
18046     scope = resolve_typename_type (scope, only_current_p);
18047   /* If we don't know what SCOPE refers to, then we cannot resolve the
18048      TYPENAME_TYPE.  */
18049   if (TREE_CODE (scope) == TYPENAME_TYPE)
18050     return type;
18051   /* If the SCOPE is a template type parameter, we have no way of
18052      resolving the name.  */
18053   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18054     return type;
18055   /* If the SCOPE is not the current instantiation, there's no reason
18056      to look inside it.  */
18057   if (only_current_p && !currently_open_class (scope))
18058     return type;
18059   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18060   if (typedef_variant_p (type))
18061     return type;
18062   /* If SCOPE isn't the template itself, it will not have a valid
18063      TYPE_FIELDS list.  */
18064   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18065     /* scope is either the template itself or a compatible instantiation
18066        like X<T>, so look up the name in the original template.  */
18067     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18068   else
18069     /* scope is a partial instantiation, so we can't do the lookup or we
18070        will lose the template arguments.  */
18071     return type;
18072   /* Enter the SCOPE so that name lookup will be resolved as if we
18073      were in the class definition.  In particular, SCOPE will no
18074      longer be considered a dependent type.  */
18075   pushed_scope = push_scope (scope);
18076   /* Look up the declaration.  */
18077   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18078
18079   result = NULL_TREE;
18080   
18081   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18082      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18083   if (!decl)
18084     /*nop*/;
18085   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18086            && TREE_CODE (decl) == TYPE_DECL)
18087     {
18088       result = TREE_TYPE (decl);
18089       if (result == error_mark_node)
18090         result = NULL_TREE;
18091     }
18092   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18093            && DECL_CLASS_TEMPLATE_P (decl))
18094     {
18095       tree tmpl;
18096       tree args;
18097       /* Obtain the template and the arguments.  */
18098       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18099       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18100       /* Instantiate the template.  */
18101       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18102                                       /*entering_scope=*/0,
18103                                       tf_error | tf_user);
18104       if (result == error_mark_node)
18105         result = NULL_TREE;
18106     }
18107   
18108   /* Leave the SCOPE.  */
18109   if (pushed_scope)
18110     pop_scope (pushed_scope);
18111
18112   /* If we failed to resolve it, return the original typename.  */
18113   if (!result)
18114     return type;
18115   
18116   /* If lookup found a typename type, resolve that too.  */
18117   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18118     {
18119       /* Ill-formed programs can cause infinite recursion here, so we
18120          must catch that.  */
18121       TYPENAME_IS_RESOLVING_P (type) = 1;
18122       result = resolve_typename_type (result, only_current_p);
18123       TYPENAME_IS_RESOLVING_P (type) = 0;
18124     }
18125   
18126   /* Qualify the resulting type.  */
18127   quals = cp_type_quals (type);
18128   if (quals)
18129     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18130
18131   return result;
18132 }
18133
18134 /* EXPR is an expression which is not type-dependent.  Return a proxy
18135    for EXPR that can be used to compute the types of larger
18136    expressions containing EXPR.  */
18137
18138 tree
18139 build_non_dependent_expr (tree expr)
18140 {
18141   tree inner_expr;
18142
18143   /* Preserve null pointer constants so that the type of things like
18144      "p == 0" where "p" is a pointer can be determined.  */
18145   if (null_ptr_cst_p (expr))
18146     return expr;
18147   /* Preserve OVERLOADs; the functions must be available to resolve
18148      types.  */
18149   inner_expr = expr;
18150   if (TREE_CODE (inner_expr) == STMT_EXPR)
18151     inner_expr = stmt_expr_value_expr (inner_expr);
18152   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18153     inner_expr = TREE_OPERAND (inner_expr, 0);
18154   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18155     inner_expr = TREE_OPERAND (inner_expr, 1);
18156   if (is_overloaded_fn (inner_expr)
18157       || TREE_CODE (inner_expr) == OFFSET_REF)
18158     return expr;
18159   /* There is no need to return a proxy for a variable.  */
18160   if (TREE_CODE (expr) == VAR_DECL)
18161     return expr;
18162   /* Preserve string constants; conversions from string constants to
18163      "char *" are allowed, even though normally a "const char *"
18164      cannot be used to initialize a "char *".  */
18165   if (TREE_CODE (expr) == STRING_CST)
18166     return expr;
18167   /* Preserve arithmetic constants, as an optimization -- there is no
18168      reason to create a new node.  */
18169   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18170     return expr;
18171   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18172      There is at least one place where we want to know that a
18173      particular expression is a throw-expression: when checking a ?:
18174      expression, there are special rules if the second or third
18175      argument is a throw-expression.  */
18176   if (TREE_CODE (expr) == THROW_EXPR)
18177     return expr;
18178
18179   if (TREE_CODE (expr) == COND_EXPR)
18180     return build3 (COND_EXPR,
18181                    TREE_TYPE (expr),
18182                    TREE_OPERAND (expr, 0),
18183                    (TREE_OPERAND (expr, 1)
18184                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18185                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18186                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18187   if (TREE_CODE (expr) == COMPOUND_EXPR
18188       && !COMPOUND_EXPR_OVERLOADED (expr))
18189     return build2 (COMPOUND_EXPR,
18190                    TREE_TYPE (expr),
18191                    TREE_OPERAND (expr, 0),
18192                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18193
18194   /* If the type is unknown, it can't really be non-dependent */
18195   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18196
18197   /* Otherwise, build a NON_DEPENDENT_EXPR.
18198
18199      REFERENCE_TYPEs are not stripped for expressions in templates
18200      because doing so would play havoc with mangling.  Consider, for
18201      example:
18202
18203        template <typename T> void f<T& g>() { g(); }
18204
18205      In the body of "f", the expression for "g" will have
18206      REFERENCE_TYPE, even though the standard says that it should
18207      not.  The reason is that we must preserve the syntactic form of
18208      the expression so that mangling (say) "f<g>" inside the body of
18209      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18210      stripped here.  */
18211   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18212 }
18213
18214 /* ARGS is a vector of expressions as arguments to a function call.
18215    Replace the arguments with equivalent non-dependent expressions.
18216    This modifies ARGS in place.  */
18217
18218 void
18219 make_args_non_dependent (VEC(tree,gc) *args)
18220 {
18221   unsigned int ix;
18222   tree arg;
18223
18224   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18225     {
18226       tree newarg = build_non_dependent_expr (arg);
18227       if (newarg != arg)
18228         VEC_replace (tree, args, ix, newarg);
18229     }
18230 }
18231
18232 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18233    with a level one deeper than the actual template parms.  */
18234
18235 tree
18236 make_auto (void)
18237 {
18238   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18239   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18240                                TYPE_DECL, get_identifier ("auto"), au);
18241   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18242   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18243     (0, processing_template_decl + 1, processing_template_decl + 1,
18244      TYPE_NAME (au), NULL_TREE);
18245   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18246   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18247   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18248
18249   return au;
18250 }
18251
18252 /* Given type ARG, return std::initializer_list<ARG>.  */
18253
18254 static tree
18255 listify (tree arg)
18256 {
18257   tree std_init_list = namespace_binding
18258     (get_identifier ("initializer_list"), std_node);
18259   tree argvec;
18260   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18261     {    
18262       error ("deducing from brace-enclosed initializer list requires "
18263              "#include <initializer_list>");
18264       return error_mark_node;
18265     }
18266   argvec = make_tree_vec (1);
18267   TREE_VEC_ELT (argvec, 0) = arg;
18268   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18269                                 NULL_TREE, 0, tf_warning_or_error);
18270 }
18271
18272 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18273
18274 static tree
18275 listify_autos (tree type, tree auto_node)
18276 {
18277   tree init_auto = listify (auto_node);
18278   tree argvec = make_tree_vec (1);
18279   TREE_VEC_ELT (argvec, 0) = init_auto;
18280   if (processing_template_decl)
18281     argvec = add_to_template_args (current_template_args (), argvec);
18282   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18283 }
18284
18285 /* walk_tree helper for do_auto_deduction.  */
18286
18287 static tree
18288 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18289                  void *type)
18290 {
18291   /* Is this a variable with the type we're looking for?  */
18292   if (DECL_P (*tp)
18293       && TREE_TYPE (*tp) == type)
18294     return *tp;
18295   else
18296     return NULL_TREE;
18297 }
18298
18299 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18300    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18301
18302 tree
18303 do_auto_deduction (tree type, tree init, tree auto_node)
18304 {
18305   tree parms, tparms, targs;
18306   tree args[1];
18307   tree decl;
18308   int val;
18309
18310   /* The name of the object being declared shall not appear in the
18311      initializer expression.  */
18312   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18313   if (decl)
18314     {
18315       error ("variable %q#D with %<auto%> type used in its own "
18316              "initializer", decl);
18317       return error_mark_node;
18318     }
18319
18320   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18321      with either a new invented type template parameter U or, if the
18322      initializer is a braced-init-list (8.5.4), with
18323      std::initializer_list<U>.  */
18324   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18325     type = listify_autos (type, auto_node);
18326
18327   parms = build_tree_list (NULL_TREE, type);
18328   args[0] = init;
18329   tparms = make_tree_vec (1);
18330   targs = make_tree_vec (1);
18331   TREE_VEC_ELT (tparms, 0)
18332     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18333   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18334                                DEDUCE_CALL, LOOKUP_NORMAL);
18335   if (val > 0)
18336     {
18337       error ("unable to deduce %qT from %qE", type, init);
18338       return error_mark_node;
18339     }
18340
18341   /* If the list of declarators contains more than one declarator, the type
18342      of each declared variable is determined as described above. If the
18343      type deduced for the template parameter U is not the same in each
18344      deduction, the program is ill-formed.  */
18345   if (TREE_TYPE (auto_node)
18346       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18347     {
18348       error ("inconsistent deduction for %qT: %qT and then %qT",
18349              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18350       return error_mark_node;
18351     }
18352   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18353
18354   if (processing_template_decl)
18355     targs = add_to_template_args (current_template_args (), targs);
18356   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18357 }
18358
18359 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18360    result.  */
18361
18362 tree
18363 splice_late_return_type (tree type, tree late_return_type)
18364 {
18365   tree argvec;
18366
18367   if (late_return_type == NULL_TREE)
18368     return type;
18369   argvec = make_tree_vec (1);
18370   TREE_VEC_ELT (argvec, 0) = late_return_type;
18371   if (processing_template_decl)
18372     argvec = add_to_template_args (current_template_args (), argvec);
18373   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18374 }
18375
18376 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18377
18378 bool
18379 is_auto (const_tree type)
18380 {
18381   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18382       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18383     return true;
18384   else
18385     return false;
18386 }
18387
18388 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18389    appear as a type-specifier for the declaration in question, we don't
18390    have to look through the whole type.  */
18391
18392 tree
18393 type_uses_auto (tree type)
18394 {
18395   enum tree_code code;
18396   if (is_auto (type))
18397     return type;
18398
18399   code = TREE_CODE (type);
18400
18401   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18402       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18403       || code == METHOD_TYPE || code == ARRAY_TYPE)
18404     return type_uses_auto (TREE_TYPE (type));
18405
18406   if (TYPE_PTRMEMFUNC_P (type))
18407     return type_uses_auto (TREE_TYPE (TREE_TYPE
18408                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18409
18410   return NULL_TREE;
18411 }
18412
18413 /* For a given template T, return the vector of typedefs referenced
18414    in T for which access check is needed at T instantiation time.
18415    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18416    Those typedefs were added to T by the function
18417    append_type_to_template_for_access_check.  */
18418
18419 VEC(qualified_typedef_usage_t,gc)*
18420 get_types_needing_access_check (tree t)
18421 {
18422   tree ti;
18423   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18424
18425   if (!t || t == error_mark_node)
18426     return NULL;
18427
18428   if (!(ti = get_template_info (t)))
18429     return NULL;
18430
18431   if (CLASS_TYPE_P (t)
18432       || TREE_CODE (t) == FUNCTION_DECL)
18433     {
18434       if (!TI_TEMPLATE (ti))
18435         return NULL;
18436
18437       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18438     }
18439
18440   return result;
18441 }
18442
18443 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18444    tied to T. That list of typedefs will be access checked at
18445    T instantiation time.
18446    T is either a FUNCTION_DECL or a RECORD_TYPE.
18447    TYPE_DECL is a TYPE_DECL node representing a typedef.
18448    SCOPE is the scope through which TYPE_DECL is accessed.
18449    LOCATION is the location of the usage point of TYPE_DECL.
18450
18451    This function is a subroutine of
18452    append_type_to_template_for_access_check.  */
18453
18454 static void
18455 append_type_to_template_for_access_check_1 (tree t,
18456                                             tree type_decl,
18457                                             tree scope,
18458                                             location_t location)
18459 {
18460   qualified_typedef_usage_t typedef_usage;
18461   tree ti;
18462
18463   if (!t || t == error_mark_node)
18464     return;
18465
18466   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18467                || CLASS_TYPE_P (t))
18468               && type_decl
18469               && TREE_CODE (type_decl) == TYPE_DECL
18470               && scope);
18471
18472   if (!(ti = get_template_info (t)))
18473     return;
18474
18475   gcc_assert (TI_TEMPLATE (ti));
18476
18477   typedef_usage.typedef_decl = type_decl;
18478   typedef_usage.context = scope;
18479   typedef_usage.locus = location;
18480
18481   VEC_safe_push (qualified_typedef_usage_t, gc,
18482                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18483                  &typedef_usage);
18484 }
18485
18486 /* Append TYPE_DECL to the template TEMPL.
18487    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18488    At TEMPL instanciation time, TYPE_DECL will be checked to see
18489    if it can be accessed through SCOPE.
18490    LOCATION is the location of the usage point of TYPE_DECL.
18491
18492    e.g. consider the following code snippet:
18493
18494      class C
18495      {
18496        typedef int myint;
18497      };
18498
18499      template<class U> struct S
18500      {
18501        C::myint mi; // <-- usage point of the typedef C::myint
18502      };
18503
18504      S<char> s;
18505
18506    At S<char> instantiation time, we need to check the access of C::myint
18507    In other words, we need to check the access of the myint typedef through
18508    the C scope. For that purpose, this function will add the myint typedef
18509    and the scope C through which its being accessed to a list of typedefs
18510    tied to the template S. That list will be walked at template instantiation
18511    time and access check performed on each typedefs it contains.
18512    Note that this particular code snippet should yield an error because
18513    myint is private to C.  */
18514
18515 void
18516 append_type_to_template_for_access_check (tree templ,
18517                                           tree type_decl,
18518                                           tree scope,
18519                                           location_t location)
18520 {
18521   qualified_typedef_usage_t *iter;
18522   int i;
18523
18524   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18525
18526   /* Make sure we don't append the type to the template twice.  */
18527   for (i = 0;
18528        VEC_iterate (qualified_typedef_usage_t,
18529                     get_types_needing_access_check (templ),
18530                     i, iter);
18531        ++i)
18532     if (iter->typedef_decl == type_decl && scope == iter->context)
18533       return;
18534
18535   append_type_to_template_for_access_check_1 (templ, type_decl,
18536                                               scope, location);
18537 }
18538
18539 /* Set up the hash tables for template instantiations.  */
18540
18541 void
18542 init_template_processing (void)
18543 {
18544   decl_specializations = htab_create_ggc (37,
18545                                           hash_specialization,
18546                                           eq_specializations,
18547                                           ggc_free);
18548   type_specializations = htab_create_ggc (37,
18549                                           hash_specialization,
18550                                           eq_specializations,
18551                                           ggc_free);
18552 }
18553
18554 #include "gt-cp-pt.h"