OSDN Git Service

PR c++/43016
[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, 2010
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     case LAMBDA_EXPR:
1567       /* A lambda can't appear in a template arg, but don't crash on
1568          erroneous input.  */
1569       gcc_assert (errorcount > 0);
1570       return val;
1571
1572     default:
1573       switch (tclass)
1574         {
1575         case tcc_type:
1576           if (TYPE_CANONICAL (arg))
1577             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1578                                           val);
1579           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1580             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1581           /* Otherwise just compare the types during lookup.  */
1582           return val;
1583
1584         case tcc_declaration:
1585         case tcc_constant:
1586           return iterative_hash_expr (arg, val);
1587
1588         default:
1589           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1590           {
1591             unsigned n = TREE_OPERAND_LENGTH (arg);
1592             for (i = 0; i < n; ++i)
1593               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1594             return val;
1595           }
1596         }
1597     }
1598   gcc_unreachable ();
1599   return 0;
1600 }
1601
1602 /* Unregister the specialization SPEC as a specialization of TMPL.
1603    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1604    if the SPEC was listed as a specialization of TMPL.
1605
1606    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1607
1608 bool
1609 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1610 {
1611   spec_entry **slot;
1612   spec_entry elt;
1613
1614   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1615   elt.args = TI_ARGS (tinfo);
1616   elt.spec = NULL_TREE;
1617
1618   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1619   if (*slot)
1620     {
1621       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1622       gcc_assert (new_spec != NULL_TREE);
1623       (*slot)->spec = new_spec;
1624       return 1;
1625     }
1626
1627   return 0;
1628 }
1629
1630 /* Compare an entry in the local specializations hash table P1 (which
1631    is really a pointer to a TREE_LIST) with P2 (which is really a
1632    DECL).  */
1633
1634 static int
1635 eq_local_specializations (const void *p1, const void *p2)
1636 {
1637   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1638 }
1639
1640 /* Hash P1, an entry in the local specializations table.  */
1641
1642 static hashval_t
1643 hash_local_specialization (const void* p1)
1644 {
1645   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1646 }
1647
1648 /* Like register_specialization, but for local declarations.  We are
1649    registering SPEC, an instantiation of TMPL.  */
1650
1651 static void
1652 register_local_specialization (tree spec, tree tmpl)
1653 {
1654   void **slot;
1655
1656   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1657                                    htab_hash_pointer (tmpl), INSERT);
1658   *slot = build_tree_list (spec, tmpl);
1659 }
1660
1661 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1662    specialized class.  */
1663
1664 bool
1665 explicit_class_specialization_p (tree type)
1666 {
1667   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1668     return false;
1669   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1670 }
1671
1672 /* Print the list of functions at FNS, going through all the overloads
1673    for each element of the list.  Alternatively, FNS can not be a
1674    TREE_LIST, in which case it will be printed together with all the
1675    overloads.
1676
1677    MORE and *STR should respectively be FALSE and NULL when the function
1678    is called from the outside.  They are used internally on recursive
1679    calls.  print_candidates manages the two parameters and leaves NULL
1680    in *STR when it ends.  */
1681
1682 static void
1683 print_candidates_1 (tree fns, bool more, const char **str)
1684 {
1685   tree fn, fn2;
1686   char *spaces = NULL;
1687
1688   for (fn = fns; fn; fn = OVL_NEXT (fn))
1689     if (TREE_CODE (fn) == TREE_LIST)
1690       {
1691         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1692         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1693           print_candidates_1 (TREE_VALUE (fn2),
1694                               TREE_CHAIN (fn2) || more, str);
1695       }
1696     else
1697       {
1698         if (!*str)
1699           {
1700             /* Pick the prefix string.  */
1701             if (!more && !OVL_NEXT (fns))
1702               {
1703                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1704                 continue;
1705               }
1706
1707             *str = _("candidates are:");
1708             spaces = get_spaces (*str);
1709           }
1710         error ("%s %+#D", *str, OVL_CURRENT (fn));
1711         *str = spaces ? spaces : *str;
1712       }
1713
1714   if (!more)
1715     {
1716       free (spaces);
1717       *str = NULL;
1718     }
1719 }
1720
1721 /* Print the list of candidate FNS in an error message.  */
1722
1723 void
1724 print_candidates (tree fns)
1725 {
1726   const char *str = NULL;
1727   print_candidates_1 (fns, false, &str);
1728   gcc_assert (str == NULL);
1729 }
1730
1731 /* Returns the template (one of the functions given by TEMPLATE_ID)
1732    which can be specialized to match the indicated DECL with the
1733    explicit template args given in TEMPLATE_ID.  The DECL may be
1734    NULL_TREE if none is available.  In that case, the functions in
1735    TEMPLATE_ID are non-members.
1736
1737    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1738    specialization of a member template.
1739
1740    The TEMPLATE_COUNT is the number of references to qualifying
1741    template classes that appeared in the name of the function. See
1742    check_explicit_specialization for a more accurate description.
1743
1744    TSK indicates what kind of template declaration (if any) is being
1745    declared.  TSK_TEMPLATE indicates that the declaration given by
1746    DECL, though a FUNCTION_DECL, has template parameters, and is
1747    therefore a template function.
1748
1749    The template args (those explicitly specified and those deduced)
1750    are output in a newly created vector *TARGS_OUT.
1751
1752    If it is impossible to determine the result, an error message is
1753    issued.  The error_mark_node is returned to indicate failure.  */
1754
1755 static tree
1756 determine_specialization (tree template_id,
1757                           tree decl,
1758                           tree* targs_out,
1759                           int need_member_template,
1760                           int template_count,
1761                           tmpl_spec_kind tsk)
1762 {
1763   tree fns;
1764   tree targs;
1765   tree explicit_targs;
1766   tree candidates = NULL_TREE;
1767   /* A TREE_LIST of templates of which DECL may be a specialization.
1768      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1769      corresponding TREE_PURPOSE is the set of template arguments that,
1770      when used to instantiate the template, would produce a function
1771      with the signature of DECL.  */
1772   tree templates = NULL_TREE;
1773   int header_count;
1774   struct cp_binding_level *b;
1775
1776   *targs_out = NULL_TREE;
1777
1778   if (template_id == error_mark_node || decl == error_mark_node)
1779     return error_mark_node;
1780
1781   fns = TREE_OPERAND (template_id, 0);
1782   explicit_targs = TREE_OPERAND (template_id, 1);
1783
1784   if (fns == error_mark_node)
1785     return error_mark_node;
1786
1787   /* Check for baselinks.  */
1788   if (BASELINK_P (fns))
1789     fns = BASELINK_FUNCTIONS (fns);
1790
1791   if (!is_overloaded_fn (fns))
1792     {
1793       error ("%qD is not a function template", fns);
1794       return error_mark_node;
1795     }
1796
1797   /* Count the number of template headers specified for this
1798      specialization.  */
1799   header_count = 0;
1800   for (b = current_binding_level;
1801        b->kind == sk_template_parms;
1802        b = b->level_chain)
1803     ++header_count;
1804
1805   for (; fns; fns = OVL_NEXT (fns))
1806     {
1807       tree fn = OVL_CURRENT (fns);
1808
1809       if (TREE_CODE (fn) == TEMPLATE_DECL)
1810         {
1811           tree decl_arg_types;
1812           tree fn_arg_types;
1813
1814           /* In case of explicit specialization, we need to check if
1815              the number of template headers appearing in the specialization
1816              is correct. This is usually done in check_explicit_specialization,
1817              but the check done there cannot be exhaustive when specializing
1818              member functions. Consider the following code:
1819
1820              template <> void A<int>::f(int);
1821              template <> template <> void A<int>::f(int);
1822
1823              Assuming that A<int> is not itself an explicit specialization
1824              already, the first line specializes "f" which is a non-template
1825              member function, whilst the second line specializes "f" which
1826              is a template member function. So both lines are syntactically
1827              correct, and check_explicit_specialization does not reject
1828              them.
1829
1830              Here, we can do better, as we are matching the specialization
1831              against the declarations. We count the number of template
1832              headers, and we check if they match TEMPLATE_COUNT + 1
1833              (TEMPLATE_COUNT is the number of qualifying template classes,
1834              plus there must be another header for the member template
1835              itself).
1836
1837              Notice that if header_count is zero, this is not a
1838              specialization but rather a template instantiation, so there
1839              is no check we can perform here.  */
1840           if (header_count && header_count != template_count + 1)
1841             continue;
1842
1843           /* Check that the number of template arguments at the
1844              innermost level for DECL is the same as for FN.  */
1845           if (current_binding_level->kind == sk_template_parms
1846               && !current_binding_level->explicit_spec_p
1847               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1848                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1849                                       (current_template_parms))))
1850             continue;
1851
1852           /* DECL might be a specialization of FN.  */
1853           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1854           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1855
1856           /* For a non-static member function, we need to make sure
1857              that the const qualification is the same.  Since
1858              get_bindings does not try to merge the "this" parameter,
1859              we must do the comparison explicitly.  */
1860           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1861               && !same_type_p (TREE_VALUE (fn_arg_types),
1862                                TREE_VALUE (decl_arg_types)))
1863             continue;
1864
1865           /* Skip the "this" parameter and, for constructors of
1866              classes with virtual bases, the VTT parameter.  A
1867              full specialization of a constructor will have a VTT
1868              parameter, but a template never will.  */ 
1869           decl_arg_types 
1870             = skip_artificial_parms_for (decl, decl_arg_types);
1871           fn_arg_types 
1872             = skip_artificial_parms_for (fn, fn_arg_types);
1873
1874           /* Check that the number of function parameters matches.
1875              For example,
1876                template <class T> void f(int i = 0);
1877                template <> void f<int>();
1878              The specialization f<int> is invalid but is not caught
1879              by get_bindings below.  */
1880           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1881             continue;
1882
1883           /* Function templates cannot be specializations; there are
1884              no partial specializations of functions.  Therefore, if
1885              the type of DECL does not match FN, there is no
1886              match.  */
1887           if (tsk == tsk_template)
1888             {
1889               if (compparms (fn_arg_types, decl_arg_types))
1890                 candidates = tree_cons (NULL_TREE, fn, candidates);
1891               continue;
1892             }
1893
1894           /* See whether this function might be a specialization of this
1895              template.  */
1896           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1897
1898           if (!targs)
1899             /* We cannot deduce template arguments that when used to
1900                specialize TMPL will produce DECL.  */
1901             continue;
1902
1903           /* Save this template, and the arguments deduced.  */
1904           templates = tree_cons (targs, fn, templates);
1905         }
1906       else if (need_member_template)
1907         /* FN is an ordinary member function, and we need a
1908            specialization of a member template.  */
1909         ;
1910       else if (TREE_CODE (fn) != FUNCTION_DECL)
1911         /* We can get IDENTIFIER_NODEs here in certain erroneous
1912            cases.  */
1913         ;
1914       else if (!DECL_FUNCTION_MEMBER_P (fn))
1915         /* This is just an ordinary non-member function.  Nothing can
1916            be a specialization of that.  */
1917         ;
1918       else if (DECL_ARTIFICIAL (fn))
1919         /* Cannot specialize functions that are created implicitly.  */
1920         ;
1921       else
1922         {
1923           tree decl_arg_types;
1924
1925           /* This is an ordinary member function.  However, since
1926              we're here, we can assume it's enclosing class is a
1927              template class.  For example,
1928
1929                template <typename T> struct S { void f(); };
1930                template <> void S<int>::f() {}
1931
1932              Here, S<int>::f is a non-template, but S<int> is a
1933              template class.  If FN has the same type as DECL, we
1934              might be in business.  */
1935
1936           if (!DECL_TEMPLATE_INFO (fn))
1937             /* Its enclosing class is an explicit specialization
1938                of a template class.  This is not a candidate.  */
1939             continue;
1940
1941           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1942                             TREE_TYPE (TREE_TYPE (fn))))
1943             /* The return types differ.  */
1944             continue;
1945
1946           /* Adjust the type of DECL in case FN is a static member.  */
1947           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1948           if (DECL_STATIC_FUNCTION_P (fn)
1949               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1950             decl_arg_types = TREE_CHAIN (decl_arg_types);
1951
1952           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1953                          decl_arg_types))
1954             /* They match!  */
1955             candidates = tree_cons (NULL_TREE, fn, candidates);
1956         }
1957     }
1958
1959   if (templates && TREE_CHAIN (templates))
1960     {
1961       /* We have:
1962
1963            [temp.expl.spec]
1964
1965            It is possible for a specialization with a given function
1966            signature to be instantiated from more than one function
1967            template.  In such cases, explicit specification of the
1968            template arguments must be used to uniquely identify the
1969            function template specialization being specialized.
1970
1971          Note that here, there's no suggestion that we're supposed to
1972          determine which of the candidate templates is most
1973          specialized.  However, we, also have:
1974
1975            [temp.func.order]
1976
1977            Partial ordering of overloaded function template
1978            declarations is used in the following contexts to select
1979            the function template to which a function template
1980            specialization refers:
1981
1982            -- when an explicit specialization refers to a function
1983               template.
1984
1985          So, we do use the partial ordering rules, at least for now.
1986          This extension can only serve to make invalid programs valid,
1987          so it's safe.  And, there is strong anecdotal evidence that
1988          the committee intended the partial ordering rules to apply;
1989          the EDG front end has that behavior, and John Spicer claims
1990          that the committee simply forgot to delete the wording in
1991          [temp.expl.spec].  */
1992       tree tmpl = most_specialized_instantiation (templates);
1993       if (tmpl != error_mark_node)
1994         {
1995           templates = tmpl;
1996           TREE_CHAIN (templates) = NULL_TREE;
1997         }
1998     }
1999
2000   if (templates == NULL_TREE && candidates == NULL_TREE)
2001     {
2002       error ("template-id %qD for %q+D does not match any template "
2003              "declaration", template_id, decl);
2004       if (header_count && header_count != template_count + 1)
2005         inform (input_location, "saw %d %<template<>%>, need %d for "
2006                 "specializing a member function template",
2007                 header_count, template_count + 1);
2008       return error_mark_node;
2009     }
2010   else if ((templates && TREE_CHAIN (templates))
2011            || (candidates && TREE_CHAIN (candidates))
2012            || (templates && candidates))
2013     {
2014       error ("ambiguous template specialization %qD for %q+D",
2015              template_id, decl);
2016       candidates = chainon (candidates, templates);
2017       print_candidates (candidates);
2018       return error_mark_node;
2019     }
2020
2021   /* We have one, and exactly one, match.  */
2022   if (candidates)
2023     {
2024       tree fn = TREE_VALUE (candidates);
2025       *targs_out = copy_node (DECL_TI_ARGS (fn));
2026       /* DECL is a re-declaration or partial instantiation of a template
2027          function.  */
2028       if (TREE_CODE (fn) == TEMPLATE_DECL)
2029         return fn;
2030       /* It was a specialization of an ordinary member function in a
2031          template class.  */
2032       return DECL_TI_TEMPLATE (fn);
2033     }
2034
2035   /* It was a specialization of a template.  */
2036   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2037   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2038     {
2039       *targs_out = copy_node (targs);
2040       SET_TMPL_ARGS_LEVEL (*targs_out,
2041                            TMPL_ARGS_DEPTH (*targs_out),
2042                            TREE_PURPOSE (templates));
2043     }
2044   else
2045     *targs_out = TREE_PURPOSE (templates);
2046   return TREE_VALUE (templates);
2047 }
2048
2049 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2050    but with the default argument values filled in from those in the
2051    TMPL_TYPES.  */
2052
2053 static tree
2054 copy_default_args_to_explicit_spec_1 (tree spec_types,
2055                                       tree tmpl_types)
2056 {
2057   tree new_spec_types;
2058
2059   if (!spec_types)
2060     return NULL_TREE;
2061
2062   if (spec_types == void_list_node)
2063     return void_list_node;
2064
2065   /* Substitute into the rest of the list.  */
2066   new_spec_types =
2067     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2068                                           TREE_CHAIN (tmpl_types));
2069
2070   /* Add the default argument for this parameter.  */
2071   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2072                          TREE_VALUE (spec_types),
2073                          new_spec_types);
2074 }
2075
2076 /* DECL is an explicit specialization.  Replicate default arguments
2077    from the template it specializes.  (That way, code like:
2078
2079      template <class T> void f(T = 3);
2080      template <> void f(double);
2081      void g () { f (); }
2082
2083    works, as required.)  An alternative approach would be to look up
2084    the correct default arguments at the call-site, but this approach
2085    is consistent with how implicit instantiations are handled.  */
2086
2087 static void
2088 copy_default_args_to_explicit_spec (tree decl)
2089 {
2090   tree tmpl;
2091   tree spec_types;
2092   tree tmpl_types;
2093   tree new_spec_types;
2094   tree old_type;
2095   tree new_type;
2096   tree t;
2097   tree object_type = NULL_TREE;
2098   tree in_charge = NULL_TREE;
2099   tree vtt = NULL_TREE;
2100
2101   /* See if there's anything we need to do.  */
2102   tmpl = DECL_TI_TEMPLATE (decl);
2103   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2104   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2105     if (TREE_PURPOSE (t))
2106       break;
2107   if (!t)
2108     return;
2109
2110   old_type = TREE_TYPE (decl);
2111   spec_types = TYPE_ARG_TYPES (old_type);
2112
2113   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2114     {
2115       /* Remove the this pointer, but remember the object's type for
2116          CV quals.  */
2117       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2118       spec_types = TREE_CHAIN (spec_types);
2119       tmpl_types = TREE_CHAIN (tmpl_types);
2120
2121       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2122         {
2123           /* DECL may contain more parameters than TMPL due to the extra
2124              in-charge parameter in constructors and destructors.  */
2125           in_charge = spec_types;
2126           spec_types = TREE_CHAIN (spec_types);
2127         }
2128       if (DECL_HAS_VTT_PARM_P (decl))
2129         {
2130           vtt = spec_types;
2131           spec_types = TREE_CHAIN (spec_types);
2132         }
2133     }
2134
2135   /* Compute the merged default arguments.  */
2136   new_spec_types =
2137     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2138
2139   /* Compute the new FUNCTION_TYPE.  */
2140   if (object_type)
2141     {
2142       if (vtt)
2143         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2144                                          TREE_VALUE (vtt),
2145                                          new_spec_types);
2146
2147       if (in_charge)
2148         /* Put the in-charge parameter back.  */
2149         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2150                                          TREE_VALUE (in_charge),
2151                                          new_spec_types);
2152
2153       new_type = build_method_type_directly (object_type,
2154                                              TREE_TYPE (old_type),
2155                                              new_spec_types);
2156     }
2157   else
2158     new_type = build_function_type (TREE_TYPE (old_type),
2159                                     new_spec_types);
2160   new_type = cp_build_type_attribute_variant (new_type,
2161                                               TYPE_ATTRIBUTES (old_type));
2162   new_type = build_exception_variant (new_type,
2163                                       TYPE_RAISES_EXCEPTIONS (old_type));
2164   TREE_TYPE (decl) = new_type;
2165 }
2166
2167 /* Check to see if the function just declared, as indicated in
2168    DECLARATOR, and in DECL, is a specialization of a function
2169    template.  We may also discover that the declaration is an explicit
2170    instantiation at this point.
2171
2172    Returns DECL, or an equivalent declaration that should be used
2173    instead if all goes well.  Issues an error message if something is
2174    amiss.  Returns error_mark_node if the error is not easily
2175    recoverable.
2176
2177    FLAGS is a bitmask consisting of the following flags:
2178
2179    2: The function has a definition.
2180    4: The function is a friend.
2181
2182    The TEMPLATE_COUNT is the number of references to qualifying
2183    template classes that appeared in the name of the function.  For
2184    example, in
2185
2186      template <class T> struct S { void f(); };
2187      void S<int>::f();
2188
2189    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2190    classes are not counted in the TEMPLATE_COUNT, so that in
2191
2192      template <class T> struct S {};
2193      template <> struct S<int> { void f(); }
2194      template <> void S<int>::f();
2195
2196    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2197    invalid; there should be no template <>.)
2198
2199    If the function is a specialization, it is marked as such via
2200    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2201    is set up correctly, and it is added to the list of specializations
2202    for that template.  */
2203
2204 tree
2205 check_explicit_specialization (tree declarator,
2206                                tree decl,
2207                                int template_count,
2208                                int flags)
2209 {
2210   int have_def = flags & 2;
2211   int is_friend = flags & 4;
2212   int specialization = 0;
2213   int explicit_instantiation = 0;
2214   int member_specialization = 0;
2215   tree ctype = DECL_CLASS_CONTEXT (decl);
2216   tree dname = DECL_NAME (decl);
2217   tmpl_spec_kind tsk;
2218
2219   if (is_friend)
2220     {
2221       if (!processing_specialization)
2222         tsk = tsk_none;
2223       else
2224         tsk = tsk_excessive_parms;
2225     }
2226   else
2227     tsk = current_tmpl_spec_kind (template_count);
2228
2229   switch (tsk)
2230     {
2231     case tsk_none:
2232       if (processing_specialization)
2233         {
2234           specialization = 1;
2235           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2236         }
2237       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2238         {
2239           if (is_friend)
2240             /* This could be something like:
2241
2242                template <class T> void f(T);
2243                class S { friend void f<>(int); }  */
2244             specialization = 1;
2245           else
2246             {
2247               /* This case handles bogus declarations like template <>
2248                  template <class T> void f<int>(); */
2249
2250               error ("template-id %qD in declaration of primary template",
2251                      declarator);
2252               return decl;
2253             }
2254         }
2255       break;
2256
2257     case tsk_invalid_member_spec:
2258       /* The error has already been reported in
2259          check_specialization_scope.  */
2260       return error_mark_node;
2261
2262     case tsk_invalid_expl_inst:
2263       error ("template parameter list used in explicit instantiation");
2264
2265       /* Fall through.  */
2266
2267     case tsk_expl_inst:
2268       if (have_def)
2269         error ("definition provided for explicit instantiation");
2270
2271       explicit_instantiation = 1;
2272       break;
2273
2274     case tsk_excessive_parms:
2275     case tsk_insufficient_parms:
2276       if (tsk == tsk_excessive_parms)
2277         error ("too many template parameter lists in declaration of %qD",
2278                decl);
2279       else if (template_header_count)
2280         error("too few template parameter lists in declaration of %qD", decl);
2281       else
2282         error("explicit specialization of %qD must be introduced by "
2283               "%<template <>%>", decl);
2284
2285       /* Fall through.  */
2286     case tsk_expl_spec:
2287       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2288       if (ctype)
2289         member_specialization = 1;
2290       else
2291         specialization = 1;
2292       break;
2293
2294     case tsk_template:
2295       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2296         {
2297           /* This case handles bogus declarations like template <>
2298              template <class T> void f<int>(); */
2299
2300           if (uses_template_parms (declarator))
2301             error ("function template partial specialization %qD "
2302                    "is not allowed", declarator);
2303           else
2304             error ("template-id %qD in declaration of primary template",
2305                    declarator);
2306           return decl;
2307         }
2308
2309       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2310         /* This is a specialization of a member template, without
2311            specialization the containing class.  Something like:
2312
2313              template <class T> struct S {
2314                template <class U> void f (U);
2315              };
2316              template <> template <class U> void S<int>::f(U) {}
2317
2318            That's a specialization -- but of the entire template.  */
2319         specialization = 1;
2320       break;
2321
2322     default:
2323       gcc_unreachable ();
2324     }
2325
2326   if (specialization || member_specialization)
2327     {
2328       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2329       for (; t; t = TREE_CHAIN (t))
2330         if (TREE_PURPOSE (t))
2331           {
2332             permerror (input_location, 
2333                        "default argument specified in explicit specialization");
2334             break;
2335           }
2336     }
2337
2338   if (specialization || member_specialization || explicit_instantiation)
2339     {
2340       tree tmpl = NULL_TREE;
2341       tree targs = NULL_TREE;
2342
2343       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2344       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2345         {
2346           tree fns;
2347
2348           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2349           if (ctype)
2350             fns = dname;
2351           else
2352             {
2353               /* If there is no class context, the explicit instantiation
2354                  must be at namespace scope.  */
2355               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2356
2357               /* Find the namespace binding, using the declaration
2358                  context.  */
2359               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2360                                            false, true);
2361               if (fns == error_mark_node || !is_overloaded_fn (fns))
2362                 {
2363                   error ("%qD is not a template function", dname);
2364                   fns = error_mark_node;
2365                 }
2366               else
2367                 {
2368                   tree fn = OVL_CURRENT (fns);
2369                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2370                                                 CP_DECL_CONTEXT (fn)))
2371                     error ("%qD is not declared in %qD",
2372                            decl, current_namespace);
2373                 }
2374             }
2375
2376           declarator = lookup_template_function (fns, NULL_TREE);
2377         }
2378
2379       if (declarator == error_mark_node)
2380         return error_mark_node;
2381
2382       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2383         {
2384           if (!explicit_instantiation)
2385             /* A specialization in class scope.  This is invalid,
2386                but the error will already have been flagged by
2387                check_specialization_scope.  */
2388             return error_mark_node;
2389           else
2390             {
2391               /* It's not valid to write an explicit instantiation in
2392                  class scope, e.g.:
2393
2394                    class C { template void f(); }
2395
2396                    This case is caught by the parser.  However, on
2397                    something like:
2398
2399                    template class C { void f(); };
2400
2401                    (which is invalid) we can get here.  The error will be
2402                    issued later.  */
2403               ;
2404             }
2405
2406           return decl;
2407         }
2408       else if (ctype != NULL_TREE
2409                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2410                    IDENTIFIER_NODE))
2411         {
2412           /* Find the list of functions in ctype that have the same
2413              name as the declared function.  */
2414           tree name = TREE_OPERAND (declarator, 0);
2415           tree fns = NULL_TREE;
2416           int idx;
2417
2418           if (constructor_name_p (name, ctype))
2419             {
2420               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2421
2422               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2423                   : !CLASSTYPE_DESTRUCTORS (ctype))
2424                 {
2425                   /* From [temp.expl.spec]:
2426
2427                      If such an explicit specialization for the member
2428                      of a class template names an implicitly-declared
2429                      special member function (clause _special_), the
2430                      program is ill-formed.
2431
2432                      Similar language is found in [temp.explicit].  */
2433                   error ("specialization of implicitly-declared special member function");
2434                   return error_mark_node;
2435                 }
2436
2437               name = is_constructor ? ctor_identifier : dtor_identifier;
2438             }
2439
2440           if (!DECL_CONV_FN_P (decl))
2441             {
2442               idx = lookup_fnfields_1 (ctype, name);
2443               if (idx >= 0)
2444                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2445             }
2446           else
2447             {
2448               VEC(tree,gc) *methods;
2449               tree ovl;
2450
2451               /* For a type-conversion operator, we cannot do a
2452                  name-based lookup.  We might be looking for `operator
2453                  int' which will be a specialization of `operator T'.
2454                  So, we find *all* the conversion operators, and then
2455                  select from them.  */
2456               fns = NULL_TREE;
2457
2458               methods = CLASSTYPE_METHOD_VEC (ctype);
2459               if (methods)
2460                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2461                      VEC_iterate (tree, methods, idx, ovl);
2462                      ++idx)
2463                   {
2464                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2465                       /* There are no more conversion functions.  */
2466                       break;
2467
2468                     /* Glue all these conversion functions together
2469                        with those we already have.  */
2470                     for (; ovl; ovl = OVL_NEXT (ovl))
2471                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2472                   }
2473             }
2474
2475           if (fns == NULL_TREE)
2476             {
2477               error ("no member function %qD declared in %qT", name, ctype);
2478               return error_mark_node;
2479             }
2480           else
2481             TREE_OPERAND (declarator, 0) = fns;
2482         }
2483
2484       /* Figure out what exactly is being specialized at this point.
2485          Note that for an explicit instantiation, even one for a
2486          member function, we cannot tell apriori whether the
2487          instantiation is for a member template, or just a member
2488          function of a template class.  Even if a member template is
2489          being instantiated, the member template arguments may be
2490          elided if they can be deduced from the rest of the
2491          declaration.  */
2492       tmpl = determine_specialization (declarator, decl,
2493                                        &targs,
2494                                        member_specialization,
2495                                        template_count,
2496                                        tsk);
2497
2498       if (!tmpl || tmpl == error_mark_node)
2499         /* We couldn't figure out what this declaration was
2500            specializing.  */
2501         return error_mark_node;
2502       else
2503         {
2504           tree gen_tmpl = most_general_template (tmpl);
2505
2506           if (explicit_instantiation)
2507             {
2508               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2509                  is done by do_decl_instantiation later.  */
2510
2511               int arg_depth = TMPL_ARGS_DEPTH (targs);
2512               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2513
2514               if (arg_depth > parm_depth)
2515                 {
2516                   /* If TMPL is not the most general template (for
2517                      example, if TMPL is a friend template that is
2518                      injected into namespace scope), then there will
2519                      be too many levels of TARGS.  Remove some of them
2520                      here.  */
2521                   int i;
2522                   tree new_targs;
2523
2524                   new_targs = make_tree_vec (parm_depth);
2525                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2526                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2527                       = TREE_VEC_ELT (targs, i);
2528                   targs = new_targs;
2529                 }
2530
2531               return instantiate_template (tmpl, targs, tf_error);
2532             }
2533
2534           /* If we thought that the DECL was a member function, but it
2535              turns out to be specializing a static member function,
2536              make DECL a static member function as well.  */
2537           if (DECL_STATIC_FUNCTION_P (tmpl)
2538               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2539             revert_static_member_fn (decl);
2540
2541           /* If this is a specialization of a member template of a
2542              template class, we want to return the TEMPLATE_DECL, not
2543              the specialization of it.  */
2544           if (tsk == tsk_template)
2545             {
2546               tree result = DECL_TEMPLATE_RESULT (tmpl);
2547               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2548               DECL_INITIAL (result) = NULL_TREE;
2549               if (have_def)
2550                 {
2551                   tree parm;
2552                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2553                   DECL_SOURCE_LOCATION (result)
2554                     = DECL_SOURCE_LOCATION (decl);
2555                   /* We want to use the argument list specified in the
2556                      definition, not in the original declaration.  */
2557                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2558                   for (parm = DECL_ARGUMENTS (result); parm;
2559                        parm = TREE_CHAIN (parm))
2560                     DECL_CONTEXT (parm) = result;
2561                 }
2562               return register_specialization (tmpl, gen_tmpl, targs,
2563                                               is_friend, 0);
2564             }
2565
2566           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2567           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2568
2569           /* Inherit default function arguments from the template
2570              DECL is specializing.  */
2571           copy_default_args_to_explicit_spec (decl);
2572
2573           /* This specialization has the same protection as the
2574              template it specializes.  */
2575           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2576           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2577
2578           /* 7.1.1-1 [dcl.stc]
2579
2580              A storage-class-specifier shall not be specified in an
2581              explicit specialization...
2582
2583              The parser rejects these, so unless action is taken here,
2584              explicit function specializations will always appear with
2585              global linkage.
2586
2587              The action recommended by the C++ CWG in response to C++
2588              defect report 605 is to make the storage class and linkage
2589              of the explicit specialization match the templated function:
2590
2591              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2592            */
2593           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2594             {
2595               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2596               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2597
2598               /* This specialization has the same linkage and visibility as
2599                  the function template it specializes.  */
2600               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2601               if (! TREE_PUBLIC (decl))
2602                 {
2603                   DECL_INTERFACE_KNOWN (decl) = 1;
2604                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2605                 }
2606               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2607               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2608                 {
2609                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2610                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2611                 }
2612             }
2613
2614           /* If DECL is a friend declaration, declared using an
2615              unqualified name, the namespace associated with DECL may
2616              have been set incorrectly.  For example, in:
2617
2618                template <typename T> void f(T);
2619                namespace N {
2620                  struct S { friend void f<int>(int); }
2621                }
2622
2623              we will have set the DECL_CONTEXT for the friend
2624              declaration to N, rather than to the global namespace.  */
2625           if (DECL_NAMESPACE_SCOPE_P (decl))
2626             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2627
2628           if (is_friend && !have_def)
2629             /* This is not really a declaration of a specialization.
2630                It's just the name of an instantiation.  But, it's not
2631                a request for an instantiation, either.  */
2632             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2633           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2634             /* This is indeed a specialization.  In case of constructors
2635                and destructors, we need in-charge and not-in-charge
2636                versions in V3 ABI.  */
2637             clone_function_decl (decl, /*update_method_vec_p=*/0);
2638
2639           /* Register this specialization so that we can find it
2640              again.  */
2641           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2642         }
2643     }
2644
2645   return decl;
2646 }
2647
2648 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2649    parameters.  These are represented in the same format used for
2650    DECL_TEMPLATE_PARMS.  */
2651
2652 int
2653 comp_template_parms (const_tree parms1, const_tree parms2)
2654 {
2655   const_tree p1;
2656   const_tree p2;
2657
2658   if (parms1 == parms2)
2659     return 1;
2660
2661   for (p1 = parms1, p2 = parms2;
2662        p1 != NULL_TREE && p2 != NULL_TREE;
2663        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2664     {
2665       tree t1 = TREE_VALUE (p1);
2666       tree t2 = TREE_VALUE (p2);
2667       int i;
2668
2669       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2670       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2671
2672       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2673         return 0;
2674
2675       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2676         {
2677           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2678           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2679
2680           /* If either of the template parameters are invalid, assume
2681              they match for the sake of error recovery. */
2682           if (parm1 == error_mark_node || parm2 == error_mark_node)
2683             return 1;
2684
2685           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2686             return 0;
2687
2688           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2689               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2690                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2691             continue;
2692           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2693             return 0;
2694         }
2695     }
2696
2697   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2698     /* One set of parameters has more parameters lists than the
2699        other.  */
2700     return 0;
2701
2702   return 1;
2703 }
2704
2705 /* Determine whether PARM is a parameter pack.  */
2706
2707 bool 
2708 template_parameter_pack_p (const_tree parm)
2709 {
2710   /* Determine if we have a non-type template parameter pack.  */
2711   if (TREE_CODE (parm) == PARM_DECL)
2712     return (DECL_TEMPLATE_PARM_P (parm) 
2713             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2714
2715   /* If this is a list of template parameters, we could get a
2716      TYPE_DECL or a TEMPLATE_DECL.  */ 
2717   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2718     parm = TREE_TYPE (parm);
2719
2720   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2721            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2722           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2723 }
2724
2725 /* Determine if T is a function parameter pack.  */
2726
2727 bool
2728 function_parameter_pack_p (const_tree t)
2729 {
2730   if (t && TREE_CODE (t) == PARM_DECL)
2731     return FUNCTION_PARAMETER_PACK_P (t);
2732   return false;
2733 }
2734
2735 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2736    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2737
2738 tree
2739 get_function_template_decl (const_tree primary_func_tmpl_inst)
2740 {
2741   if (! primary_func_tmpl_inst
2742       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2743       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2744     return NULL;
2745
2746   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2747 }
2748
2749 /* Return true iff the function parameter PARAM_DECL was expanded
2750    from the function parameter pack PACK.  */
2751
2752 bool
2753 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2754 {
2755   if (DECL_ARTIFICIAL (param_decl)
2756       || !function_parameter_pack_p (pack))
2757     return false;
2758
2759   /* The parameter pack and its pack arguments have the same
2760      DECL_PARM_INDEX.  */
2761   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2762 }
2763
2764 /* Determine whether ARGS describes a variadic template args list,
2765    i.e., one that is terminated by a template argument pack.  */
2766
2767 static bool 
2768 template_args_variadic_p (tree args)
2769 {
2770   int nargs;
2771   tree last_parm;
2772
2773   if (args == NULL_TREE)
2774     return false;
2775
2776   args = INNERMOST_TEMPLATE_ARGS (args);
2777   nargs = TREE_VEC_LENGTH (args);
2778
2779   if (nargs == 0)
2780     return false;
2781
2782   last_parm = TREE_VEC_ELT (args, nargs - 1);
2783
2784   return ARGUMENT_PACK_P (last_parm);
2785 }
2786
2787 /* Generate a new name for the parameter pack name NAME (an
2788    IDENTIFIER_NODE) that incorporates its */
2789
2790 static tree
2791 make_ith_pack_parameter_name (tree name, int i)
2792 {
2793   /* Munge the name to include the parameter index.  */
2794 #define NUMBUF_LEN 128
2795   char numbuf[NUMBUF_LEN];
2796   char* newname;
2797   int newname_len;
2798
2799   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2800   newname_len = IDENTIFIER_LENGTH (name)
2801                 + strlen (numbuf) + 2;
2802   newname = (char*)alloca (newname_len);
2803   snprintf (newname, newname_len,
2804             "%s#%i", IDENTIFIER_POINTER (name), i);
2805   return get_identifier (newname);
2806 }
2807
2808 /* Return true if T is a primary function
2809    or class template instantiation.  */
2810
2811 bool
2812 primary_template_instantiation_p (const_tree t)
2813 {
2814   if (!t)
2815     return false;
2816
2817   if (TREE_CODE (t) == FUNCTION_DECL)
2818     return DECL_LANG_SPECIFIC (t)
2819            && DECL_TEMPLATE_INSTANTIATION (t)
2820            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2821   else if (CLASS_TYPE_P (t))
2822     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2823            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2824   return false;
2825 }
2826
2827 /* Return true if PARM is a template template parameter.  */
2828
2829 bool
2830 template_template_parameter_p (const_tree parm)
2831 {
2832   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2833 }
2834
2835 /* Return the template parameters of T if T is a
2836    primary template instantiation, NULL otherwise.  */
2837
2838 tree
2839 get_primary_template_innermost_parameters (const_tree t)
2840 {
2841   tree parms = NULL, template_info = NULL;
2842
2843   if ((template_info = get_template_info (t))
2844       && primary_template_instantiation_p (t))
2845     parms = INNERMOST_TEMPLATE_PARMS
2846         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2847
2848   return parms;
2849 }
2850
2851 /* Return the template parameters of the LEVELth level from the full list
2852    of template parameters PARMS.  */
2853
2854 tree
2855 get_template_parms_at_level (tree parms, int level)
2856 {
2857   tree p;
2858   if (!parms
2859       || TREE_CODE (parms) != TREE_LIST
2860       || level > TMPL_PARMS_DEPTH (parms))
2861     return NULL_TREE;
2862
2863   for (p = parms; p; p = TREE_CHAIN (p))
2864     if (TMPL_PARMS_DEPTH (p) == level)
2865       return p;
2866
2867   return NULL_TREE;
2868 }
2869
2870 /* Returns the template arguments of T if T is a template instantiation,
2871    NULL otherwise.  */
2872
2873 tree
2874 get_template_innermost_arguments (const_tree t)
2875 {
2876   tree args = NULL, template_info = NULL;
2877
2878   if ((template_info = get_template_info (t))
2879       && TI_ARGS (template_info))
2880     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2881
2882   return args;
2883 }
2884
2885 /* Return the argument pack elements of T if T is a template argument pack,
2886    NULL otherwise.  */
2887
2888 tree
2889 get_template_argument_pack_elems (const_tree t)
2890 {
2891   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2892       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2893     return NULL;
2894
2895   return ARGUMENT_PACK_ARGS (t);
2896 }
2897
2898 /* Structure used to track the progress of find_parameter_packs_r.  */
2899 struct find_parameter_pack_data 
2900 {
2901   /* TREE_LIST that will contain all of the parameter packs found by
2902      the traversal.  */
2903   tree* parameter_packs;
2904
2905   /* Set of AST nodes that have been visited by the traversal.  */
2906   struct pointer_set_t *visited;
2907 };
2908
2909 /* Identifies all of the argument packs that occur in a template
2910    argument and appends them to the TREE_LIST inside DATA, which is a
2911    find_parameter_pack_data structure. This is a subroutine of
2912    make_pack_expansion and uses_parameter_packs.  */
2913 static tree
2914 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2915 {
2916   tree t = *tp;
2917   struct find_parameter_pack_data* ppd = 
2918     (struct find_parameter_pack_data*)data;
2919   bool parameter_pack_p = false;
2920
2921   /* Identify whether this is a parameter pack or not.  */
2922   switch (TREE_CODE (t))
2923     {
2924     case TEMPLATE_PARM_INDEX:
2925       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2926         parameter_pack_p = true;
2927       break;
2928
2929     case TEMPLATE_TYPE_PARM:
2930     case TEMPLATE_TEMPLATE_PARM:
2931       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2932         parameter_pack_p = true;
2933       break;
2934
2935     case PARM_DECL:
2936       if (FUNCTION_PARAMETER_PACK_P (t))
2937         {
2938           /* We don't want to walk into the type of a PARM_DECL,
2939              because we don't want to see the type parameter pack.  */
2940           *walk_subtrees = 0;
2941           parameter_pack_p = true;
2942         }
2943       break;
2944
2945     default:
2946       /* Not a parameter pack.  */
2947       break;
2948     }
2949
2950   if (parameter_pack_p)
2951     {
2952       /* Add this parameter pack to the list.  */
2953       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2954     }
2955
2956   if (TYPE_P (t))
2957     cp_walk_tree (&TYPE_CONTEXT (t), 
2958                   &find_parameter_packs_r, ppd, ppd->visited);
2959
2960   /* This switch statement will return immediately if we don't find a
2961      parameter pack.  */
2962   switch (TREE_CODE (t)) 
2963     {
2964     case TEMPLATE_PARM_INDEX:
2965       return NULL_TREE;
2966
2967     case BOUND_TEMPLATE_TEMPLATE_PARM:
2968       /* Check the template itself.  */
2969       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2970                     &find_parameter_packs_r, ppd, ppd->visited);
2971       /* Check the template arguments.  */
2972       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2973                     ppd->visited);
2974       *walk_subtrees = 0;
2975       return NULL_TREE;
2976
2977     case TEMPLATE_TYPE_PARM:
2978     case TEMPLATE_TEMPLATE_PARM:
2979       return NULL_TREE;
2980
2981     case PARM_DECL:
2982       return NULL_TREE;
2983
2984     case RECORD_TYPE:
2985       if (TYPE_PTRMEMFUNC_P (t))
2986         return NULL_TREE;
2987       /* Fall through.  */
2988
2989     case UNION_TYPE:
2990     case ENUMERAL_TYPE:
2991       if (TYPE_TEMPLATE_INFO (t))
2992         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2993                       &find_parameter_packs_r, ppd, ppd->visited);
2994
2995       *walk_subtrees = 0;
2996       return NULL_TREE;
2997
2998     case TEMPLATE_DECL:
2999       cp_walk_tree (&TREE_TYPE (t),
3000                     &find_parameter_packs_r, ppd, ppd->visited);
3001       return NULL_TREE;
3002  
3003     case TYPENAME_TYPE:
3004       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3005                    ppd, ppd->visited);
3006       *walk_subtrees = 0;
3007       return NULL_TREE;
3008       
3009     case TYPE_PACK_EXPANSION:
3010     case EXPR_PACK_EXPANSION:
3011       *walk_subtrees = 0;
3012       return NULL_TREE;
3013
3014     case INTEGER_TYPE:
3015       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3016                     ppd, ppd->visited);
3017       *walk_subtrees = 0;
3018       return NULL_TREE;
3019
3020     case IDENTIFIER_NODE:
3021       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3022                     ppd->visited);
3023       *walk_subtrees = 0;
3024       return NULL_TREE;
3025
3026     default:
3027       return NULL_TREE;
3028     }
3029
3030   return NULL_TREE;
3031 }
3032
3033 /* Determines if the expression or type T uses any parameter packs.  */
3034 bool
3035 uses_parameter_packs (tree t)
3036 {
3037   tree parameter_packs = NULL_TREE;
3038   struct find_parameter_pack_data ppd;
3039   ppd.parameter_packs = &parameter_packs;
3040   ppd.visited = pointer_set_create ();
3041   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3042   pointer_set_destroy (ppd.visited);
3043   return parameter_packs != NULL_TREE;
3044 }
3045
3046 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3047    representation a base-class initializer into a parameter pack
3048    expansion. If all goes well, the resulting node will be an
3049    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3050    respectively.  */
3051 tree 
3052 make_pack_expansion (tree arg)
3053 {
3054   tree result;
3055   tree parameter_packs = NULL_TREE;
3056   bool for_types = false;
3057   struct find_parameter_pack_data ppd;
3058
3059   if (!arg || arg == error_mark_node)
3060     return arg;
3061
3062   if (TREE_CODE (arg) == TREE_LIST)
3063     {
3064       /* The only time we will see a TREE_LIST here is for a base
3065          class initializer.  In this case, the TREE_PURPOSE will be a
3066          _TYPE node (representing the base class expansion we're
3067          initializing) and the TREE_VALUE will be a TREE_LIST
3068          containing the initialization arguments. 
3069
3070          The resulting expansion looks somewhat different from most
3071          expansions. Rather than returning just one _EXPANSION, we
3072          return a TREE_LIST whose TREE_PURPOSE is a
3073          TYPE_PACK_EXPANSION containing the bases that will be
3074          initialized.  The TREE_VALUE will be identical to the
3075          original TREE_VALUE, which is a list of arguments that will
3076          be passed to each base.  We do not introduce any new pack
3077          expansion nodes into the TREE_VALUE (although it is possible
3078          that some already exist), because the TREE_PURPOSE and
3079          TREE_VALUE all need to be expanded together with the same
3080          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3081          resulting TREE_PURPOSE will mention the parameter packs in
3082          both the bases and the arguments to the bases.  */
3083       tree purpose;
3084       tree value;
3085       tree parameter_packs = NULL_TREE;
3086
3087       /* Determine which parameter packs will be used by the base
3088          class expansion.  */
3089       ppd.visited = pointer_set_create ();
3090       ppd.parameter_packs = &parameter_packs;
3091       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3092                     &ppd, ppd.visited);
3093
3094       if (parameter_packs == NULL_TREE)
3095         {
3096           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3097           pointer_set_destroy (ppd.visited);
3098           return error_mark_node;
3099         }
3100
3101       if (TREE_VALUE (arg) != void_type_node)
3102         {
3103           /* Collect the sets of parameter packs used in each of the
3104              initialization arguments.  */
3105           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3106             {
3107               /* Determine which parameter packs will be expanded in this
3108                  argument.  */
3109               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3110                             &ppd, ppd.visited);
3111             }
3112         }
3113
3114       pointer_set_destroy (ppd.visited);
3115
3116       /* Create the pack expansion type for the base type.  */
3117       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3118       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3119       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3120
3121       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3122          they will rarely be compared to anything.  */
3123       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3124
3125       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3126     }
3127
3128   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3129     for_types = true;
3130
3131   /* Build the PACK_EXPANSION_* node.  */
3132   result = for_types
3133      ? cxx_make_type (TYPE_PACK_EXPANSION)
3134      : make_node (EXPR_PACK_EXPANSION);
3135   SET_PACK_EXPANSION_PATTERN (result, arg);
3136   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3137     {
3138       /* Propagate type and const-expression information.  */
3139       TREE_TYPE (result) = TREE_TYPE (arg);
3140       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3141     }
3142   else
3143     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3144        they will rarely be compared to anything.  */
3145     SET_TYPE_STRUCTURAL_EQUALITY (result);
3146
3147   /* Determine which parameter packs will be expanded.  */
3148   ppd.parameter_packs = &parameter_packs;
3149   ppd.visited = pointer_set_create ();
3150   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3151   pointer_set_destroy (ppd.visited);
3152
3153   /* Make sure we found some parameter packs.  */
3154   if (parameter_packs == NULL_TREE)
3155     {
3156       if (TYPE_P (arg))
3157         error ("expansion pattern %<%T%> contains no argument packs", arg);
3158       else
3159         error ("expansion pattern %<%E%> contains no argument packs", arg);
3160       return error_mark_node;
3161     }
3162   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3163
3164   return result;
3165 }
3166
3167 /* Checks T for any "bare" parameter packs, which have not yet been
3168    expanded, and issues an error if any are found. This operation can
3169    only be done on full expressions or types (e.g., an expression
3170    statement, "if" condition, etc.), because we could have expressions like:
3171
3172      foo(f(g(h(args)))...)
3173
3174    where "args" is a parameter pack. check_for_bare_parameter_packs
3175    should not be called for the subexpressions args, h(args),
3176    g(h(args)), or f(g(h(args))), because we would produce erroneous
3177    error messages. 
3178
3179    Returns TRUE and emits an error if there were bare parameter packs,
3180    returns FALSE otherwise.  */
3181 bool 
3182 check_for_bare_parameter_packs (tree t)
3183 {
3184   tree parameter_packs = NULL_TREE;
3185   struct find_parameter_pack_data ppd;
3186
3187   if (!processing_template_decl || !t || t == error_mark_node)
3188     return false;
3189
3190   if (TREE_CODE (t) == TYPE_DECL)
3191     t = TREE_TYPE (t);
3192
3193   ppd.parameter_packs = &parameter_packs;
3194   ppd.visited = pointer_set_create ();
3195   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3196   pointer_set_destroy (ppd.visited);
3197
3198   if (parameter_packs) 
3199     {
3200       error ("parameter packs not expanded with %<...%>:");
3201       while (parameter_packs)
3202         {
3203           tree pack = TREE_VALUE (parameter_packs);
3204           tree name = NULL_TREE;
3205
3206           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3207               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3208             name = TYPE_NAME (pack);
3209           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3210             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3211           else
3212             name = DECL_NAME (pack);
3213
3214           if (name)
3215             inform (input_location, "        %qD", name);
3216           else
3217             inform (input_location, "        <anonymous>");
3218
3219           parameter_packs = TREE_CHAIN (parameter_packs);
3220         }
3221
3222       return true;
3223     }
3224
3225   return false;
3226 }
3227
3228 /* Expand any parameter packs that occur in the template arguments in
3229    ARGS.  */
3230 tree
3231 expand_template_argument_pack (tree args)
3232 {
3233   tree result_args = NULL_TREE;
3234   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3235   int num_result_args = -1;
3236   int non_default_args_count = -1;
3237
3238   /* First, determine if we need to expand anything, and the number of
3239      slots we'll need.  */
3240   for (in_arg = 0; in_arg < nargs; ++in_arg)
3241     {
3242       tree arg = TREE_VEC_ELT (args, in_arg);
3243       if (arg == NULL_TREE)
3244         return args;
3245       if (ARGUMENT_PACK_P (arg))
3246         {
3247           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3248           if (num_result_args < 0)
3249             num_result_args = in_arg + num_packed;
3250           else
3251             num_result_args += num_packed;
3252         }
3253       else
3254         {
3255           if (num_result_args >= 0)
3256             num_result_args++;
3257         }
3258     }
3259
3260   /* If no expansion is necessary, we're done.  */
3261   if (num_result_args < 0)
3262     return args;
3263
3264   /* Expand arguments.  */
3265   result_args = make_tree_vec (num_result_args);
3266   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3267     non_default_args_count =
3268       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3269   for (in_arg = 0; in_arg < nargs; ++in_arg)
3270     {
3271       tree arg = TREE_VEC_ELT (args, in_arg);
3272       if (ARGUMENT_PACK_P (arg))
3273         {
3274           tree packed = ARGUMENT_PACK_ARGS (arg);
3275           int i, num_packed = TREE_VEC_LENGTH (packed);
3276           for (i = 0; i < num_packed; ++i, ++out_arg)
3277             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3278           if (non_default_args_count > 0)
3279             non_default_args_count += num_packed;
3280         }
3281       else
3282         {
3283           TREE_VEC_ELT (result_args, out_arg) = arg;
3284           ++out_arg;
3285         }
3286     }
3287   if (non_default_args_count >= 0)
3288     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3289   return result_args;
3290 }
3291
3292 /* Checks if DECL shadows a template parameter.
3293
3294    [temp.local]: A template-parameter shall not be redeclared within its
3295    scope (including nested scopes).
3296
3297    Emits an error and returns TRUE if the DECL shadows a parameter,
3298    returns FALSE otherwise.  */
3299
3300 bool
3301 check_template_shadow (tree decl)
3302 {
3303   tree olddecl;
3304
3305   /* If we're not in a template, we can't possibly shadow a template
3306      parameter.  */
3307   if (!current_template_parms)
3308     return true;
3309
3310   /* Figure out what we're shadowing.  */
3311   if (TREE_CODE (decl) == OVERLOAD)
3312     decl = OVL_CURRENT (decl);
3313   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3314
3315   /* If there's no previous binding for this name, we're not shadowing
3316      anything, let alone a template parameter.  */
3317   if (!olddecl)
3318     return true;
3319
3320   /* If we're not shadowing a template parameter, we're done.  Note
3321      that OLDDECL might be an OVERLOAD (or perhaps even an
3322      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3323      node.  */
3324   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3325     return true;
3326
3327   /* We check for decl != olddecl to avoid bogus errors for using a
3328      name inside a class.  We check TPFI to avoid duplicate errors for
3329      inline member templates.  */
3330   if (decl == olddecl
3331       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3332     return true;
3333
3334   error ("declaration of %q+#D", decl);
3335   error (" shadows template parm %q+#D", olddecl);
3336   return false;
3337 }
3338
3339 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3340    ORIG_LEVEL, DECL, and TYPE.  */
3341
3342 static tree
3343 build_template_parm_index (int index,
3344                            int level,
3345                            int orig_level,
3346                            tree decl,
3347                            tree type)
3348 {
3349   tree t = make_node (TEMPLATE_PARM_INDEX);
3350   TEMPLATE_PARM_IDX (t) = index;
3351   TEMPLATE_PARM_LEVEL (t) = level;
3352   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3353   TEMPLATE_PARM_DECL (t) = decl;
3354   TREE_TYPE (t) = type;
3355   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3356   TREE_READONLY (t) = TREE_READONLY (decl);
3357
3358   return t;
3359 }
3360
3361 /* Find the canonical type parameter for the given template type
3362    parameter.  Returns the canonical type parameter, which may be TYPE
3363    if no such parameter existed.  */
3364 static tree
3365 canonical_type_parameter (tree type)
3366 {
3367   tree list;
3368   int idx = TEMPLATE_TYPE_IDX (type);
3369   if (!canonical_template_parms)
3370     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3371
3372   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3373     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3374
3375   list = VEC_index (tree, canonical_template_parms, idx);
3376   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3377     list = TREE_CHAIN (list);
3378
3379   if (list)
3380     return TREE_VALUE (list);
3381   else
3382     {
3383       VEC_replace(tree, canonical_template_parms, idx,
3384                   tree_cons (NULL_TREE, type, 
3385                              VEC_index (tree, canonical_template_parms, idx)));
3386       return type;
3387     }
3388 }
3389
3390 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3391    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3392    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3393    new one is created.  */
3394
3395 static tree
3396 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3397                             tsubst_flags_t complain)
3398 {
3399   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3400       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3401           != TEMPLATE_PARM_LEVEL (index) - levels)
3402       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3403     {
3404       tree orig_decl = TEMPLATE_PARM_DECL (index);
3405       tree decl, t;
3406
3407       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3408                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3409       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3410       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3411       DECL_ARTIFICIAL (decl) = 1;
3412       SET_DECL_TEMPLATE_PARM_P (decl);
3413
3414       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3415                                      TEMPLATE_PARM_LEVEL (index) - levels,
3416                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3417                                      decl, type);
3418       TEMPLATE_PARM_DESCENDANTS (index) = t;
3419       TEMPLATE_PARM_PARAMETER_PACK (t) 
3420         = TEMPLATE_PARM_PARAMETER_PACK (index);
3421
3422         /* Template template parameters need this.  */
3423       if (TREE_CODE (decl) == TEMPLATE_DECL)
3424         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3425           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3426            args, complain);
3427     }
3428
3429   return TEMPLATE_PARM_DESCENDANTS (index);
3430 }
3431
3432 /* Process information from new template parameter PARM and append it to the
3433    LIST being built.  This new parameter is a non-type parameter iff
3434    IS_NON_TYPE is true. This new parameter is a parameter
3435    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3436    PARM_LOC.  */
3437
3438 tree
3439 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3440                        bool is_parameter_pack)
3441 {
3442   tree decl = 0;
3443   tree defval;
3444   tree err_parm_list;
3445   int idx = 0;
3446
3447   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3448   defval = TREE_PURPOSE (parm);
3449
3450   if (list)
3451     {
3452       tree p = tree_last (list);
3453
3454       if (p && TREE_VALUE (p) != error_mark_node)
3455         {
3456           p = TREE_VALUE (p);
3457           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3458             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3459           else
3460             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3461         }
3462
3463       ++idx;
3464     }
3465   else
3466     idx = 0;
3467
3468   if (is_non_type)
3469     {
3470       parm = TREE_VALUE (parm);
3471
3472       SET_DECL_TEMPLATE_PARM_P (parm);
3473
3474       if (TREE_TYPE (parm) == error_mark_node)
3475         {
3476           err_parm_list = build_tree_list (defval, parm);
3477           TREE_VALUE (err_parm_list) = error_mark_node;
3478            return chainon (list, err_parm_list);
3479         }
3480       else
3481       {
3482         /* [temp.param]
3483
3484            The top-level cv-qualifiers on the template-parameter are
3485            ignored when determining its type.  */
3486         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3487         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3488           {
3489             err_parm_list = build_tree_list (defval, parm);
3490             TREE_VALUE (err_parm_list) = error_mark_node;
3491              return chainon (list, err_parm_list);
3492           }
3493
3494         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3495           {
3496             /* This template parameter is not a parameter pack, but it
3497                should be. Complain about "bare" parameter packs.  */
3498             check_for_bare_parameter_packs (TREE_TYPE (parm));
3499             
3500             /* Recover by calling this a parameter pack.  */
3501             is_parameter_pack = true;
3502           }
3503       }
3504
3505       /* A template parameter is not modifiable.  */
3506       TREE_CONSTANT (parm) = 1;
3507       TREE_READONLY (parm) = 1;
3508       decl = build_decl (parm_loc,
3509                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3510       TREE_CONSTANT (decl) = 1;
3511       TREE_READONLY (decl) = 1;
3512       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3513         = build_template_parm_index (idx, processing_template_decl,
3514                                      processing_template_decl,
3515                                      decl, TREE_TYPE (parm));
3516
3517       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3518         = is_parameter_pack;
3519     }
3520   else
3521     {
3522       tree t;
3523       parm = TREE_VALUE (TREE_VALUE (parm));
3524
3525       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3526         {
3527           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3528           /* This is for distinguishing between real templates and template
3529              template parameters */
3530           TREE_TYPE (parm) = t;
3531           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3532           decl = parm;
3533         }
3534       else
3535         {
3536           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3537           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3538           decl = build_decl (parm_loc,
3539                              TYPE_DECL, parm, t);
3540         }
3541
3542       TYPE_NAME (t) = decl;
3543       TYPE_STUB_DECL (t) = decl;
3544       parm = decl;
3545       TEMPLATE_TYPE_PARM_INDEX (t)
3546         = build_template_parm_index (idx, processing_template_decl,
3547                                      processing_template_decl,
3548                                      decl, TREE_TYPE (parm));
3549       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3550       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3551     }
3552   DECL_ARTIFICIAL (decl) = 1;
3553   SET_DECL_TEMPLATE_PARM_P (decl);
3554   pushdecl (decl);
3555   parm = build_tree_list (defval, parm);
3556   return chainon (list, parm);
3557 }
3558
3559 /* The end of a template parameter list has been reached.  Process the
3560    tree list into a parameter vector, converting each parameter into a more
3561    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3562    as PARM_DECLs.  */
3563
3564 tree
3565 end_template_parm_list (tree parms)
3566 {
3567   int nparms;
3568   tree parm, next;
3569   tree saved_parmlist = make_tree_vec (list_length (parms));
3570
3571   current_template_parms
3572     = tree_cons (size_int (processing_template_decl),
3573                  saved_parmlist, current_template_parms);
3574
3575   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3576     {
3577       next = TREE_CHAIN (parm);
3578       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3579       TREE_CHAIN (parm) = NULL_TREE;
3580       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3581         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3582               current_template_parms;
3583     }
3584
3585   --processing_template_parmlist;
3586
3587   return saved_parmlist;
3588 }
3589
3590 /* end_template_decl is called after a template declaration is seen.  */
3591
3592 void
3593 end_template_decl (void)
3594 {
3595   reset_specialization ();
3596
3597   if (! processing_template_decl)
3598     return;
3599
3600   /* This matches the pushlevel in begin_template_parm_list.  */
3601   finish_scope ();
3602
3603   --processing_template_decl;
3604   current_template_parms = TREE_CHAIN (current_template_parms);
3605 }
3606
3607 /* Within the declaration of a template, return all levels of template
3608    parameters that apply.  The template parameters are represented as
3609    a TREE_VEC, in the form documented in cp-tree.h for template
3610    arguments.  */
3611
3612 static tree
3613 current_template_args (void)
3614 {
3615   tree header;
3616   tree args = NULL_TREE;
3617   int length = TMPL_PARMS_DEPTH (current_template_parms);
3618   int l = length;
3619
3620   /* If there is only one level of template parameters, we do not
3621      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3622      TREE_VEC containing the arguments.  */
3623   if (length > 1)
3624     args = make_tree_vec (length);
3625
3626   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3627     {
3628       tree a = copy_node (TREE_VALUE (header));
3629       int i;
3630
3631       TREE_TYPE (a) = NULL_TREE;
3632       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3633         {
3634           tree t = TREE_VEC_ELT (a, i);
3635
3636           /* T will be a list if we are called from within a
3637              begin/end_template_parm_list pair, but a vector directly
3638              if within a begin/end_member_template_processing pair.  */
3639           if (TREE_CODE (t) == TREE_LIST)
3640             {
3641               t = TREE_VALUE (t);
3642
3643               if (!error_operand_p (t))
3644                 {
3645                   if (TREE_CODE (t) == TYPE_DECL
3646                       || TREE_CODE (t) == TEMPLATE_DECL)
3647                     {
3648                       t = TREE_TYPE (t);
3649                       
3650                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3651                         {
3652                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3653                              with a single element, which expands T.  */
3654                           tree vec = make_tree_vec (1);
3655 #ifdef ENABLE_CHECKING
3656                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3657                                 (vec, TREE_VEC_LENGTH (vec));
3658 #endif
3659                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3660                           
3661                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3662                           SET_ARGUMENT_PACK_ARGS (t, vec);
3663                         }
3664                     }
3665                   else
3666                     {
3667                       t = DECL_INITIAL (t);
3668                       
3669                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3670                         {
3671                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3672                              with a single element, which expands T.  */
3673                           tree vec = make_tree_vec (1);
3674                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3675 #ifdef ENABLE_CHECKING
3676                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3677                                 (vec, TREE_VEC_LENGTH (vec));
3678 #endif
3679                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3680                           
3681                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3682                           SET_ARGUMENT_PACK_ARGS (t, vec);
3683                           TREE_TYPE (t) = type;
3684                         }
3685                     }
3686                   TREE_VEC_ELT (a, i) = t;
3687                 }
3688             }
3689         }
3690
3691 #ifdef ENABLE_CHECKING
3692       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3693 #endif
3694
3695       if (length > 1)
3696         TREE_VEC_ELT (args, --l) = a;
3697       else
3698         args = a;
3699     }
3700
3701   return args;
3702 }
3703
3704 /* Update the declared TYPE by doing any lookups which were thought to be
3705    dependent, but are not now that we know the SCOPE of the declarator.  */
3706
3707 tree
3708 maybe_update_decl_type (tree orig_type, tree scope)
3709 {
3710   tree type = orig_type;
3711
3712   if (type == NULL_TREE)
3713     return type;
3714
3715   if (TREE_CODE (orig_type) == TYPE_DECL)
3716     type = TREE_TYPE (type);
3717
3718   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3719       && dependent_type_p (type)
3720       /* Don't bother building up the args in this case.  */
3721       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3722     {
3723       /* tsubst in the args corresponding to the template parameters,
3724          including auto if present.  Most things will be unchanged, but
3725          make_typename_type and tsubst_qualified_id will resolve
3726          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3727       tree args = current_template_args ();
3728       tree auto_node = type_uses_auto (type);
3729       tree pushed;
3730       if (auto_node)
3731         {
3732           tree auto_vec = make_tree_vec (1);
3733           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3734           args = add_to_template_args (args, auto_vec);
3735         }
3736       pushed = push_scope (scope);
3737       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3738       if (pushed)
3739         pop_scope (scope);
3740     }
3741
3742   if (type == error_mark_node)
3743     return orig_type;
3744
3745   if (TREE_CODE (orig_type) == TYPE_DECL)
3746     {
3747       if (same_type_p (type, TREE_TYPE (orig_type)))
3748         type = orig_type;
3749       else
3750         type = TYPE_NAME (type);
3751     }
3752   return type;
3753 }
3754
3755 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3756    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3757    a member template.  Used by push_template_decl below.  */
3758
3759 static tree
3760 build_template_decl (tree decl, tree parms, bool member_template_p)
3761 {
3762   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3763   DECL_TEMPLATE_PARMS (tmpl) = parms;
3764   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3765   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3766
3767   return tmpl;
3768 }
3769
3770 struct template_parm_data
3771 {
3772   /* The level of the template parameters we are currently
3773      processing.  */
3774   int level;
3775
3776   /* The index of the specialization argument we are currently
3777      processing.  */
3778   int current_arg;
3779
3780   /* An array whose size is the number of template parameters.  The
3781      elements are nonzero if the parameter has been used in any one
3782      of the arguments processed so far.  */
3783   int* parms;
3784
3785   /* An array whose size is the number of template arguments.  The
3786      elements are nonzero if the argument makes use of template
3787      parameters of this level.  */
3788   int* arg_uses_template_parms;
3789 };
3790
3791 /* Subroutine of push_template_decl used to see if each template
3792    parameter in a partial specialization is used in the explicit
3793    argument list.  If T is of the LEVEL given in DATA (which is
3794    treated as a template_parm_data*), then DATA->PARMS is marked
3795    appropriately.  */
3796
3797 static int
3798 mark_template_parm (tree t, void* data)
3799 {
3800   int level;
3801   int idx;
3802   struct template_parm_data* tpd = (struct template_parm_data*) data;
3803
3804   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3805     {
3806       level = TEMPLATE_PARM_LEVEL (t);
3807       idx = TEMPLATE_PARM_IDX (t);
3808     }
3809   else
3810     {
3811       level = TEMPLATE_TYPE_LEVEL (t);
3812       idx = TEMPLATE_TYPE_IDX (t);
3813     }
3814
3815   if (level == tpd->level)
3816     {
3817       tpd->parms[idx] = 1;
3818       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3819     }
3820
3821   /* Return zero so that for_each_template_parm will continue the
3822      traversal of the tree; we want to mark *every* template parm.  */
3823   return 0;
3824 }
3825
3826 /* Process the partial specialization DECL.  */
3827
3828 static tree
3829 process_partial_specialization (tree decl)
3830 {
3831   tree type = TREE_TYPE (decl);
3832   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3833   tree specargs = CLASSTYPE_TI_ARGS (type);
3834   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3835   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3836   tree inner_parms;
3837   int nargs = TREE_VEC_LENGTH (inner_args);
3838   int ntparms;
3839   int  i;
3840   bool did_error_intro = false;
3841   struct template_parm_data tpd;
3842   struct template_parm_data tpd2;
3843
3844   gcc_assert (current_template_parms);
3845
3846   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3847   ntparms = TREE_VEC_LENGTH (inner_parms);
3848
3849   /* We check that each of the template parameters given in the
3850      partial specialization is used in the argument list to the
3851      specialization.  For example:
3852
3853        template <class T> struct S;
3854        template <class T> struct S<T*>;
3855
3856      The second declaration is OK because `T*' uses the template
3857      parameter T, whereas
3858
3859        template <class T> struct S<int>;
3860
3861      is no good.  Even trickier is:
3862
3863        template <class T>
3864        struct S1
3865        {
3866           template <class U>
3867           struct S2;
3868           template <class U>
3869           struct S2<T>;
3870        };
3871
3872      The S2<T> declaration is actually invalid; it is a
3873      full-specialization.  Of course,
3874
3875           template <class U>
3876           struct S2<T (*)(U)>;
3877
3878      or some such would have been OK.  */
3879   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3880   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3881   memset (tpd.parms, 0, sizeof (int) * ntparms);
3882
3883   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3884   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3885   for (i = 0; i < nargs; ++i)
3886     {
3887       tpd.current_arg = i;
3888       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3889                               &mark_template_parm,
3890                               &tpd,
3891                               NULL,
3892                               /*include_nondeduced_p=*/false);
3893     }
3894   for (i = 0; i < ntparms; ++i)
3895     if (tpd.parms[i] == 0)
3896       {
3897         /* One of the template parms was not used in the
3898            specialization.  */
3899         if (!did_error_intro)
3900           {
3901             error ("template parameters not used in partial specialization:");
3902             did_error_intro = true;
3903           }
3904
3905         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3906       }
3907
3908   if (did_error_intro)
3909     return error_mark_node;
3910
3911   /* [temp.class.spec]
3912
3913      The argument list of the specialization shall not be identical to
3914      the implicit argument list of the primary template.  */
3915   if (comp_template_args
3916       (inner_args,
3917        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3918                                                    (maintmpl)))))
3919     error ("partial specialization %qT does not specialize any template arguments", type);
3920
3921   /* [temp.class.spec]
3922
3923      A partially specialized non-type argument expression shall not
3924      involve template parameters of the partial specialization except
3925      when the argument expression is a simple identifier.
3926
3927      The type of a template parameter corresponding to a specialized
3928      non-type argument shall not be dependent on a parameter of the
3929      specialization. 
3930
3931      Also, we verify that pack expansions only occur at the
3932      end of the argument list.  */
3933   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3934   tpd2.parms = 0;
3935   for (i = 0; i < nargs; ++i)
3936     {
3937       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3938       tree arg = TREE_VEC_ELT (inner_args, i);
3939       tree packed_args = NULL_TREE;
3940       int j, len = 1;
3941
3942       if (ARGUMENT_PACK_P (arg))
3943         {
3944           /* Extract the arguments from the argument pack. We'll be
3945              iterating over these in the following loop.  */
3946           packed_args = ARGUMENT_PACK_ARGS (arg);
3947           len = TREE_VEC_LENGTH (packed_args);
3948         }
3949
3950       for (j = 0; j < len; j++)
3951         {
3952           if (packed_args)
3953             /* Get the Jth argument in the parameter pack.  */
3954             arg = TREE_VEC_ELT (packed_args, j);
3955
3956           if (PACK_EXPANSION_P (arg))
3957             {
3958               /* Pack expansions must come at the end of the
3959                  argument list.  */
3960               if ((packed_args && j < len - 1)
3961                   || (!packed_args && i < nargs - 1))
3962                 {
3963                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3964                     error ("parameter pack argument %qE must be at the "
3965                            "end of the template argument list", arg);
3966                   else
3967                     error ("parameter pack argument %qT must be at the "
3968                            "end of the template argument list", arg);
3969                 }
3970             }
3971
3972           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3973             /* We only care about the pattern.  */
3974             arg = PACK_EXPANSION_PATTERN (arg);
3975
3976           if (/* These first two lines are the `non-type' bit.  */
3977               !TYPE_P (arg)
3978               && TREE_CODE (arg) != TEMPLATE_DECL
3979               /* This next line is the `argument expression is not just a
3980                  simple identifier' condition and also the `specialized
3981                  non-type argument' bit.  */
3982               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3983             {
3984               if ((!packed_args && tpd.arg_uses_template_parms[i])
3985                   || (packed_args && uses_template_parms (arg)))
3986                 error ("template argument %qE involves template parameter(s)",
3987                        arg);
3988               else 
3989                 {
3990                   /* Look at the corresponding template parameter,
3991                      marking which template parameters its type depends
3992                      upon.  */
3993                   tree type = TREE_TYPE (parm);
3994
3995                   if (!tpd2.parms)
3996                     {
3997                       /* We haven't yet initialized TPD2.  Do so now.  */
3998                       tpd2.arg_uses_template_parms 
3999                         = (int *) alloca (sizeof (int) * nargs);
4000                       /* The number of parameters here is the number in the
4001                          main template, which, as checked in the assertion
4002                          above, is NARGS.  */
4003                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
4004                       tpd2.level = 
4005                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4006                     }
4007
4008                   /* Mark the template parameters.  But this time, we're
4009                      looking for the template parameters of the main
4010                      template, not in the specialization.  */
4011                   tpd2.current_arg = i;
4012                   tpd2.arg_uses_template_parms[i] = 0;
4013                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4014                   for_each_template_parm (type,
4015                                           &mark_template_parm,
4016                                           &tpd2,
4017                                           NULL,
4018                                           /*include_nondeduced_p=*/false);
4019
4020                   if (tpd2.arg_uses_template_parms [i])
4021                     {
4022                       /* The type depended on some template parameters.
4023                          If they are fully specialized in the
4024                          specialization, that's OK.  */
4025                       int j;
4026                       int count = 0;
4027                       for (j = 0; j < nargs; ++j)
4028                         if (tpd2.parms[j] != 0
4029                             && tpd.arg_uses_template_parms [j])
4030                           ++count;
4031                       if (count != 0)
4032                         error_n (input_location, count,
4033                                  "type %qT of template argument %qE depends "
4034                                  "on a template parameter",
4035                                  "type %qT of template argument %qE depends "
4036                                  "on template parameters",
4037                                  type,
4038                                  arg);
4039                     }
4040                 }
4041             }
4042         }
4043     }
4044
4045   /* We should only get here once.  */
4046   gcc_assert (!COMPLETE_TYPE_P (type));
4047
4048   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4049     = tree_cons (specargs, inner_parms,
4050                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4051   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4052   return decl;
4053 }
4054
4055 /* Check that a template declaration's use of default arguments and
4056    parameter packs is not invalid.  Here, PARMS are the template
4057    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4058    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4059    specialization.
4060    
4061
4062    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4063    declaration (but not a definition); 1 indicates a declaration, 2
4064    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4065    emitted for extraneous default arguments.
4066
4067    Returns TRUE if there were no errors found, FALSE otherwise. */
4068
4069 bool
4070 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4071                          int is_partial, int is_friend_decl)
4072 {
4073   const char *msg;
4074   int last_level_to_check;
4075   tree parm_level;
4076   bool no_errors = true;
4077
4078   /* [temp.param]
4079
4080      A default template-argument shall not be specified in a
4081      function template declaration or a function template definition, nor
4082      in the template-parameter-list of the definition of a member of a
4083      class template.  */
4084
4085   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4086     /* You can't have a function template declaration in a local
4087        scope, nor you can you define a member of a class template in a
4088        local scope.  */
4089     return true;
4090
4091   if (current_class_type
4092       && !TYPE_BEING_DEFINED (current_class_type)
4093       && DECL_LANG_SPECIFIC (decl)
4094       && DECL_DECLARES_FUNCTION_P (decl)
4095       /* If this is either a friend defined in the scope of the class
4096          or a member function.  */
4097       && (DECL_FUNCTION_MEMBER_P (decl)
4098           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4099           : DECL_FRIEND_CONTEXT (decl)
4100           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4101           : false)
4102       /* And, if it was a member function, it really was defined in
4103          the scope of the class.  */
4104       && (!DECL_FUNCTION_MEMBER_P (decl)
4105           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4106     /* We already checked these parameters when the template was
4107        declared, so there's no need to do it again now.  This function
4108        was defined in class scope, but we're processing it's body now
4109        that the class is complete.  */
4110     return true;
4111
4112   /* Core issue 226 (C++0x only): the following only applies to class
4113      templates.  */
4114   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4115     {
4116       /* [temp.param]
4117
4118          If a template-parameter has a default template-argument, all
4119          subsequent template-parameters shall have a default
4120          template-argument supplied.  */
4121       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4122         {
4123           tree inner_parms = TREE_VALUE (parm_level);
4124           int ntparms = TREE_VEC_LENGTH (inner_parms);
4125           int seen_def_arg_p = 0;
4126           int i;
4127
4128           for (i = 0; i < ntparms; ++i)
4129             {
4130               tree parm = TREE_VEC_ELT (inner_parms, i);
4131
4132               if (parm == error_mark_node)
4133                 continue;
4134
4135               if (TREE_PURPOSE (parm))
4136                 seen_def_arg_p = 1;
4137               else if (seen_def_arg_p
4138                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4139                 {
4140                   error ("no default argument for %qD", TREE_VALUE (parm));
4141                   /* For better subsequent error-recovery, we indicate that
4142                      there should have been a default argument.  */
4143                   TREE_PURPOSE (parm) = error_mark_node;
4144                   no_errors = false;
4145                 }
4146               else if (is_primary
4147                        && !is_partial
4148                        && !is_friend_decl
4149                        /* Don't complain about an enclosing partial
4150                           specialization.  */
4151                        && parm_level == parms
4152                        && TREE_CODE (decl) == TYPE_DECL
4153                        && i < ntparms - 1
4154                        && template_parameter_pack_p (TREE_VALUE (parm)))
4155                 {
4156                   /* A primary class template can only have one
4157                      parameter pack, at the end of the template
4158                      parameter list.  */
4159
4160                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4161                     error ("parameter pack %qE must be at the end of the"
4162                            " template parameter list", TREE_VALUE (parm));
4163                   else
4164                     error ("parameter pack %qT must be at the end of the"
4165                            " template parameter list", 
4166                            TREE_TYPE (TREE_VALUE (parm)));
4167
4168                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4169                     = error_mark_node;
4170                   no_errors = false;
4171                 }
4172             }
4173         }
4174     }
4175
4176   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4177       || is_partial 
4178       || !is_primary
4179       || is_friend_decl)
4180     /* For an ordinary class template, default template arguments are
4181        allowed at the innermost level, e.g.:
4182          template <class T = int>
4183          struct S {};
4184        but, in a partial specialization, they're not allowed even
4185        there, as we have in [temp.class.spec]:
4186
4187          The template parameter list of a specialization shall not
4188          contain default template argument values.
4189
4190        So, for a partial specialization, or for a function template
4191        (in C++98/C++03), we look at all of them.  */
4192     ;
4193   else
4194     /* But, for a primary class template that is not a partial
4195        specialization we look at all template parameters except the
4196        innermost ones.  */
4197     parms = TREE_CHAIN (parms);
4198
4199   /* Figure out what error message to issue.  */
4200   if (is_friend_decl == 2)
4201     msg = G_("default template arguments may not be used in function template "
4202              "friend re-declaration");
4203   else if (is_friend_decl)
4204     msg = G_("default template arguments may not be used in function template "
4205              "friend declarations");
4206   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4207     msg = G_("default template arguments may not be used in function templates "
4208              "without -std=c++0x or -std=gnu++0x");
4209   else if (is_partial)
4210     msg = G_("default template arguments may not be used in "
4211              "partial specializations");
4212   else
4213     msg = G_("default argument for template parameter for class enclosing %qD");
4214
4215   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4216     /* If we're inside a class definition, there's no need to
4217        examine the parameters to the class itself.  On the one
4218        hand, they will be checked when the class is defined, and,
4219        on the other, default arguments are valid in things like:
4220          template <class T = double>
4221          struct S { template <class U> void f(U); };
4222        Here the default argument for `S' has no bearing on the
4223        declaration of `f'.  */
4224     last_level_to_check = template_class_depth (current_class_type) + 1;
4225   else
4226     /* Check everything.  */
4227     last_level_to_check = 0;
4228
4229   for (parm_level = parms;
4230        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4231        parm_level = TREE_CHAIN (parm_level))
4232     {
4233       tree inner_parms = TREE_VALUE (parm_level);
4234       int i;
4235       int ntparms;
4236
4237       ntparms = TREE_VEC_LENGTH (inner_parms);
4238       for (i = 0; i < ntparms; ++i)
4239         {
4240           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4241             continue;
4242
4243           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4244             {
4245               if (msg)
4246                 {
4247                   no_errors = false;
4248                   if (is_friend_decl == 2)
4249                     return no_errors;
4250
4251                   error (msg, decl);
4252                   msg = 0;
4253                 }
4254
4255               /* Clear out the default argument so that we are not
4256                  confused later.  */
4257               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4258             }
4259         }
4260
4261       /* At this point, if we're still interested in issuing messages,
4262          they must apply to classes surrounding the object declared.  */
4263       if (msg)
4264         msg = G_("default argument for template parameter for class "
4265                  "enclosing %qD");
4266     }
4267
4268   return no_errors;
4269 }
4270
4271 /* Worker for push_template_decl_real, called via
4272    for_each_template_parm.  DATA is really an int, indicating the
4273    level of the parameters we are interested in.  If T is a template
4274    parameter of that level, return nonzero.  */
4275
4276 static int
4277 template_parm_this_level_p (tree t, void* data)
4278 {
4279   int this_level = *(int *)data;
4280   int level;
4281
4282   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4283     level = TEMPLATE_PARM_LEVEL (t);
4284   else
4285     level = TEMPLATE_TYPE_LEVEL (t);
4286   return level == this_level;
4287 }
4288
4289 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4290    parameters given by current_template_args, or reuses a
4291    previously existing one, if appropriate.  Returns the DECL, or an
4292    equivalent one, if it is replaced via a call to duplicate_decls.
4293
4294    If IS_FRIEND is true, DECL is a friend declaration.  */
4295
4296 tree
4297 push_template_decl_real (tree decl, bool is_friend)
4298 {
4299   tree tmpl;
4300   tree args;
4301   tree info;
4302   tree ctx;
4303   int primary;
4304   int is_partial;
4305   int new_template_p = 0;
4306   /* True if the template is a member template, in the sense of
4307      [temp.mem].  */
4308   bool member_template_p = false;
4309
4310   if (decl == error_mark_node || !current_template_parms)
4311     return error_mark_node;
4312
4313   /* See if this is a partial specialization.  */
4314   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4315                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4316                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4317
4318   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4319     is_friend = true;
4320
4321   if (is_friend)
4322     /* For a friend, we want the context of the friend function, not
4323        the type of which it is a friend.  */
4324     ctx = DECL_CONTEXT (decl);
4325   else if (CP_DECL_CONTEXT (decl)
4326            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4327     /* In the case of a virtual function, we want the class in which
4328        it is defined.  */
4329     ctx = CP_DECL_CONTEXT (decl);
4330   else
4331     /* Otherwise, if we're currently defining some class, the DECL
4332        is assumed to be a member of the class.  */
4333     ctx = current_scope ();
4334
4335   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4336     ctx = NULL_TREE;
4337
4338   if (!DECL_CONTEXT (decl))
4339     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4340
4341   /* See if this is a primary template.  */
4342   if (is_friend && ctx)
4343     /* A friend template that specifies a class context, i.e.
4344          template <typename T> friend void A<T>::f();
4345        is not primary.  */
4346     primary = 0;
4347   else
4348     primary = template_parm_scope_p ();
4349
4350   if (primary)
4351     {
4352       if (DECL_CLASS_SCOPE_P (decl))
4353         member_template_p = true;
4354       if (TREE_CODE (decl) == TYPE_DECL
4355           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4356         {
4357           error ("template class without a name");
4358           return error_mark_node;
4359         }
4360       else if (TREE_CODE (decl) == FUNCTION_DECL)
4361         {
4362           if (DECL_DESTRUCTOR_P (decl))
4363             {
4364               /* [temp.mem]
4365
4366                  A destructor shall not be a member template.  */
4367               error ("destructor %qD declared as member template", decl);
4368               return error_mark_node;
4369             }
4370           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4371               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4372                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4373                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4374                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4375                       == void_list_node)))
4376             {
4377               /* [basic.stc.dynamic.allocation]
4378
4379                  An allocation function can be a function
4380                  template. ... Template allocation functions shall
4381                  have two or more parameters.  */
4382               error ("invalid template declaration of %qD", decl);
4383               return error_mark_node;
4384             }
4385         }
4386       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4387                && CLASS_TYPE_P (TREE_TYPE (decl)))
4388         /* OK */;
4389       else
4390         {
4391           error ("template declaration of %q#D", decl);
4392           return error_mark_node;
4393         }
4394     }
4395
4396   /* Check to see that the rules regarding the use of default
4397      arguments are not being violated.  */
4398   check_default_tmpl_args (decl, current_template_parms,
4399                            primary, is_partial, /*is_friend_decl=*/0);
4400
4401   /* Ensure that there are no parameter packs in the type of this
4402      declaration that have not been expanded.  */
4403   if (TREE_CODE (decl) == FUNCTION_DECL)
4404     {
4405       /* Check each of the arguments individually to see if there are
4406          any bare parameter packs.  */
4407       tree type = TREE_TYPE (decl);
4408       tree arg = DECL_ARGUMENTS (decl);
4409       tree argtype = TYPE_ARG_TYPES (type);
4410
4411       while (arg && argtype)
4412         {
4413           if (!FUNCTION_PARAMETER_PACK_P (arg)
4414               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4415             {
4416             /* This is a PARM_DECL that contains unexpanded parameter
4417                packs. We have already complained about this in the
4418                check_for_bare_parameter_packs call, so just replace
4419                these types with ERROR_MARK_NODE.  */
4420               TREE_TYPE (arg) = error_mark_node;
4421               TREE_VALUE (argtype) = error_mark_node;
4422             }
4423
4424           arg = TREE_CHAIN (arg);
4425           argtype = TREE_CHAIN (argtype);
4426         }
4427
4428       /* Check for bare parameter packs in the return type and the
4429          exception specifiers.  */
4430       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4431         /* Errors were already issued, set return type to int
4432            as the frontend doesn't expect error_mark_node as
4433            the return type.  */
4434         TREE_TYPE (type) = integer_type_node;
4435       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4436         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4437     }
4438   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4439     {
4440       TREE_TYPE (decl) = error_mark_node;
4441       return error_mark_node;
4442     }
4443
4444   if (is_partial)
4445     return process_partial_specialization (decl);
4446
4447   args = current_template_args ();
4448
4449   if (!ctx
4450       || TREE_CODE (ctx) == FUNCTION_DECL
4451       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4452       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4453     {
4454       if (DECL_LANG_SPECIFIC (decl)
4455           && DECL_TEMPLATE_INFO (decl)
4456           && DECL_TI_TEMPLATE (decl))
4457         tmpl = DECL_TI_TEMPLATE (decl);
4458       /* If DECL is a TYPE_DECL for a class-template, then there won't
4459          be DECL_LANG_SPECIFIC.  The information equivalent to
4460          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4461       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4462                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4463                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4464         {
4465           /* Since a template declaration already existed for this
4466              class-type, we must be redeclaring it here.  Make sure
4467              that the redeclaration is valid.  */
4468           redeclare_class_template (TREE_TYPE (decl),
4469                                     current_template_parms);
4470           /* We don't need to create a new TEMPLATE_DECL; just use the
4471              one we already had.  */
4472           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4473         }
4474       else
4475         {
4476           tmpl = build_template_decl (decl, current_template_parms,
4477                                       member_template_p);
4478           new_template_p = 1;
4479
4480           if (DECL_LANG_SPECIFIC (decl)
4481               && DECL_TEMPLATE_SPECIALIZATION (decl))
4482             {
4483               /* A specialization of a member template of a template
4484                  class.  */
4485               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4486               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4487               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4488             }
4489         }
4490     }
4491   else
4492     {
4493       tree a, t, current, parms;
4494       int i;
4495       tree tinfo = get_template_info (decl);
4496
4497       if (!tinfo)
4498         {
4499           error ("template definition of non-template %q#D", decl);
4500           return error_mark_node;
4501         }
4502
4503       tmpl = TI_TEMPLATE (tinfo);
4504
4505       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4506           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4507           && DECL_TEMPLATE_SPECIALIZATION (decl)
4508           && DECL_MEMBER_TEMPLATE_P (tmpl))
4509         {
4510           tree new_tmpl;
4511
4512           /* The declaration is a specialization of a member
4513              template, declared outside the class.  Therefore, the
4514              innermost template arguments will be NULL, so we
4515              replace them with the arguments determined by the
4516              earlier call to check_explicit_specialization.  */
4517           args = DECL_TI_ARGS (decl);
4518
4519           new_tmpl
4520             = build_template_decl (decl, current_template_parms,
4521                                    member_template_p);
4522           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4523           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4524           DECL_TI_TEMPLATE (decl) = new_tmpl;
4525           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4526           DECL_TEMPLATE_INFO (new_tmpl)
4527             = build_template_info (tmpl, args);
4528
4529           register_specialization (new_tmpl,
4530                                    most_general_template (tmpl),
4531                                    args,
4532                                    is_friend, 0);
4533           return decl;
4534         }
4535
4536       /* Make sure the template headers we got make sense.  */
4537
4538       parms = DECL_TEMPLATE_PARMS (tmpl);
4539       i = TMPL_PARMS_DEPTH (parms);
4540       if (TMPL_ARGS_DEPTH (args) != i)
4541         {
4542           error ("expected %d levels of template parms for %q#D, got %d",
4543                  i, decl, TMPL_ARGS_DEPTH (args));
4544         }
4545       else
4546         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4547           {
4548             a = TMPL_ARGS_LEVEL (args, i);
4549             t = INNERMOST_TEMPLATE_PARMS (parms);
4550
4551             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4552               {
4553                 if (current == decl)
4554                   error ("got %d template parameters for %q#D",
4555                          TREE_VEC_LENGTH (a), decl);
4556                 else
4557                   error ("got %d template parameters for %q#T",
4558                          TREE_VEC_LENGTH (a), current);
4559                 error ("  but %d required", TREE_VEC_LENGTH (t));
4560                 return error_mark_node;
4561               }
4562
4563             if (current == decl)
4564               current = ctx;
4565             else if (current == NULL_TREE)
4566               /* Can happen in erroneous input.  */
4567               break;
4568             else
4569               current = (TYPE_P (current)
4570                          ? TYPE_CONTEXT (current)
4571                          : DECL_CONTEXT (current));
4572           }
4573
4574       /* Check that the parms are used in the appropriate qualifying scopes
4575          in the declarator.  */
4576       if (!comp_template_args
4577           (TI_ARGS (tinfo),
4578            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4579         {
4580           error ("\
4581 template arguments to %qD do not match original template %qD",
4582                  decl, DECL_TEMPLATE_RESULT (tmpl));
4583           if (!uses_template_parms (TI_ARGS (tinfo)))
4584             inform (input_location, "use template<> for an explicit specialization");
4585           /* Avoid crash in import_export_decl.  */
4586           DECL_INTERFACE_KNOWN (decl) = 1;
4587           return error_mark_node;
4588         }
4589     }
4590
4591   DECL_TEMPLATE_RESULT (tmpl) = decl;
4592   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4593
4594   /* Push template declarations for global functions and types.  Note
4595      that we do not try to push a global template friend declared in a
4596      template class; such a thing may well depend on the template
4597      parameters of the class.  */
4598   if (new_template_p && !ctx
4599       && !(is_friend && template_class_depth (current_class_type) > 0))
4600     {
4601       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4602       if (tmpl == error_mark_node)
4603         return error_mark_node;
4604
4605       /* Hide template friend classes that haven't been declared yet.  */
4606       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4607         {
4608           DECL_ANTICIPATED (tmpl) = 1;
4609           DECL_FRIEND_P (tmpl) = 1;
4610         }
4611     }
4612
4613   if (primary)
4614     {
4615       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4616       int i;
4617
4618       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4619       if (DECL_CONV_FN_P (tmpl))
4620         {
4621           int depth = TMPL_PARMS_DEPTH (parms);
4622
4623           /* It is a conversion operator. See if the type converted to
4624              depends on innermost template operands.  */
4625
4626           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4627                                          depth))
4628             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4629         }
4630
4631       /* Give template template parms a DECL_CONTEXT of the template
4632          for which they are a parameter.  */
4633       parms = INNERMOST_TEMPLATE_PARMS (parms);
4634       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4635         {
4636           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4637           if (TREE_CODE (parm) == TEMPLATE_DECL)
4638             DECL_CONTEXT (parm) = tmpl;
4639         }
4640     }
4641
4642   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4643      back to its most general template.  If TMPL is a specialization,
4644      ARGS may only have the innermost set of arguments.  Add the missing
4645      argument levels if necessary.  */
4646   if (DECL_TEMPLATE_INFO (tmpl))
4647     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4648
4649   info = build_template_info (tmpl, args);
4650
4651   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4652     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4653   else if (DECL_LANG_SPECIFIC (decl))
4654     DECL_TEMPLATE_INFO (decl) = info;
4655
4656   return DECL_TEMPLATE_RESULT (tmpl);
4657 }
4658
4659 tree
4660 push_template_decl (tree decl)
4661 {
4662   return push_template_decl_real (decl, false);
4663 }
4664
4665 /* Called when a class template TYPE is redeclared with the indicated
4666    template PARMS, e.g.:
4667
4668      template <class T> struct S;
4669      template <class T> struct S {};  */
4670
4671 bool
4672 redeclare_class_template (tree type, tree parms)
4673 {
4674   tree tmpl;
4675   tree tmpl_parms;
4676   int i;
4677
4678   if (!TYPE_TEMPLATE_INFO (type))
4679     {
4680       error ("%qT is not a template type", type);
4681       return false;
4682     }
4683
4684   tmpl = TYPE_TI_TEMPLATE (type);
4685   if (!PRIMARY_TEMPLATE_P (tmpl))
4686     /* The type is nested in some template class.  Nothing to worry
4687        about here; there are no new template parameters for the nested
4688        type.  */
4689     return true;
4690
4691   if (!parms)
4692     {
4693       error ("template specifiers not specified in declaration of %qD",
4694              tmpl);
4695       return false;
4696     }
4697
4698   parms = INNERMOST_TEMPLATE_PARMS (parms);
4699   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4700
4701   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4702     {
4703       error_n (input_location, TREE_VEC_LENGTH (parms),
4704                "redeclared with %d template parameter",
4705                "redeclared with %d template parameters",
4706                TREE_VEC_LENGTH (parms));
4707       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4708                 "previous declaration %q+D used %d template parameter",
4709                 "previous declaration %q+D used %d template parameters",
4710                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4711       return false;
4712     }
4713
4714   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4715     {
4716       tree tmpl_parm;
4717       tree parm;
4718       tree tmpl_default;
4719       tree parm_default;
4720
4721       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4722           || TREE_VEC_ELT (parms, i) == error_mark_node)
4723         continue;
4724
4725       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4726       if (tmpl_parm == error_mark_node)
4727         return false;
4728
4729       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4730       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4731       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4732
4733       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4734          TEMPLATE_DECL.  */
4735       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4736           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4737               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4738           || (TREE_CODE (tmpl_parm) != PARM_DECL
4739               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4740                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4741           || (TREE_CODE (tmpl_parm) == PARM_DECL
4742               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4743                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4744         {
4745           error ("template parameter %q+#D", tmpl_parm);
4746           error ("redeclared here as %q#D", parm);
4747           return false;
4748         }
4749
4750       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4751         {
4752           /* We have in [temp.param]:
4753
4754              A template-parameter may not be given default arguments
4755              by two different declarations in the same scope.  */
4756           error_at (input_location, "redefinition of default argument for %q#D", parm);
4757           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4758                   "original definition appeared here");
4759           return false;
4760         }
4761
4762       if (parm_default != NULL_TREE)
4763         /* Update the previous template parameters (which are the ones
4764            that will really count) with the new default value.  */
4765         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4766       else if (tmpl_default != NULL_TREE)
4767         /* Update the new parameters, too; they'll be used as the
4768            parameters for any members.  */
4769         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4770     }
4771
4772     return true;
4773 }
4774
4775 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4776    (possibly simplified) expression.  */
4777
4778 tree
4779 fold_non_dependent_expr (tree expr)
4780 {
4781   if (expr == NULL_TREE)
4782     return NULL_TREE;
4783
4784   /* If we're in a template, but EXPR isn't value dependent, simplify
4785      it.  We're supposed to treat:
4786
4787        template <typename T> void f(T[1 + 1]);
4788        template <typename T> void f(T[2]);
4789
4790      as two declarations of the same function, for example.  */
4791   if (processing_template_decl
4792       && !type_dependent_expression_p (expr)
4793       && !value_dependent_expression_p (expr))
4794     {
4795       HOST_WIDE_INT saved_processing_template_decl;
4796
4797       saved_processing_template_decl = processing_template_decl;
4798       processing_template_decl = 0;
4799       expr = tsubst_copy_and_build (expr,
4800                                     /*args=*/NULL_TREE,
4801                                     tf_error,
4802                                     /*in_decl=*/NULL_TREE,
4803                                     /*function_p=*/false,
4804                                     /*integral_constant_expression_p=*/true);
4805       processing_template_decl = saved_processing_template_decl;
4806     }
4807   return expr;
4808 }
4809
4810 /* EXPR is an expression which is used in a constant-expression context.
4811    For instance, it could be a VAR_DECL with a constant initializer.
4812    Extract the innermost constant expression.
4813
4814    This is basically a more powerful version of
4815    integral_constant_value, which can be used also in templates where
4816    initializers can maintain a syntactic rather than semantic form
4817    (even if they are non-dependent, for access-checking purposes).  */
4818
4819 static tree
4820 fold_decl_constant_value (tree expr)
4821 {
4822   tree const_expr = expr;
4823   do
4824     {
4825       expr = fold_non_dependent_expr (const_expr);
4826       const_expr = integral_constant_value (expr);
4827     }
4828   while (expr != const_expr);
4829
4830   return expr;
4831 }
4832
4833 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4834    must be a function or a pointer-to-function type, as specified
4835    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4836    and check that the resulting function has external linkage.  */
4837
4838 static tree
4839 convert_nontype_argument_function (tree type, tree expr)
4840 {
4841   tree fns = expr;
4842   tree fn, fn_no_ptr;
4843
4844   fn = instantiate_type (type, fns, tf_none);
4845   if (fn == error_mark_node)
4846     return error_mark_node;
4847
4848   fn_no_ptr = fn;
4849   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4850     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4851   if (TREE_CODE (fn_no_ptr) == BASELINK)
4852     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4853  
4854   /* [temp.arg.nontype]/1
4855
4856      A template-argument for a non-type, non-template template-parameter
4857      shall be one of:
4858      [...]
4859      -- the address of an object or function with external linkage.  */
4860   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4861     {
4862       error ("%qE is not a valid template argument for type %qT "
4863              "because function %qD has not external linkage",
4864              expr, type, fn_no_ptr);
4865       return NULL_TREE;
4866     }
4867
4868   return fn;
4869 }
4870
4871 /* Subroutine of convert_nontype_argument.
4872    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4873    Emit an error otherwise.  */
4874
4875 static bool
4876 check_valid_ptrmem_cst_expr (tree type, tree expr)
4877 {
4878   STRIP_NOPS (expr);
4879   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4880     return true;
4881   error ("%qE is not a valid template argument for type %qT",
4882          expr, type);
4883   error ("it must be a pointer-to-member of the form `&X::Y'");
4884   return false;
4885 }
4886
4887 /* Attempt to convert the non-type template parameter EXPR to the
4888    indicated TYPE.  If the conversion is successful, return the
4889    converted value.  If the conversion is unsuccessful, return
4890    NULL_TREE if we issued an error message, or error_mark_node if we
4891    did not.  We issue error messages for out-and-out bad template
4892    parameters, but not simply because the conversion failed, since we
4893    might be just trying to do argument deduction.  Both TYPE and EXPR
4894    must be non-dependent.
4895
4896    The conversion follows the special rules described in
4897    [temp.arg.nontype], and it is much more strict than an implicit
4898    conversion.
4899
4900    This function is called twice for each template argument (see
4901    lookup_template_class for a more accurate description of this
4902    problem). This means that we need to handle expressions which
4903    are not valid in a C++ source, but can be created from the
4904    first call (for instance, casts to perform conversions). These
4905    hacks can go away after we fix the double coercion problem.  */
4906
4907 static tree
4908 convert_nontype_argument (tree type, tree expr)
4909 {
4910   tree expr_type;
4911
4912   /* Detect immediately string literals as invalid non-type argument.
4913      This special-case is not needed for correctness (we would easily
4914      catch this later), but only to provide better diagnostic for this
4915      common user mistake. As suggested by DR 100, we do not mention
4916      linkage issues in the diagnostic as this is not the point.  */
4917   if (TREE_CODE (expr) == STRING_CST)
4918     {
4919       error ("%qE is not a valid template argument for type %qT "
4920              "because string literals can never be used in this context",
4921              expr, type);
4922       return NULL_TREE;
4923     }
4924
4925   /* If we are in a template, EXPR may be non-dependent, but still
4926      have a syntactic, rather than semantic, form.  For example, EXPR
4927      might be a SCOPE_REF, rather than the VAR_DECL to which the
4928      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4929      so that access checking can be performed when the template is
4930      instantiated -- but here we need the resolved form so that we can
4931      convert the argument.  */
4932   expr = fold_non_dependent_expr (expr);
4933   if (error_operand_p (expr))
4934     return error_mark_node;
4935   expr_type = TREE_TYPE (expr);
4936   expr = mark_rvalue_use (expr);
4937
4938   /* HACK: Due to double coercion, we can get a
4939      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4940      which is the tree that we built on the first call (see
4941      below when coercing to reference to object or to reference to
4942      function). We just strip everything and get to the arg.
4943      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4944      for examples.  */
4945   if (TREE_CODE (expr) == NOP_EXPR)
4946     {
4947       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4948         {
4949           /* ??? Maybe we could use convert_from_reference here, but we
4950              would need to relax its constraints because the NOP_EXPR
4951              could actually change the type to something more cv-qualified,
4952              and this is not folded by convert_from_reference.  */
4953           tree addr = TREE_OPERAND (expr, 0);
4954           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4955           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4956           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4957           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4958                       (TREE_TYPE (expr_type),
4959                        TREE_TYPE (TREE_TYPE (addr))));
4960
4961           expr = TREE_OPERAND (addr, 0);
4962           expr_type = TREE_TYPE (expr);
4963         }
4964
4965       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4966          parameter is a pointer to object, through decay and
4967          qualification conversion. Let's strip everything.  */
4968       else if (TYPE_PTROBV_P (type))
4969         {
4970           STRIP_NOPS (expr);
4971           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4972           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4973           /* Skip the ADDR_EXPR only if it is part of the decay for
4974              an array. Otherwise, it is part of the original argument
4975              in the source code.  */
4976           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4977             expr = TREE_OPERAND (expr, 0);
4978           expr_type = TREE_TYPE (expr);
4979         }
4980     }
4981
4982   /* [temp.arg.nontype]/5, bullet 1
4983
4984      For a non-type template-parameter of integral or enumeration type,
4985      integral promotions (_conv.prom_) and integral conversions
4986      (_conv.integral_) are applied.  */
4987   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4988     {
4989       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4990         return error_mark_node;
4991
4992       expr = fold_decl_constant_value (expr);
4993       /* Notice that there are constant expressions like '4 % 0' which
4994          do not fold into integer constants.  */
4995       if (TREE_CODE (expr) != INTEGER_CST)
4996         {
4997           error ("%qE is not a valid template argument for type %qT "
4998                  "because it is a non-constant expression", expr, type);
4999           return NULL_TREE;
5000         }
5001
5002       /* At this point, an implicit conversion does what we want,
5003          because we already know that the expression is of integral
5004          type.  */
5005       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
5006       if (expr == error_mark_node)
5007         return error_mark_node;
5008
5009       /* Conversion was allowed: fold it to a bare integer constant.  */
5010       expr = fold (expr);
5011     }
5012   /* [temp.arg.nontype]/5, bullet 2
5013
5014      For a non-type template-parameter of type pointer to object,
5015      qualification conversions (_conv.qual_) and the array-to-pointer
5016      conversion (_conv.array_) are applied.  */
5017   else if (TYPE_PTROBV_P (type))
5018     {
5019       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5020
5021          A template-argument for a non-type, non-template template-parameter
5022          shall be one of: [...]
5023
5024          -- the name of a non-type template-parameter;
5025          -- the address of an object or function with external linkage, [...]
5026             expressed as "& id-expression" where the & is optional if the name
5027             refers to a function or array, or if the corresponding
5028             template-parameter is a reference.
5029
5030         Here, we do not care about functions, as they are invalid anyway
5031         for a parameter of type pointer-to-object.  */
5032
5033       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5034         /* Non-type template parameters are OK.  */
5035         ;
5036       else if (TREE_CODE (expr) != ADDR_EXPR
5037                && TREE_CODE (expr_type) != ARRAY_TYPE)
5038         {
5039           if (TREE_CODE (expr) == VAR_DECL)
5040             {
5041               error ("%qD is not a valid template argument "
5042                      "because %qD is a variable, not the address of "
5043                      "a variable",
5044                      expr, expr);
5045               return NULL_TREE;
5046             }
5047           /* Other values, like integer constants, might be valid
5048              non-type arguments of some other type.  */
5049           return error_mark_node;
5050         }
5051       else
5052         {
5053           tree decl;
5054
5055           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5056                   ? TREE_OPERAND (expr, 0) : expr);
5057           if (TREE_CODE (decl) != VAR_DECL)
5058             {
5059               error ("%qE is not a valid template argument of type %qT "
5060                      "because %qE is not a variable",
5061                      expr, type, decl);
5062               return NULL_TREE;
5063             }
5064           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5065             {
5066               error ("%qE is not a valid template argument of type %qT "
5067                      "because %qD does not have external linkage",
5068                      expr, type, decl);
5069               return NULL_TREE;
5070             }
5071         }
5072
5073       expr = decay_conversion (expr);
5074       if (expr == error_mark_node)
5075         return error_mark_node;
5076
5077       expr = perform_qualification_conversions (type, expr);
5078       if (expr == error_mark_node)
5079         return error_mark_node;
5080     }
5081   /* [temp.arg.nontype]/5, bullet 3
5082
5083      For a non-type template-parameter of type reference to object, no
5084      conversions apply. The type referred to by the reference may be more
5085      cv-qualified than the (otherwise identical) type of the
5086      template-argument. The template-parameter is bound directly to the
5087      template-argument, which must be an lvalue.  */
5088   else if (TYPE_REF_OBJ_P (type))
5089     {
5090       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5091                                                       expr_type))
5092         return error_mark_node;
5093
5094       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5095         {
5096           error ("%qE is not a valid template argument for type %qT "
5097                  "because of conflicts in cv-qualification", expr, type);
5098           return NULL_TREE;
5099         }
5100
5101       if (!real_lvalue_p (expr))
5102         {
5103           error ("%qE is not a valid template argument for type %qT "
5104                  "because it is not an lvalue", expr, type);
5105           return NULL_TREE;
5106         }
5107
5108       /* [temp.arg.nontype]/1
5109
5110          A template-argument for a non-type, non-template template-parameter
5111          shall be one of: [...]
5112
5113          -- the address of an object or function with external linkage.  */
5114       if (TREE_CODE (expr) == INDIRECT_REF
5115           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5116         {
5117           expr = TREE_OPERAND (expr, 0);
5118           if (DECL_P (expr))
5119             {
5120               error ("%q#D is not a valid template argument for type %qT "
5121                      "because a reference variable does not have a constant "
5122                      "address", expr, type);
5123               return NULL_TREE;
5124             }
5125         }
5126
5127       if (!DECL_P (expr))
5128         {
5129           error ("%qE is not a valid template argument for type %qT "
5130                  "because it is not an object with external linkage",
5131                  expr, type);
5132           return NULL_TREE;
5133         }
5134
5135       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5136         {
5137           error ("%qE is not a valid template argument for type %qT "
5138                  "because object %qD has not external linkage",
5139                  expr, type, expr);
5140           return NULL_TREE;
5141         }
5142
5143       expr = build_nop (type, build_address (expr));
5144     }
5145   /* [temp.arg.nontype]/5, bullet 4
5146
5147      For a non-type template-parameter of type pointer to function, only
5148      the function-to-pointer conversion (_conv.func_) is applied. If the
5149      template-argument represents a set of overloaded functions (or a
5150      pointer to such), the matching function is selected from the set
5151      (_over.over_).  */
5152   else if (TYPE_PTRFN_P (type))
5153     {
5154       /* If the argument is a template-id, we might not have enough
5155          context information to decay the pointer.  */
5156       if (!type_unknown_p (expr_type))
5157         {
5158           expr = decay_conversion (expr);
5159           if (expr == error_mark_node)
5160             return error_mark_node;
5161         }
5162
5163       expr = convert_nontype_argument_function (type, expr);
5164       if (!expr || expr == error_mark_node)
5165         return expr;
5166
5167       if (TREE_CODE (expr) != ADDR_EXPR)
5168         {
5169           error ("%qE is not a valid template argument for type %qT", expr, type);
5170           error ("it must be the address of a function with external linkage");
5171           return NULL_TREE;
5172         }
5173     }
5174   /* [temp.arg.nontype]/5, bullet 5
5175
5176      For a non-type template-parameter of type reference to function, no
5177      conversions apply. If the template-argument represents a set of
5178      overloaded functions, the matching function is selected from the set
5179      (_over.over_).  */
5180   else if (TYPE_REFFN_P (type))
5181     {
5182       if (TREE_CODE (expr) == ADDR_EXPR)
5183         {
5184           error ("%qE is not a valid template argument for type %qT "
5185                  "because it is a pointer", expr, type);
5186           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5187           return NULL_TREE;
5188         }
5189
5190       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5191       if (!expr || expr == error_mark_node)
5192         return expr;
5193
5194       expr = build_nop (type, build_address (expr));
5195     }
5196   /* [temp.arg.nontype]/5, bullet 6
5197
5198      For a non-type template-parameter of type pointer to member function,
5199      no conversions apply. If the template-argument represents a set of
5200      overloaded member functions, the matching member function is selected
5201      from the set (_over.over_).  */
5202   else if (TYPE_PTRMEMFUNC_P (type))
5203     {
5204       expr = instantiate_type (type, expr, tf_none);
5205       if (expr == error_mark_node)
5206         return error_mark_node;
5207
5208       /* [temp.arg.nontype] bullet 1 says the pointer to member
5209          expression must be a pointer-to-member constant.  */
5210       if (!check_valid_ptrmem_cst_expr (type, expr))
5211         return error_mark_node;
5212
5213       /* There is no way to disable standard conversions in
5214          resolve_address_of_overloaded_function (called by
5215          instantiate_type). It is possible that the call succeeded by
5216          converting &B::I to &D::I (where B is a base of D), so we need
5217          to reject this conversion here.
5218
5219          Actually, even if there was a way to disable standard conversions,
5220          it would still be better to reject them here so that we can
5221          provide a superior diagnostic.  */
5222       if (!same_type_p (TREE_TYPE (expr), type))
5223         {
5224           error ("%qE is not a valid template argument for type %qT "
5225                  "because it is of type %qT", expr, type,
5226                  TREE_TYPE (expr));
5227           /* If we are just one standard conversion off, explain.  */
5228           if (can_convert (type, TREE_TYPE (expr)))
5229             inform (input_location,
5230                     "standard conversions are not allowed in this context");
5231           return NULL_TREE;
5232         }
5233     }
5234   /* [temp.arg.nontype]/5, bullet 7
5235
5236      For a non-type template-parameter of type pointer to data member,
5237      qualification conversions (_conv.qual_) are applied.  */
5238   else if (TYPE_PTRMEM_P (type))
5239     {
5240       /* [temp.arg.nontype] bullet 1 says the pointer to member
5241          expression must be a pointer-to-member constant.  */
5242       if (!check_valid_ptrmem_cst_expr (type, expr))
5243         return error_mark_node;
5244
5245       expr = perform_qualification_conversions (type, expr);
5246       if (expr == error_mark_node)
5247         return expr;
5248     }
5249   /* A template non-type parameter must be one of the above.  */
5250   else
5251     gcc_unreachable ();
5252
5253   /* Sanity check: did we actually convert the argument to the
5254      right type?  */
5255   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5256   return expr;
5257 }
5258
5259 /* Subroutine of coerce_template_template_parms, which returns 1 if
5260    PARM_PARM and ARG_PARM match using the rule for the template
5261    parameters of template template parameters. Both PARM and ARG are
5262    template parameters; the rest of the arguments are the same as for
5263    coerce_template_template_parms.
5264  */
5265 static int
5266 coerce_template_template_parm (tree parm,
5267                               tree arg,
5268                               tsubst_flags_t complain,
5269                               tree in_decl,
5270                               tree outer_args)
5271 {
5272   if (arg == NULL_TREE || arg == error_mark_node
5273       || parm == NULL_TREE || parm == error_mark_node)
5274     return 0;
5275   
5276   if (TREE_CODE (arg) != TREE_CODE (parm))
5277     return 0;
5278   
5279   switch (TREE_CODE (parm))
5280     {
5281     case TEMPLATE_DECL:
5282       /* We encounter instantiations of templates like
5283          template <template <template <class> class> class TT>
5284          class C;  */
5285       {
5286         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5287         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5288         
5289         if (!coerce_template_template_parms
5290             (parmparm, argparm, complain, in_decl, outer_args))
5291           return 0;
5292       }
5293       /* Fall through.  */
5294       
5295     case TYPE_DECL:
5296       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5297           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5298         /* Argument is a parameter pack but parameter is not.  */
5299         return 0;
5300       break;
5301       
5302     case PARM_DECL:
5303       /* The tsubst call is used to handle cases such as
5304          
5305            template <int> class C {};
5306            template <class T, template <T> class TT> class D {};
5307            D<int, C> d;
5308
5309          i.e. the parameter list of TT depends on earlier parameters.  */
5310       if (!uses_template_parms (TREE_TYPE (arg))
5311           && !same_type_p
5312                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5313                  TREE_TYPE (arg)))
5314         return 0;
5315       
5316       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5317           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5318         /* Argument is a parameter pack but parameter is not.  */
5319         return 0;
5320       
5321       break;
5322
5323     default:
5324       gcc_unreachable ();
5325     }
5326
5327   return 1;
5328 }
5329
5330
5331 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5332    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5333    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5334    or PARM_DECL.
5335
5336    Consider the example:
5337      template <class T> class A;
5338      template<template <class U> class TT> class B;
5339
5340    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5341    the parameters to A, and OUTER_ARGS contains A.  */
5342
5343 static int
5344 coerce_template_template_parms (tree parm_parms,
5345                                 tree arg_parms,
5346                                 tsubst_flags_t complain,
5347                                 tree in_decl,
5348                                 tree outer_args)
5349 {
5350   int nparms, nargs, i;
5351   tree parm, arg;
5352   int variadic_p = 0;
5353
5354   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5355   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5356
5357   nparms = TREE_VEC_LENGTH (parm_parms);
5358   nargs = TREE_VEC_LENGTH (arg_parms);
5359
5360   /* Determine whether we have a parameter pack at the end of the
5361      template template parameter's template parameter list.  */
5362   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5363     {
5364       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5365       
5366       if (parm == error_mark_node)
5367         return 0;
5368
5369       switch (TREE_CODE (parm))
5370         {
5371         case TEMPLATE_DECL:
5372         case TYPE_DECL:
5373           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5374             variadic_p = 1;
5375           break;
5376           
5377         case PARM_DECL:
5378           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5379             variadic_p = 1;
5380           break;
5381           
5382         default:
5383           gcc_unreachable ();
5384         }
5385     }
5386  
5387   if (nargs != nparms
5388       && !(variadic_p && nargs >= nparms - 1))
5389     return 0;
5390
5391   /* Check all of the template parameters except the parameter pack at
5392      the end (if any).  */
5393   for (i = 0; i < nparms - variadic_p; ++i)
5394     {
5395       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5396           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5397         continue;
5398
5399       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5400       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5401
5402       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5403                                           outer_args))
5404         return 0;
5405
5406     }
5407
5408   if (variadic_p)
5409     {
5410       /* Check each of the template parameters in the template
5411          argument against the template parameter pack at the end of
5412          the template template parameter.  */
5413       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5414         return 0;
5415
5416       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5417
5418       for (; i < nargs; ++i)
5419         {
5420           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5421             continue;
5422  
5423           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5424  
5425           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5426                                               outer_args))
5427             return 0;
5428         }
5429     }
5430
5431   return 1;
5432 }
5433
5434 /* Verifies that the deduced template arguments (in TARGS) for the
5435    template template parameters (in TPARMS) represent valid bindings,
5436    by comparing the template parameter list of each template argument
5437    to the template parameter list of its corresponding template
5438    template parameter, in accordance with DR150. This
5439    routine can only be called after all template arguments have been
5440    deduced. It will return TRUE if all of the template template
5441    parameter bindings are okay, FALSE otherwise.  */
5442 bool 
5443 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5444 {
5445   int i, ntparms = TREE_VEC_LENGTH (tparms);
5446   bool ret = true;
5447
5448   /* We're dealing with template parms in this process.  */
5449   ++processing_template_decl;
5450
5451   targs = INNERMOST_TEMPLATE_ARGS (targs);
5452
5453   for (i = 0; i < ntparms; ++i)
5454     {
5455       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5456       tree targ = TREE_VEC_ELT (targs, i);
5457
5458       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5459         {
5460           tree packed_args = NULL_TREE;
5461           int idx, len = 1;
5462
5463           if (ARGUMENT_PACK_P (targ))
5464             {
5465               /* Look inside the argument pack.  */
5466               packed_args = ARGUMENT_PACK_ARGS (targ);
5467               len = TREE_VEC_LENGTH (packed_args);
5468             }
5469
5470           for (idx = 0; idx < len; ++idx)
5471             {
5472               tree targ_parms = NULL_TREE;
5473
5474               if (packed_args)
5475                 /* Extract the next argument from the argument
5476                    pack.  */
5477                 targ = TREE_VEC_ELT (packed_args, idx);
5478
5479               if (PACK_EXPANSION_P (targ))
5480                 /* Look at the pattern of the pack expansion.  */
5481                 targ = PACK_EXPANSION_PATTERN (targ);
5482
5483               /* Extract the template parameters from the template
5484                  argument.  */
5485               if (TREE_CODE (targ) == TEMPLATE_DECL)
5486                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5487               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5488                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5489
5490               /* Verify that we can coerce the template template
5491                  parameters from the template argument to the template
5492                  parameter.  This requires an exact match.  */
5493               if (targ_parms
5494                   && !coerce_template_template_parms
5495                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5496                         targ_parms,
5497                         tf_none,
5498                         tparm,
5499                         targs))
5500                 {
5501                   ret = false;
5502                   goto out;
5503                 }
5504             }
5505         }
5506     }
5507
5508  out:
5509
5510   --processing_template_decl;
5511   return ret;
5512 }
5513
5514 /* Convert the indicated template ARG as necessary to match the
5515    indicated template PARM.  Returns the converted ARG, or
5516    error_mark_node if the conversion was unsuccessful.  Error and
5517    warning messages are issued under control of COMPLAIN.  This
5518    conversion is for the Ith parameter in the parameter list.  ARGS is
5519    the full set of template arguments deduced so far.  */
5520
5521 static tree
5522 convert_template_argument (tree parm,
5523                            tree arg,
5524                            tree args,
5525                            tsubst_flags_t complain,
5526                            int i,
5527                            tree in_decl)
5528 {
5529   tree orig_arg;
5530   tree val;
5531   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5532
5533   if (TREE_CODE (arg) == TREE_LIST
5534       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5535     {
5536       /* The template argument was the name of some
5537          member function.  That's usually
5538          invalid, but static members are OK.  In any
5539          case, grab the underlying fields/functions
5540          and issue an error later if required.  */
5541       orig_arg = TREE_VALUE (arg);
5542       TREE_TYPE (arg) = unknown_type_node;
5543     }
5544
5545   orig_arg = arg;
5546
5547   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5548   requires_type = (TREE_CODE (parm) == TYPE_DECL
5549                    || requires_tmpl_type);
5550
5551   /* When determining whether an argument pack expansion is a template,
5552      look at the pattern.  */
5553   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5554     arg = PACK_EXPANSION_PATTERN (arg);
5555
5556   /* Deal with an injected-class-name used as a template template arg.  */
5557   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5558     {
5559       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5560       if (TREE_CODE (t) == TEMPLATE_DECL)
5561         {
5562           if (complain & tf_warning_or_error)
5563             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5564                      " used as template template argument", TYPE_NAME (arg));
5565           else if (flag_pedantic_errors)
5566             t = arg;
5567
5568           arg = t;
5569         }
5570     }
5571
5572   is_tmpl_type = 
5573     ((TREE_CODE (arg) == TEMPLATE_DECL
5574       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5575      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5576      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5577
5578   if (is_tmpl_type
5579       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5580           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5581     arg = TYPE_STUB_DECL (arg);
5582
5583   is_type = TYPE_P (arg) || is_tmpl_type;
5584
5585   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5586       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5587     {
5588       permerror (input_location, "to refer to a type member of a template parameter, "
5589                  "use %<typename %E%>", orig_arg);
5590
5591       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5592                                      TREE_OPERAND (arg, 1),
5593                                      typename_type,
5594                                      complain & tf_error);
5595       arg = orig_arg;
5596       is_type = 1;
5597     }
5598   if (is_type != requires_type)
5599     {
5600       if (in_decl)
5601         {
5602           if (complain & tf_error)
5603             {
5604               error ("type/value mismatch at argument %d in template "
5605                      "parameter list for %qD",
5606                      i + 1, in_decl);
5607               if (is_type)
5608                 error ("  expected a constant of type %qT, got %qT",
5609                        TREE_TYPE (parm),
5610                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5611               else if (requires_tmpl_type)
5612                 error ("  expected a class template, got %qE", orig_arg);
5613               else
5614                 error ("  expected a type, got %qE", orig_arg);
5615             }
5616         }
5617       return error_mark_node;
5618     }
5619   if (is_tmpl_type ^ requires_tmpl_type)
5620     {
5621       if (in_decl && (complain & tf_error))
5622         {
5623           error ("type/value mismatch at argument %d in template "
5624                  "parameter list for %qD",
5625                  i + 1, in_decl);
5626           if (is_tmpl_type)
5627             error ("  expected a type, got %qT", DECL_NAME (arg));
5628           else
5629             error ("  expected a class template, got %qT", orig_arg);
5630         }
5631       return error_mark_node;
5632     }
5633
5634   if (is_type)
5635     {
5636       if (requires_tmpl_type)
5637         {
5638           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5639             /* The number of argument required is not known yet.
5640                Just accept it for now.  */
5641             val = TREE_TYPE (arg);
5642           else
5643             {
5644               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5645               tree argparm;
5646
5647               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5648
5649               if (coerce_template_template_parms (parmparm, argparm,
5650                                                   complain, in_decl,
5651                                                   args))
5652                 {
5653                   val = arg;
5654
5655                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5656                      TEMPLATE_DECL.  */
5657                   if (val != error_mark_node)
5658                     {
5659                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5660                         val = TREE_TYPE (val);
5661                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5662                         val = make_pack_expansion (val);
5663                     }
5664                 }
5665               else
5666                 {
5667                   if (in_decl && (complain & tf_error))
5668                     {
5669                       error ("type/value mismatch at argument %d in "
5670                              "template parameter list for %qD",
5671                              i + 1, in_decl);
5672                       error ("  expected a template of type %qD, got %qT",
5673                              parm, orig_arg);
5674                     }
5675
5676                   val = error_mark_node;
5677                 }
5678             }
5679         }
5680       else
5681         val = orig_arg;
5682       /* We only form one instance of each template specialization.
5683          Therefore, if we use a non-canonical variant (i.e., a
5684          typedef), any future messages referring to the type will use
5685          the typedef, which is confusing if those future uses do not
5686          themselves also use the typedef.  */
5687       if (TYPE_P (val))
5688         val = strip_typedefs (val);
5689     }
5690   else
5691     {
5692       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5693
5694       if (invalid_nontype_parm_type_p (t, complain))
5695         return error_mark_node;
5696
5697       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5698         {
5699           if (same_type_p (t, TREE_TYPE (orig_arg)))
5700             val = orig_arg;
5701           else
5702             {
5703               /* Not sure if this is reachable, but it doesn't hurt
5704                  to be robust.  */
5705               error ("type mismatch in nontype parameter pack");
5706               val = error_mark_node;
5707             }
5708         }
5709       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5710         /* We used to call digest_init here.  However, digest_init
5711            will report errors, which we don't want when complain
5712            is zero.  More importantly, digest_init will try too
5713            hard to convert things: for example, `0' should not be
5714            converted to pointer type at this point according to
5715            the standard.  Accepting this is not merely an
5716            extension, since deciding whether or not these
5717            conversions can occur is part of determining which
5718            function template to call, or whether a given explicit
5719            argument specification is valid.  */
5720         val = convert_nontype_argument (t, orig_arg);
5721       else
5722         val = orig_arg;
5723
5724       if (val == NULL_TREE)
5725         val = error_mark_node;
5726       else if (val == error_mark_node && (complain & tf_error))
5727         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5728
5729       if (TREE_CODE (val) == SCOPE_REF)
5730         {
5731           /* Strip typedefs from the SCOPE_REF.  */
5732           tree type = strip_typedefs (TREE_TYPE (val));
5733           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5734           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5735                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5736         }
5737     }
5738
5739   return val;
5740 }
5741
5742 /* Coerces the remaining template arguments in INNER_ARGS (from
5743    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5744    Returns the coerced argument pack. PARM_IDX is the position of this
5745    parameter in the template parameter list. ARGS is the original
5746    template argument list.  */
5747 static tree
5748 coerce_template_parameter_pack (tree parms,
5749                                 int parm_idx,
5750                                 tree args,
5751                                 tree inner_args,
5752                                 int arg_idx,
5753                                 tree new_args,
5754                                 int* lost,
5755                                 tree in_decl,
5756                                 tsubst_flags_t complain)
5757 {
5758   tree parm = TREE_VEC_ELT (parms, parm_idx);
5759   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5760   tree packed_args;
5761   tree argument_pack;
5762   tree packed_types = NULL_TREE;
5763
5764   if (arg_idx > nargs)
5765     arg_idx = nargs;
5766
5767   packed_args = make_tree_vec (nargs - arg_idx);
5768
5769   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5770       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5771     {
5772       /* When the template parameter is a non-type template
5773          parameter pack whose type uses parameter packs, we need
5774          to look at each of the template arguments
5775          separately. Build a vector of the types for these
5776          non-type template parameters in PACKED_TYPES.  */
5777       tree expansion 
5778         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5779       packed_types = tsubst_pack_expansion (expansion, args,
5780                                             complain, in_decl);
5781
5782       if (packed_types == error_mark_node)
5783         return error_mark_node;
5784
5785       /* Check that we have the right number of arguments.  */
5786       if (arg_idx < nargs
5787           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5788           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5789         {
5790           int needed_parms 
5791             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5792           error ("wrong number of template arguments (%d, should be %d)",
5793                  nargs, needed_parms);
5794           return error_mark_node;
5795         }
5796
5797       /* If we aren't able to check the actual arguments now
5798          (because they haven't been expanded yet), we can at least
5799          verify that all of the types used for the non-type
5800          template parameter pack are, in fact, valid for non-type
5801          template parameters.  */
5802       if (arg_idx < nargs 
5803           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5804         {
5805           int j, len = TREE_VEC_LENGTH (packed_types);
5806           for (j = 0; j < len; ++j)
5807             {
5808               tree t = TREE_VEC_ELT (packed_types, j);
5809               if (invalid_nontype_parm_type_p (t, complain))
5810                 return error_mark_node;
5811             }
5812         }
5813     }
5814
5815   /* Convert the remaining arguments, which will be a part of the
5816      parameter pack "parm".  */
5817   for (; arg_idx < nargs; ++arg_idx)
5818     {
5819       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5820       tree actual_parm = TREE_VALUE (parm);
5821
5822       if (packed_types && !PACK_EXPANSION_P (arg))
5823         {
5824           /* When we have a vector of types (corresponding to the
5825              non-type template parameter pack that uses parameter
5826              packs in its type, as mention above), and the
5827              argument is not an expansion (which expands to a
5828              currently unknown number of arguments), clone the
5829              parm and give it the next type in PACKED_TYPES.  */
5830           actual_parm = copy_node (actual_parm);
5831           TREE_TYPE (actual_parm) = 
5832             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5833         }
5834
5835       if (arg != error_mark_node)
5836         arg = convert_template_argument (actual_parm, 
5837                                          arg, new_args, complain, parm_idx,
5838                                          in_decl);
5839       if (arg == error_mark_node)
5840         (*lost)++;
5841       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5842     }
5843
5844   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5845       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5846     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5847   else
5848     {
5849       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5850       TREE_TYPE (argument_pack) 
5851         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5852       TREE_CONSTANT (argument_pack) = 1;
5853     }
5854
5855   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5856 #ifdef ENABLE_CHECKING
5857   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5858                                        TREE_VEC_LENGTH (packed_args));
5859 #endif
5860   return argument_pack;
5861 }
5862
5863 /* Convert all template arguments to their appropriate types, and
5864    return a vector containing the innermost resulting template
5865    arguments.  If any error occurs, return error_mark_node. Error and
5866    warning messages are issued under control of COMPLAIN.
5867
5868    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5869    for arguments not specified in ARGS.  Otherwise, if
5870    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5871    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5872    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5873    ARGS.  */
5874
5875 static tree
5876 coerce_template_parms (tree parms,
5877                        tree args,
5878                        tree in_decl,
5879                        tsubst_flags_t complain,
5880                        bool require_all_args,
5881                        bool use_default_args)
5882 {
5883   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5884   tree inner_args;
5885   tree new_args;
5886   tree new_inner_args;
5887   int saved_unevaluated_operand;
5888   int saved_inhibit_evaluation_warnings;
5889
5890   /* When used as a boolean value, indicates whether this is a
5891      variadic template parameter list. Since it's an int, we can also
5892      subtract it from nparms to get the number of non-variadic
5893      parameters.  */
5894   int variadic_p = 0;
5895
5896   nparms = TREE_VEC_LENGTH (parms);
5897
5898   /* Determine if there are any parameter packs.  */
5899   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5900     {
5901       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5902       if (template_parameter_pack_p (tparm))
5903         ++variadic_p;
5904     }
5905
5906   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5907   /* If there are 0 or 1 parameter packs, we need to expand any argument
5908      packs so that we can deduce a parameter pack from some non-packed args
5909      followed by an argument pack, as in variadic85.C.  If there are more
5910      than that, we need to leave argument packs intact so the arguments are
5911      assigned to the right parameter packs.  This should only happen when
5912      dealing with a nested class inside a partial specialization of a class
5913      template, as in variadic92.C.  */
5914   if (variadic_p <= 1)
5915     inner_args = expand_template_argument_pack (inner_args);
5916
5917   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5918   if ((nargs > nparms && !variadic_p)
5919       || (nargs < nparms - variadic_p
5920           && require_all_args
5921           && (!use_default_args
5922               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5923                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5924     {
5925       if (complain & tf_error)
5926         {
5927           const char *or_more = "";
5928           if (variadic_p)
5929             {
5930               or_more = " or more";
5931               --nparms;
5932             }
5933
5934           error ("wrong number of template arguments (%d, should be %d%s)",
5935                  nargs, nparms, or_more);
5936
5937           if (in_decl)
5938             error ("provided for %q+D", in_decl);
5939         }
5940
5941       return error_mark_node;
5942     }
5943
5944   /* We need to evaluate the template arguments, even though this
5945      template-id may be nested within a "sizeof".  */
5946   saved_unevaluated_operand = cp_unevaluated_operand;
5947   cp_unevaluated_operand = 0;
5948   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5949   c_inhibit_evaluation_warnings = 0;
5950   new_inner_args = make_tree_vec (nparms);
5951   new_args = add_outermost_template_args (args, new_inner_args);
5952   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5953     {
5954       tree arg;
5955       tree parm;
5956
5957       /* Get the Ith template parameter.  */
5958       parm = TREE_VEC_ELT (parms, parm_idx);
5959  
5960       if (parm == error_mark_node)
5961       {
5962         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5963         continue;
5964       }
5965
5966       /* Calculate the next argument.  */
5967       if (arg_idx < nargs)
5968         arg = TREE_VEC_ELT (inner_args, arg_idx);
5969       else
5970         arg = NULL_TREE;
5971
5972       if (template_parameter_pack_p (TREE_VALUE (parm))
5973           && !(arg && ARGUMENT_PACK_P (arg)))
5974         {
5975           /* All remaining arguments will be placed in the
5976              template parameter pack PARM.  */
5977           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5978                                                 inner_args, arg_idx,
5979                                                 new_args, &lost,
5980                                                 in_decl, complain);
5981
5982           /* Store this argument.  */
5983           if (arg == error_mark_node)
5984             lost++;
5985           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5986
5987           /* We are done with all of the arguments.  */
5988           arg_idx = nargs;
5989           
5990           continue;
5991         }
5992       else if (arg)
5993         {
5994           if (PACK_EXPANSION_P (arg))
5995             {
5996               if (complain & tf_error)
5997                 {
5998                   /* FIXME this restriction was removed by N2555; see
5999                      bug 35722.  */
6000                   /* If ARG is a pack expansion, but PARM is not a
6001                      template parameter pack (if it were, we would have
6002                      handled it above), we're trying to expand into a
6003                      fixed-length argument list.  */
6004                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6005                     sorry ("cannot expand %<%E%> into a fixed-length "
6006                            "argument list", arg);
6007                   else
6008                     sorry ("cannot expand %<%T%> into a fixed-length "
6009                            "argument list", arg);
6010                 }
6011               return error_mark_node;
6012             }
6013         }
6014       else if (require_all_args)
6015         {
6016           /* There must be a default arg in this case.  */
6017           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6018                                      complain, in_decl);
6019           /* The position of the first default template argument,
6020              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6021              Record that.  */
6022           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6023             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6024         }
6025       else
6026         break;
6027
6028       if (arg == error_mark_node)
6029         {
6030           if (complain & tf_error)
6031             error ("template argument %d is invalid", arg_idx + 1);
6032         }
6033       else if (!arg)
6034         /* This only occurs if there was an error in the template
6035            parameter list itself (which we would already have
6036            reported) that we are trying to recover from, e.g., a class
6037            template with a parameter list such as
6038            template<typename..., typename>.  */
6039         return error_mark_node;
6040       else
6041         arg = convert_template_argument (TREE_VALUE (parm),
6042                                          arg, new_args, complain, 
6043                                          parm_idx, in_decl);
6044
6045       if (arg == error_mark_node)
6046         lost++;
6047       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6048     }
6049   cp_unevaluated_operand = saved_unevaluated_operand;
6050   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6051
6052   if (lost)
6053     return error_mark_node;
6054
6055 #ifdef ENABLE_CHECKING
6056   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6057     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6058                                          TREE_VEC_LENGTH (new_inner_args));
6059 #endif
6060
6061   return new_inner_args;
6062 }
6063
6064 /* Returns 1 if template args OT and NT are equivalent.  */
6065
6066 static int
6067 template_args_equal (tree ot, tree nt)
6068 {
6069   if (nt == ot)
6070     return 1;
6071
6072   if (TREE_CODE (nt) == TREE_VEC)
6073     /* For member templates */
6074     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6075   else if (PACK_EXPANSION_P (ot))
6076     return PACK_EXPANSION_P (nt) 
6077       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6078                               PACK_EXPANSION_PATTERN (nt));
6079   else if (ARGUMENT_PACK_P (ot))
6080     {
6081       int i, len;
6082       tree opack, npack;
6083
6084       if (!ARGUMENT_PACK_P (nt))
6085         return 0;
6086
6087       opack = ARGUMENT_PACK_ARGS (ot);
6088       npack = ARGUMENT_PACK_ARGS (nt);
6089       len = TREE_VEC_LENGTH (opack);
6090       if (TREE_VEC_LENGTH (npack) != len)
6091         return 0;
6092       for (i = 0; i < len; ++i)
6093         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6094                                   TREE_VEC_ELT (npack, i)))
6095           return 0;
6096       return 1;
6097     }
6098   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6099     {
6100       /* We get here probably because we are in the middle of substituting
6101          into the pattern of a pack expansion. In that case the
6102          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6103          interested in. So we want to use the initial pack argument for
6104          the comparison.  */
6105       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6106       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6107         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6108       return template_args_equal (ot, nt);
6109     }
6110   else if (TYPE_P (nt))
6111     return TYPE_P (ot) && same_type_p (ot, nt);
6112   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6113     return 0;
6114   else
6115     return cp_tree_equal (ot, nt);
6116 }
6117
6118 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6119    of template arguments.  Returns 0 otherwise.  */
6120
6121 int
6122 comp_template_args (tree oldargs, tree newargs)
6123 {
6124   int i;
6125
6126   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6127     return 0;
6128
6129   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6130     {
6131       tree nt = TREE_VEC_ELT (newargs, i);
6132       tree ot = TREE_VEC_ELT (oldargs, i);
6133
6134       if (! template_args_equal (ot, nt))
6135         return 0;
6136     }
6137   return 1;
6138 }
6139
6140 static void
6141 add_pending_template (tree d)
6142 {
6143   tree ti = (TYPE_P (d)
6144              ? CLASSTYPE_TEMPLATE_INFO (d)
6145              : DECL_TEMPLATE_INFO (d));
6146   struct pending_template *pt;
6147   int level;
6148
6149   if (TI_PENDING_TEMPLATE_FLAG (ti))
6150     return;
6151
6152   /* We are called both from instantiate_decl, where we've already had a
6153      tinst_level pushed, and instantiate_template, where we haven't.
6154      Compensate.  */
6155   level = !current_tinst_level || current_tinst_level->decl != d;
6156
6157   if (level)
6158     push_tinst_level (d);
6159
6160   pt = GGC_NEW (struct pending_template);
6161   pt->next = NULL;
6162   pt->tinst = current_tinst_level;
6163   if (last_pending_template)
6164     last_pending_template->next = pt;
6165   else
6166     pending_templates = pt;
6167
6168   last_pending_template = pt;
6169
6170   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6171
6172   if (level)
6173     pop_tinst_level ();
6174 }
6175
6176
6177 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6178    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6179    documentation for TEMPLATE_ID_EXPR.  */
6180
6181 tree
6182 lookup_template_function (tree fns, tree arglist)
6183 {
6184   tree type;
6185
6186   if (fns == error_mark_node || arglist == error_mark_node)
6187     return error_mark_node;
6188
6189   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6190   gcc_assert (fns && (is_overloaded_fn (fns)
6191                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6192
6193   if (BASELINK_P (fns))
6194     {
6195       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6196                                          unknown_type_node,
6197                                          BASELINK_FUNCTIONS (fns),
6198                                          arglist);
6199       return fns;
6200     }
6201
6202   type = TREE_TYPE (fns);
6203   if (TREE_CODE (fns) == OVERLOAD || !type)
6204     type = unknown_type_node;
6205
6206   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6207 }
6208
6209 /* Within the scope of a template class S<T>, the name S gets bound
6210    (in build_self_reference) to a TYPE_DECL for the class, not a
6211    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6212    or one of its enclosing classes, and that type is a template,
6213    return the associated TEMPLATE_DECL.  Otherwise, the original
6214    DECL is returned.
6215
6216    Also handle the case when DECL is a TREE_LIST of ambiguous
6217    injected-class-names from different bases.  */
6218
6219 tree
6220 maybe_get_template_decl_from_type_decl (tree decl)
6221 {
6222   if (decl == NULL_TREE)
6223     return decl;
6224
6225   /* DR 176: A lookup that finds an injected-class-name (10.2
6226      [class.member.lookup]) can result in an ambiguity in certain cases
6227      (for example, if it is found in more than one base class). If all of
6228      the injected-class-names that are found refer to specializations of
6229      the same class template, and if the name is followed by a
6230      template-argument-list, the reference refers to the class template
6231      itself and not a specialization thereof, and is not ambiguous.  */
6232   if (TREE_CODE (decl) == TREE_LIST)
6233     {
6234       tree t, tmpl = NULL_TREE;
6235       for (t = decl; t; t = TREE_CHAIN (t))
6236         {
6237           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6238           if (!tmpl)
6239             tmpl = elt;
6240           else if (tmpl != elt)
6241             break;
6242         }
6243       if (tmpl && t == NULL_TREE)
6244         return tmpl;
6245       else
6246         return decl;
6247     }
6248
6249   return (decl != NULL_TREE
6250           && DECL_SELF_REFERENCE_P (decl)
6251           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6252     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6253 }
6254
6255 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6256    parameters, find the desired type.
6257
6258    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6259
6260    IN_DECL, if non-NULL, is the template declaration we are trying to
6261    instantiate.
6262
6263    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6264    the class we are looking up.
6265
6266    Issue error and warning messages under control of COMPLAIN.
6267
6268    If the template class is really a local class in a template
6269    function, then the FUNCTION_CONTEXT is the function in which it is
6270    being instantiated.
6271
6272    ??? Note that this function is currently called *twice* for each
6273    template-id: the first time from the parser, while creating the
6274    incomplete type (finish_template_type), and the second type during the
6275    real instantiation (instantiate_template_class). This is surely something
6276    that we want to avoid. It also causes some problems with argument
6277    coercion (see convert_nontype_argument for more information on this).  */
6278
6279 tree
6280 lookup_template_class (tree d1,
6281                        tree arglist,
6282                        tree in_decl,
6283                        tree context,
6284                        int entering_scope,
6285                        tsubst_flags_t complain)
6286 {
6287   tree templ = NULL_TREE, parmlist;
6288   tree t;
6289   spec_entry **slot;
6290   spec_entry *entry;
6291   spec_entry elt;
6292   hashval_t hash;
6293
6294   timevar_push (TV_NAME_LOOKUP);
6295
6296   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6297     {
6298       tree value = innermost_non_namespace_value (d1);
6299       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6300         templ = value;
6301       else
6302         {
6303           if (context)
6304             push_decl_namespace (context);
6305           templ = lookup_name (d1);
6306           templ = maybe_get_template_decl_from_type_decl (templ);
6307           if (context)
6308             pop_decl_namespace ();
6309         }
6310       if (templ)
6311         context = DECL_CONTEXT (templ);
6312     }
6313   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6314     {
6315       tree type = TREE_TYPE (d1);
6316
6317       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6318          an implicit typename for the second A.  Deal with it.  */
6319       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6320         type = TREE_TYPE (type);
6321
6322       if (CLASSTYPE_TEMPLATE_INFO (type))
6323         {
6324           templ = CLASSTYPE_TI_TEMPLATE (type);
6325           d1 = DECL_NAME (templ);
6326         }
6327     }
6328   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6329            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6330     {
6331       templ = TYPE_TI_TEMPLATE (d1);
6332       d1 = DECL_NAME (templ);
6333     }
6334   else if (TREE_CODE (d1) == TEMPLATE_DECL
6335            && DECL_TEMPLATE_RESULT (d1)
6336            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6337     {
6338       templ = d1;
6339       d1 = DECL_NAME (templ);
6340       context = DECL_CONTEXT (templ);
6341     }
6342
6343   /* Issue an error message if we didn't find a template.  */
6344   if (! templ)
6345     {
6346       if (complain & tf_error)
6347         error ("%qT is not a template", d1);
6348       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6349     }
6350
6351   if (TREE_CODE (templ) != TEMPLATE_DECL
6352          /* Make sure it's a user visible template, if it was named by
6353             the user.  */
6354       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6355           && !PRIMARY_TEMPLATE_P (templ)))
6356     {
6357       if (complain & tf_error)
6358         {
6359           error ("non-template type %qT used as a template", d1);
6360           if (in_decl)
6361             error ("for template declaration %q+D", in_decl);
6362         }
6363       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6364     }
6365
6366   complain &= ~tf_user;
6367
6368   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6369     {
6370       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6371          template arguments */
6372
6373       tree parm;
6374       tree arglist2;
6375       tree outer;
6376
6377       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6378
6379       /* Consider an example where a template template parameter declared as
6380
6381            template <class T, class U = std::allocator<T> > class TT
6382
6383          The template parameter level of T and U are one level larger than
6384          of TT.  To proper process the default argument of U, say when an
6385          instantiation `TT<int>' is seen, we need to build the full
6386          arguments containing {int} as the innermost level.  Outer levels,
6387          available when not appearing as default template argument, can be
6388          obtained from the arguments of the enclosing template.
6389
6390          Suppose that TT is later substituted with std::vector.  The above
6391          instantiation is `TT<int, std::allocator<T> >' with TT at
6392          level 1, and T at level 2, while the template arguments at level 1
6393          becomes {std::vector} and the inner level 2 is {int}.  */
6394
6395       outer = DECL_CONTEXT (templ);
6396       if (outer)
6397         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6398       else if (current_template_parms)
6399         /* This is an argument of the current template, so we haven't set
6400            DECL_CONTEXT yet.  */
6401         outer = current_template_args ();
6402
6403       if (outer)
6404         arglist = add_to_template_args (outer, arglist);
6405
6406       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6407                                         complain,
6408                                         /*require_all_args=*/true,
6409                                         /*use_default_args=*/true);
6410       if (arglist2 == error_mark_node
6411           || (!uses_template_parms (arglist2)
6412               && check_instantiated_args (templ, arglist2, complain)))
6413         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6414
6415       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6416       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6417     }
6418   else
6419     {
6420       tree template_type = TREE_TYPE (templ);
6421       tree gen_tmpl;
6422       tree type_decl;
6423       tree found = NULL_TREE;
6424       int arg_depth;
6425       int parm_depth;
6426       int is_dependent_type;
6427       int use_partial_inst_tmpl = false;
6428
6429       gen_tmpl = most_general_template (templ);
6430       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6431       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6432       arg_depth = TMPL_ARGS_DEPTH (arglist);
6433
6434       if (arg_depth == 1 && parm_depth > 1)
6435         {
6436           /* We've been given an incomplete set of template arguments.
6437              For example, given:
6438
6439                template <class T> struct S1 {
6440                  template <class U> struct S2 {};
6441                  template <class U> struct S2<U*> {};
6442                 };
6443
6444              we will be called with an ARGLIST of `U*', but the
6445              TEMPLATE will be `template <class T> template
6446              <class U> struct S1<T>::S2'.  We must fill in the missing
6447              arguments.  */
6448           arglist
6449             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6450                                            arglist);
6451           arg_depth = TMPL_ARGS_DEPTH (arglist);
6452         }
6453
6454       /* Now we should have enough arguments.  */
6455       gcc_assert (parm_depth == arg_depth);
6456
6457       /* From here on, we're only interested in the most general
6458          template.  */
6459
6460       /* Calculate the BOUND_ARGS.  These will be the args that are
6461          actually tsubst'd into the definition to create the
6462          instantiation.  */
6463       if (parm_depth > 1)
6464         {
6465           /* We have multiple levels of arguments to coerce, at once.  */
6466           int i;
6467           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6468
6469           tree bound_args = make_tree_vec (parm_depth);
6470
6471           for (i = saved_depth,
6472                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6473                i > 0 && t != NULL_TREE;
6474                --i, t = TREE_CHAIN (t))
6475             {
6476               tree a = coerce_template_parms (TREE_VALUE (t),
6477                                               arglist, gen_tmpl,
6478                                               complain,
6479                                               /*require_all_args=*/true,
6480                                               /*use_default_args=*/true);
6481
6482               /* Don't process further if one of the levels fails.  */
6483               if (a == error_mark_node)
6484                 {
6485                   /* Restore the ARGLIST to its full size.  */
6486                   TREE_VEC_LENGTH (arglist) = saved_depth;
6487                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6488                 }
6489
6490               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6491
6492               /* We temporarily reduce the length of the ARGLIST so
6493                  that coerce_template_parms will see only the arguments
6494                  corresponding to the template parameters it is
6495                  examining.  */
6496               TREE_VEC_LENGTH (arglist)--;
6497             }
6498
6499           /* Restore the ARGLIST to its full size.  */
6500           TREE_VEC_LENGTH (arglist) = saved_depth;
6501
6502           arglist = bound_args;
6503         }
6504       else
6505         arglist
6506           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6507                                    INNERMOST_TEMPLATE_ARGS (arglist),
6508                                    gen_tmpl,
6509                                    complain,
6510                                    /*require_all_args=*/true,
6511                                    /*use_default_args=*/true);
6512
6513       if (arglist == error_mark_node)
6514         /* We were unable to bind the arguments.  */
6515         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6516
6517       /* In the scope of a template class, explicit references to the
6518          template class refer to the type of the template, not any
6519          instantiation of it.  For example, in:
6520
6521            template <class T> class C { void f(C<T>); }
6522
6523          the `C<T>' is just the same as `C'.  Outside of the
6524          class, however, such a reference is an instantiation.  */
6525       if ((entering_scope
6526            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6527            || currently_open_class (template_type))
6528           /* comp_template_args is expensive, check it last.  */
6529           && comp_template_args (TYPE_TI_ARGS (template_type),
6530                                  arglist))
6531         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6532
6533       /* If we already have this specialization, return it.  */
6534       elt.tmpl = gen_tmpl;
6535       elt.args = arglist;
6536       hash = hash_specialization (&elt);
6537       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6538                                                   &elt, hash);
6539
6540       if (entry)
6541         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6542
6543       is_dependent_type = uses_template_parms (arglist);
6544
6545       /* If the deduced arguments are invalid, then the binding
6546          failed.  */
6547       if (!is_dependent_type
6548           && check_instantiated_args (gen_tmpl,
6549                                       INNERMOST_TEMPLATE_ARGS (arglist),
6550                                       complain))
6551         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6552
6553       if (!is_dependent_type
6554           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6555           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6556           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6557         {
6558           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6559                                       DECL_NAME (gen_tmpl),
6560                                       /*tag_scope=*/ts_global);
6561           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6562         }
6563
6564       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6565                         complain, in_decl);
6566       if (!context)
6567         context = global_namespace;
6568
6569       /* Create the type.  */
6570       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6571         {
6572           if (!is_dependent_type)
6573             {
6574               set_current_access_from_decl (TYPE_NAME (template_type));
6575               t = start_enum (TYPE_IDENTIFIER (template_type),
6576                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6577                                       arglist, complain, in_decl),
6578                               SCOPED_ENUM_P (template_type));
6579             }
6580           else
6581             {
6582               /* We don't want to call start_enum for this type, since
6583                  the values for the enumeration constants may involve
6584                  template parameters.  And, no one should be interested
6585                  in the enumeration constants for such a type.  */
6586               t = cxx_make_type (ENUMERAL_TYPE);
6587               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6588             }
6589         }
6590       else
6591         {
6592           t = make_class_type (TREE_CODE (template_type));
6593           CLASSTYPE_DECLARED_CLASS (t)
6594             = CLASSTYPE_DECLARED_CLASS (template_type);
6595           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6596           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6597
6598           /* A local class.  Make sure the decl gets registered properly.  */
6599           if (context == current_function_decl)
6600             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6601
6602           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6603             /* This instantiation is another name for the primary
6604                template type. Set the TYPE_CANONICAL field
6605                appropriately. */
6606             TYPE_CANONICAL (t) = template_type;
6607           else if (any_template_arguments_need_structural_equality_p (arglist))
6608             /* Some of the template arguments require structural
6609                equality testing, so this template class requires
6610                structural equality testing. */
6611             SET_TYPE_STRUCTURAL_EQUALITY (t);
6612         }
6613
6614       /* If we called start_enum or pushtag above, this information
6615          will already be set up.  */
6616       if (!TYPE_NAME (t))
6617         {
6618           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6619
6620           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6621           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6622           DECL_SOURCE_LOCATION (type_decl)
6623             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6624         }
6625       else
6626         type_decl = TYPE_NAME (t);
6627
6628       TREE_PRIVATE (type_decl)
6629         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6630       TREE_PROTECTED (type_decl)
6631         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6632       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6633         {
6634           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6635           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6636         }
6637
6638       /* Let's consider the explicit specialization of a member
6639          of a class template specialization that is implicitely instantiated,
6640          e.g.:
6641              template<class T>
6642              struct S
6643              {
6644                template<class U> struct M {}; //#0
6645              };
6646
6647              template<>
6648              template<>
6649              struct S<int>::M<char> //#1
6650              {
6651                int i;
6652              };
6653         [temp.expl.spec]/4 says this is valid.
6654
6655         In this case, when we write:
6656         S<int>::M<char> m;
6657
6658         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6659         the one of #0.
6660
6661         When we encounter #1, we want to store the partial instantiation
6662         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6663
6664         For all cases other than this "explicit specialization of member of a
6665         class template", we just want to store the most general template into
6666         the CLASSTYPE_TI_TEMPLATE of M.
6667
6668         This case of "explicit specialization of member of a class template"
6669         only happens when:
6670         1/ the enclosing class is an instantiation of, and therefore not
6671         the same as, the context of the most general template, and
6672         2/ we aren't looking at the partial instantiation itself, i.e.
6673         the innermost arguments are not the same as the innermost parms of
6674         the most general template.
6675
6676         So it's only when 1/ and 2/ happens that we want to use the partial
6677         instantiation of the member template in lieu of its most general
6678         template.  */
6679
6680       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6681           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6682           /* the enclosing class must be an instantiation...  */
6683           && CLASS_TYPE_P (context)
6684           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6685         {
6686           tree partial_inst_args;
6687           TREE_VEC_LENGTH (arglist)--;
6688           ++processing_template_decl;
6689           partial_inst_args =
6690             tsubst (INNERMOST_TEMPLATE_ARGS
6691                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6692                     arglist, complain, NULL_TREE);
6693           --processing_template_decl;
6694           TREE_VEC_LENGTH (arglist)++;
6695           use_partial_inst_tmpl =
6696             /*...and we must not be looking at the partial instantiation
6697              itself. */
6698             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6699                                  partial_inst_args);
6700         }
6701
6702       if (!use_partial_inst_tmpl)
6703         /* This case is easy; there are no member templates involved.  */
6704         found = gen_tmpl;
6705       else
6706         {
6707           /* This is a full instantiation of a member template.  Find
6708              the partial instantiation of which this is an instance.  */
6709
6710           /* Temporarily reduce by one the number of levels in the ARGLIST
6711              so as to avoid comparing the last set of arguments.  */
6712           TREE_VEC_LENGTH (arglist)--;
6713           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6714           TREE_VEC_LENGTH (arglist)++;
6715           found = CLASSTYPE_TI_TEMPLATE (found);
6716         }
6717
6718       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6719
6720       elt.spec = t;
6721       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6722                                                        &elt, hash, INSERT);
6723       *slot = GGC_NEW (spec_entry);
6724       **slot = elt;
6725
6726       /* Note this use of the partial instantiation so we can check it
6727          later in maybe_process_partial_specialization.  */
6728       DECL_TEMPLATE_INSTANTIATIONS (templ)
6729         = tree_cons (arglist, t,
6730                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6731
6732       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6733         /* Now that the type has been registered on the instantiations
6734            list, we set up the enumerators.  Because the enumeration
6735            constants may involve the enumeration type itself, we make
6736            sure to register the type first, and then create the
6737            constants.  That way, doing tsubst_expr for the enumeration
6738            constants won't result in recursive calls here; we'll find
6739            the instantiation and exit above.  */
6740         tsubst_enum (template_type, t, arglist);
6741
6742       if (is_dependent_type)
6743         /* If the type makes use of template parameters, the
6744            code that generates debugging information will crash.  */
6745         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6746
6747       /* Possibly limit visibility based on template args.  */
6748       TREE_PUBLIC (type_decl) = 1;
6749       determine_visibility (type_decl);
6750
6751       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6752     }
6753   timevar_pop (TV_NAME_LOOKUP);
6754 }
6755 \f
6756 struct pair_fn_data
6757 {
6758   tree_fn_t fn;
6759   void *data;
6760   /* True when we should also visit template parameters that occur in
6761      non-deduced contexts.  */
6762   bool include_nondeduced_p;
6763   struct pointer_set_t *visited;
6764 };
6765
6766 /* Called from for_each_template_parm via walk_tree.  */
6767
6768 static tree
6769 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6770 {
6771   tree t = *tp;
6772   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6773   tree_fn_t fn = pfd->fn;
6774   void *data = pfd->data;
6775
6776   if (TYPE_P (t)
6777       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6778       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6779                                  pfd->include_nondeduced_p))
6780     return error_mark_node;
6781
6782   switch (TREE_CODE (t))
6783     {
6784     case RECORD_TYPE:
6785       if (TYPE_PTRMEMFUNC_P (t))
6786         break;
6787       /* Fall through.  */
6788
6789     case UNION_TYPE:
6790     case ENUMERAL_TYPE:
6791       if (!TYPE_TEMPLATE_INFO (t))
6792         *walk_subtrees = 0;
6793       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6794                                        fn, data, pfd->visited, 
6795                                        pfd->include_nondeduced_p))
6796         return error_mark_node;
6797       break;
6798
6799     case INTEGER_TYPE:
6800       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6801                                   fn, data, pfd->visited, 
6802                                   pfd->include_nondeduced_p)
6803           || for_each_template_parm (TYPE_MAX_VALUE (t),
6804                                      fn, data, pfd->visited,
6805                                      pfd->include_nondeduced_p))
6806         return error_mark_node;
6807       break;
6808
6809     case METHOD_TYPE:
6810       /* Since we're not going to walk subtrees, we have to do this
6811          explicitly here.  */
6812       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6813                                   pfd->visited, pfd->include_nondeduced_p))
6814         return error_mark_node;
6815       /* Fall through.  */
6816
6817     case FUNCTION_TYPE:
6818       /* Check the return type.  */
6819       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6820                                   pfd->include_nondeduced_p))
6821         return error_mark_node;
6822
6823       /* Check the parameter types.  Since default arguments are not
6824          instantiated until they are needed, the TYPE_ARG_TYPES may
6825          contain expressions that involve template parameters.  But,
6826          no-one should be looking at them yet.  And, once they're
6827          instantiated, they don't contain template parameters, so
6828          there's no point in looking at them then, either.  */
6829       {
6830         tree parm;
6831
6832         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6833           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6834                                       pfd->visited, pfd->include_nondeduced_p))
6835             return error_mark_node;
6836
6837         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6838            want walk_tree walking into them itself.  */
6839         *walk_subtrees = 0;
6840       }
6841       break;
6842
6843     case TYPEOF_TYPE:
6844       if (pfd->include_nondeduced_p
6845           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6846                                      pfd->visited, 
6847                                      pfd->include_nondeduced_p))
6848         return error_mark_node;
6849       break;
6850
6851     case FUNCTION_DECL:
6852     case VAR_DECL:
6853       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6854           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6855                                      pfd->visited, pfd->include_nondeduced_p))
6856         return error_mark_node;
6857       /* Fall through.  */
6858
6859     case PARM_DECL:
6860     case CONST_DECL:
6861       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6862           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6863                                      pfd->visited, pfd->include_nondeduced_p))
6864         return error_mark_node;
6865       if (DECL_CONTEXT (t)
6866           && pfd->include_nondeduced_p
6867           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6868                                      pfd->visited, pfd->include_nondeduced_p))
6869         return error_mark_node;
6870       break;
6871
6872     case BOUND_TEMPLATE_TEMPLATE_PARM:
6873       /* Record template parameters such as `T' inside `TT<T>'.  */
6874       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6875                                   pfd->include_nondeduced_p))
6876         return error_mark_node;
6877       /* Fall through.  */
6878
6879     case TEMPLATE_TEMPLATE_PARM:
6880     case TEMPLATE_TYPE_PARM:
6881     case TEMPLATE_PARM_INDEX:
6882       if (fn && (*fn)(t, data))
6883         return error_mark_node;
6884       else if (!fn)
6885         return error_mark_node;
6886       break;
6887
6888     case TEMPLATE_DECL:
6889       /* A template template parameter is encountered.  */
6890       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6891           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6892                                      pfd->include_nondeduced_p))
6893         return error_mark_node;
6894
6895       /* Already substituted template template parameter */
6896       *walk_subtrees = 0;
6897       break;
6898
6899     case TYPENAME_TYPE:
6900       if (!fn
6901           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6902                                      data, pfd->visited, 
6903                                      pfd->include_nondeduced_p))
6904         return error_mark_node;
6905       break;
6906
6907     case CONSTRUCTOR:
6908       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6909           && pfd->include_nondeduced_p
6910           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6911                                      (TREE_TYPE (t)), fn, data,
6912                                      pfd->visited, pfd->include_nondeduced_p))
6913         return error_mark_node;
6914       break;
6915
6916     case INDIRECT_REF:
6917     case COMPONENT_REF:
6918       /* If there's no type, then this thing must be some expression
6919          involving template parameters.  */
6920       if (!fn && !TREE_TYPE (t))
6921         return error_mark_node;
6922       break;
6923
6924     case MODOP_EXPR:
6925     case CAST_EXPR:
6926     case REINTERPRET_CAST_EXPR:
6927     case CONST_CAST_EXPR:
6928     case STATIC_CAST_EXPR:
6929     case DYNAMIC_CAST_EXPR:
6930     case ARROW_EXPR:
6931     case DOTSTAR_EXPR:
6932     case TYPEID_EXPR:
6933     case PSEUDO_DTOR_EXPR:
6934       if (!fn)
6935         return error_mark_node;
6936       break;
6937
6938     default:
6939       break;
6940     }
6941
6942   /* We didn't find any template parameters we liked.  */
6943   return NULL_TREE;
6944 }
6945
6946 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6947    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6948    call FN with the parameter and the DATA.
6949    If FN returns nonzero, the iteration is terminated, and
6950    for_each_template_parm returns 1.  Otherwise, the iteration
6951    continues.  If FN never returns a nonzero value, the value
6952    returned by for_each_template_parm is 0.  If FN is NULL, it is
6953    considered to be the function which always returns 1.
6954
6955    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6956    parameters that occur in non-deduced contexts.  When false, only
6957    visits those template parameters that can be deduced.  */
6958
6959 static int
6960 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6961                         struct pointer_set_t *visited,
6962                         bool include_nondeduced_p)
6963 {
6964   struct pair_fn_data pfd;
6965   int result;
6966
6967   /* Set up.  */
6968   pfd.fn = fn;
6969   pfd.data = data;
6970   pfd.include_nondeduced_p = include_nondeduced_p;
6971
6972   /* Walk the tree.  (Conceptually, we would like to walk without
6973      duplicates, but for_each_template_parm_r recursively calls
6974      for_each_template_parm, so we would need to reorganize a fair
6975      bit to use walk_tree_without_duplicates, so we keep our own
6976      visited list.)  */
6977   if (visited)
6978     pfd.visited = visited;
6979   else
6980     pfd.visited = pointer_set_create ();
6981   result = cp_walk_tree (&t,
6982                          for_each_template_parm_r,
6983                          &pfd,
6984                          pfd.visited) != NULL_TREE;
6985
6986   /* Clean up.  */
6987   if (!visited)
6988     {
6989       pointer_set_destroy (pfd.visited);
6990       pfd.visited = 0;
6991     }
6992
6993   return result;
6994 }
6995
6996 /* Returns true if T depends on any template parameter.  */
6997
6998 int
6999 uses_template_parms (tree t)
7000 {
7001   bool dependent_p;
7002   int saved_processing_template_decl;
7003
7004   saved_processing_template_decl = processing_template_decl;
7005   if (!saved_processing_template_decl)
7006     processing_template_decl = 1;
7007   if (TYPE_P (t))
7008     dependent_p = dependent_type_p (t);
7009   else if (TREE_CODE (t) == TREE_VEC)
7010     dependent_p = any_dependent_template_arguments_p (t);
7011   else if (TREE_CODE (t) == TREE_LIST)
7012     dependent_p = (uses_template_parms (TREE_VALUE (t))
7013                    || uses_template_parms (TREE_CHAIN (t)));
7014   else if (TREE_CODE (t) == TYPE_DECL)
7015     dependent_p = dependent_type_p (TREE_TYPE (t));
7016   else if (DECL_P (t)
7017            || EXPR_P (t)
7018            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7019            || TREE_CODE (t) == OVERLOAD
7020            || TREE_CODE (t) == BASELINK
7021            || TREE_CODE (t) == IDENTIFIER_NODE
7022            || TREE_CODE (t) == TRAIT_EXPR
7023            || TREE_CODE (t) == CONSTRUCTOR
7024            || CONSTANT_CLASS_P (t))
7025     dependent_p = (type_dependent_expression_p (t)
7026                    || value_dependent_expression_p (t));
7027   else
7028     {
7029       gcc_assert (t == error_mark_node);
7030       dependent_p = false;
7031     }
7032
7033   processing_template_decl = saved_processing_template_decl;
7034
7035   return dependent_p;
7036 }
7037
7038 /* Returns true if T depends on any template parameter with level LEVEL.  */
7039
7040 int
7041 uses_template_parms_level (tree t, int level)
7042 {
7043   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7044                                  /*include_nondeduced_p=*/true);
7045 }
7046
7047 static int tinst_depth;
7048 extern int max_tinst_depth;
7049 #ifdef GATHER_STATISTICS
7050 int depth_reached;
7051 #endif
7052 static int tinst_level_tick;
7053 static int last_template_error_tick;
7054
7055 /* We're starting to instantiate D; record the template instantiation context
7056    for diagnostics and to restore it later.  */
7057
7058 int
7059 push_tinst_level (tree d)
7060 {
7061   struct tinst_level *new_level;
7062
7063   if (tinst_depth >= max_tinst_depth)
7064     {
7065       /* If the instantiation in question still has unbound template parms,
7066          we don't really care if we can't instantiate it, so just return.
7067          This happens with base instantiation for implicit `typename'.  */
7068       if (uses_template_parms (d))
7069         return 0;
7070
7071       last_template_error_tick = tinst_level_tick;
7072       error ("template instantiation depth exceeds maximum of %d (use "
7073              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7074              max_tinst_depth, d);
7075
7076       print_instantiation_context ();
7077
7078       return 0;
7079     }
7080
7081   new_level = GGC_NEW (struct tinst_level);
7082   new_level->decl = d;
7083   new_level->locus = input_location;
7084   new_level->in_system_header_p = in_system_header;
7085   new_level->next = current_tinst_level;
7086   current_tinst_level = new_level;
7087
7088   ++tinst_depth;
7089 #ifdef GATHER_STATISTICS
7090   if (tinst_depth > depth_reached)
7091     depth_reached = tinst_depth;
7092 #endif
7093
7094   ++tinst_level_tick;
7095   return 1;
7096 }
7097
7098 /* We're done instantiating this template; return to the instantiation
7099    context.  */
7100
7101 void
7102 pop_tinst_level (void)
7103 {
7104   /* Restore the filename and line number stashed away when we started
7105      this instantiation.  */
7106   input_location = current_tinst_level->locus;
7107   current_tinst_level = current_tinst_level->next;
7108   --tinst_depth;
7109   ++tinst_level_tick;
7110 }
7111
7112 /* We're instantiating a deferred template; restore the template
7113    instantiation context in which the instantiation was requested, which
7114    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7115
7116 static tree
7117 reopen_tinst_level (struct tinst_level *level)
7118 {
7119   struct tinst_level *t;
7120
7121   tinst_depth = 0;
7122   for (t = level; t; t = t->next)
7123     ++tinst_depth;
7124
7125   current_tinst_level = level;
7126   pop_tinst_level ();
7127   return level->decl;
7128 }
7129
7130 /* Returns the TINST_LEVEL which gives the original instantiation
7131    context.  */
7132
7133 struct tinst_level *
7134 outermost_tinst_level (void)
7135 {
7136   struct tinst_level *level = current_tinst_level;
7137   if (level)
7138     while (level->next)
7139       level = level->next;
7140   return level;
7141 }
7142
7143 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7144
7145 bool
7146 parameter_of_template_p (tree parm, tree templ)
7147 {
7148   tree parms;
7149   int i;
7150
7151   if (!parm || !templ)
7152     return false;
7153
7154   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7155   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7156
7157   parms = DECL_TEMPLATE_PARMS (templ);
7158   parms = INNERMOST_TEMPLATE_PARMS (parms);
7159
7160   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7161     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7162       return true;
7163
7164   return false;
7165 }
7166
7167 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7168    vector of template arguments, as for tsubst.
7169
7170    Returns an appropriate tsubst'd friend declaration.  */
7171
7172 static tree
7173 tsubst_friend_function (tree decl, tree args)
7174 {
7175   tree new_friend;
7176
7177   if (TREE_CODE (decl) == FUNCTION_DECL
7178       && DECL_TEMPLATE_INSTANTIATION (decl)
7179       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7180     /* This was a friend declared with an explicit template
7181        argument list, e.g.:
7182
7183        friend void f<>(T);
7184
7185        to indicate that f was a template instantiation, not a new
7186        function declaration.  Now, we have to figure out what
7187        instantiation of what template.  */
7188     {
7189       tree template_id, arglist, fns;
7190       tree new_args;
7191       tree tmpl;
7192       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7193
7194       /* Friend functions are looked up in the containing namespace scope.
7195          We must enter that scope, to avoid finding member functions of the
7196          current class with same name.  */
7197       push_nested_namespace (ns);
7198       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7199                          tf_warning_or_error, NULL_TREE,
7200                          /*integral_constant_expression_p=*/false);
7201       pop_nested_namespace (ns);
7202       arglist = tsubst (DECL_TI_ARGS (decl), args,
7203                         tf_warning_or_error, NULL_TREE);
7204       template_id = lookup_template_function (fns, arglist);
7205
7206       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7207       tmpl = determine_specialization (template_id, new_friend,
7208                                        &new_args,
7209                                        /*need_member_template=*/0,
7210                                        TREE_VEC_LENGTH (args),
7211                                        tsk_none);
7212       return instantiate_template (tmpl, new_args, tf_error);
7213     }
7214
7215   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7216
7217   /* The NEW_FRIEND will look like an instantiation, to the
7218      compiler, but is not an instantiation from the point of view of
7219      the language.  For example, we might have had:
7220
7221      template <class T> struct S {
7222        template <class U> friend void f(T, U);
7223      };
7224
7225      Then, in S<int>, template <class U> void f(int, U) is not an
7226      instantiation of anything.  */
7227   if (new_friend == error_mark_node)
7228     return error_mark_node;
7229
7230   DECL_USE_TEMPLATE (new_friend) = 0;
7231   if (TREE_CODE (decl) == TEMPLATE_DECL)
7232     {
7233       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7234       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7235         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7236     }
7237
7238   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7239      is not a template instantiation and should not be mangled like
7240      one.  Therefore, we forget the mangling here; we'll recompute it
7241      later if we need it.  */
7242   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7243     {
7244       SET_DECL_RTL (new_friend, NULL_RTX);
7245       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7246     }
7247
7248   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7249     {
7250       tree old_decl;
7251       tree new_friend_template_info;
7252       tree new_friend_result_template_info;
7253       tree ns;
7254       int  new_friend_is_defn;
7255
7256       /* We must save some information from NEW_FRIEND before calling
7257          duplicate decls since that function will free NEW_FRIEND if
7258          possible.  */
7259       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7260       new_friend_is_defn =
7261             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7262                            (template_for_substitution (new_friend)))
7263              != NULL_TREE);
7264       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7265         {
7266           /* This declaration is a `primary' template.  */
7267           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7268
7269           new_friend_result_template_info
7270             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7271         }
7272       else
7273         new_friend_result_template_info = NULL_TREE;
7274
7275       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7276       if (new_friend_is_defn)
7277         DECL_INITIAL (new_friend) = error_mark_node;
7278
7279       /* Inside pushdecl_namespace_level, we will push into the
7280          current namespace. However, the friend function should go
7281          into the namespace of the template.  */
7282       ns = decl_namespace_context (new_friend);
7283       push_nested_namespace (ns);
7284       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7285       pop_nested_namespace (ns);
7286
7287       if (old_decl == error_mark_node)
7288         return error_mark_node;
7289
7290       if (old_decl != new_friend)
7291         {
7292           /* This new friend declaration matched an existing
7293              declaration.  For example, given:
7294
7295                template <class T> void f(T);
7296                template <class U> class C {
7297                  template <class T> friend void f(T) {}
7298                };
7299
7300              the friend declaration actually provides the definition
7301              of `f', once C has been instantiated for some type.  So,
7302              old_decl will be the out-of-class template declaration,
7303              while new_friend is the in-class definition.
7304
7305              But, if `f' was called before this point, the
7306              instantiation of `f' will have DECL_TI_ARGS corresponding
7307              to `T' but not to `U', references to which might appear
7308              in the definition of `f'.  Previously, the most general
7309              template for an instantiation of `f' was the out-of-class
7310              version; now it is the in-class version.  Therefore, we
7311              run through all specialization of `f', adding to their
7312              DECL_TI_ARGS appropriately.  In particular, they need a
7313              new set of outer arguments, corresponding to the
7314              arguments for this class instantiation.
7315
7316              The same situation can arise with something like this:
7317
7318                friend void f(int);
7319                template <class T> class C {
7320                  friend void f(T) {}
7321                };
7322
7323              when `C<int>' is instantiated.  Now, `f(int)' is defined
7324              in the class.  */
7325
7326           if (!new_friend_is_defn)
7327             /* On the other hand, if the in-class declaration does
7328                *not* provide a definition, then we don't want to alter
7329                existing definitions.  We can just leave everything
7330                alone.  */
7331             ;
7332           else
7333             {
7334               tree new_template = TI_TEMPLATE (new_friend_template_info);
7335               tree new_args = TI_ARGS (new_friend_template_info);
7336
7337               /* Overwrite whatever template info was there before, if
7338                  any, with the new template information pertaining to
7339                  the declaration.  */
7340               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7341
7342               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7343                 {
7344                   /* We should have called reregister_specialization in
7345                      duplicate_decls.  */
7346                   gcc_assert (retrieve_specialization (new_template,
7347                                                        new_args, 0)
7348                               == old_decl);
7349
7350                   /* Instantiate it if the global has already been used.  */
7351                   if (DECL_ODR_USED (old_decl))
7352                     instantiate_decl (old_decl, /*defer_ok=*/true,
7353                                       /*expl_inst_class_mem_p=*/false);
7354                 }
7355               else
7356                 {
7357                   tree t;
7358
7359                   /* Indicate that the old function template is a partial
7360                      instantiation.  */
7361                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7362                     = new_friend_result_template_info;
7363
7364                   gcc_assert (new_template
7365                               == most_general_template (new_template));
7366                   gcc_assert (new_template != old_decl);
7367
7368                   /* Reassign any specializations already in the hash table
7369                      to the new more general template, and add the
7370                      additional template args.  */
7371                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7372                        t != NULL_TREE;
7373                        t = TREE_CHAIN (t))
7374                     {
7375                       tree spec = TREE_VALUE (t);
7376                       spec_entry elt;
7377
7378                       elt.tmpl = old_decl;
7379                       elt.args = DECL_TI_ARGS (spec);
7380                       elt.spec = NULL_TREE;
7381
7382                       htab_remove_elt (decl_specializations, &elt);
7383
7384                       DECL_TI_ARGS (spec)
7385                         = add_outermost_template_args (new_args,
7386                                                        DECL_TI_ARGS (spec));
7387
7388                       register_specialization
7389                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7390
7391                     }
7392                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7393                 }
7394             }
7395
7396           /* The information from NEW_FRIEND has been merged into OLD_DECL
7397              by duplicate_decls.  */
7398           new_friend = old_decl;
7399         }
7400     }
7401   else
7402     {
7403       tree context = DECL_CONTEXT (new_friend);
7404       bool dependent_p;
7405
7406       /* In the code
7407            template <class T> class C {
7408              template <class U> friend void C1<U>::f (); // case 1
7409              friend void C2<T>::f ();                    // case 2
7410            };
7411          we only need to make sure CONTEXT is a complete type for
7412          case 2.  To distinguish between the two cases, we note that
7413          CONTEXT of case 1 remains dependent type after tsubst while
7414          this isn't true for case 2.  */
7415       ++processing_template_decl;
7416       dependent_p = dependent_type_p (context);
7417       --processing_template_decl;
7418
7419       if (!dependent_p
7420           && !complete_type_or_else (context, NULL_TREE))
7421         return error_mark_node;
7422
7423       if (COMPLETE_TYPE_P (context))
7424         {
7425           /* Check to see that the declaration is really present, and,
7426              possibly obtain an improved declaration.  */
7427           tree fn = check_classfn (context,
7428                                    new_friend, NULL_TREE);
7429
7430           if (fn)
7431             new_friend = fn;
7432         }
7433     }
7434
7435   return new_friend;
7436 }
7437
7438 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7439    template arguments, as for tsubst.
7440
7441    Returns an appropriate tsubst'd friend type or error_mark_node on
7442    failure.  */
7443
7444 static tree
7445 tsubst_friend_class (tree friend_tmpl, tree args)
7446 {
7447   tree friend_type;
7448   tree tmpl;
7449   tree context;
7450
7451   context = DECL_CONTEXT (friend_tmpl);
7452
7453   if (context)
7454     {
7455       if (TREE_CODE (context) == NAMESPACE_DECL)
7456         push_nested_namespace (context);
7457       else
7458         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7459     }
7460
7461   /* Look for a class template declaration.  We look for hidden names
7462      because two friend declarations of the same template are the
7463      same.  For example, in:
7464
7465        struct A { 
7466          template <typename> friend class F;
7467        };
7468        template <typename> struct B { 
7469          template <typename> friend class F;
7470        };
7471
7472      both F templates are the same.  */
7473   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7474                            /*block_p=*/true, 0, 
7475                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7476
7477   /* But, if we don't find one, it might be because we're in a
7478      situation like this:
7479
7480        template <class T>
7481        struct S {
7482          template <class U>
7483          friend struct S;
7484        };
7485
7486      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7487      for `S<int>', not the TEMPLATE_DECL.  */
7488   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7489     {
7490       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7491       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7492     }
7493
7494   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7495     {
7496       /* The friend template has already been declared.  Just
7497          check to see that the declarations match, and install any new
7498          default parameters.  We must tsubst the default parameters,
7499          of course.  We only need the innermost template parameters
7500          because that is all that redeclare_class_template will look
7501          at.  */
7502       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7503           > TMPL_ARGS_DEPTH (args))
7504         {
7505           tree parms;
7506           location_t saved_input_location;
7507           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7508                                          args, tf_warning_or_error);
7509
7510           saved_input_location = input_location;
7511           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7512           redeclare_class_template (TREE_TYPE (tmpl), parms);
7513           input_location = saved_input_location;
7514           
7515         }
7516
7517       friend_type = TREE_TYPE (tmpl);
7518     }
7519   else
7520     {
7521       /* The friend template has not already been declared.  In this
7522          case, the instantiation of the template class will cause the
7523          injection of this template into the global scope.  */
7524       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7525       if (tmpl == error_mark_node)
7526         return error_mark_node;
7527
7528       /* The new TMPL is not an instantiation of anything, so we
7529          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7530          the new type because that is supposed to be the corresponding
7531          template decl, i.e., TMPL.  */
7532       DECL_USE_TEMPLATE (tmpl) = 0;
7533       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7534       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7535       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7536         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7537
7538       /* Inject this template into the global scope.  */
7539       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7540     }
7541
7542   if (context)
7543     {
7544       if (TREE_CODE (context) == NAMESPACE_DECL)
7545         pop_nested_namespace (context);
7546       else
7547         pop_nested_class ();
7548     }
7549
7550   return friend_type;
7551 }
7552
7553 /* Returns zero if TYPE cannot be completed later due to circularity.
7554    Otherwise returns one.  */
7555
7556 static int
7557 can_complete_type_without_circularity (tree type)
7558 {
7559   if (type == NULL_TREE || type == error_mark_node)
7560     return 0;
7561   else if (COMPLETE_TYPE_P (type))
7562     return 1;
7563   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7564     return can_complete_type_without_circularity (TREE_TYPE (type));
7565   else if (CLASS_TYPE_P (type)
7566            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7567     return 0;
7568   else
7569     return 1;
7570 }
7571
7572 /* Apply any attributes which had to be deferred until instantiation
7573    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7574    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7575
7576 static void
7577 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7578                                 tree args, tsubst_flags_t complain, tree in_decl)
7579 {
7580   tree last_dep = NULL_TREE;
7581   tree t;
7582   tree *p;
7583
7584   for (t = attributes; t; t = TREE_CHAIN (t))
7585     if (ATTR_IS_DEPENDENT (t))
7586       {
7587         last_dep = t;
7588         attributes = copy_list (attributes);
7589         break;
7590       }
7591
7592   if (DECL_P (*decl_p))
7593     {
7594       if (TREE_TYPE (*decl_p) == error_mark_node)
7595         return;
7596       p = &DECL_ATTRIBUTES (*decl_p);
7597     }
7598   else
7599     p = &TYPE_ATTRIBUTES (*decl_p);
7600
7601   if (last_dep)
7602     {
7603       tree late_attrs = NULL_TREE;
7604       tree *q = &late_attrs;
7605
7606       for (*p = attributes; *p; )
7607         {
7608           t = *p;
7609           if (ATTR_IS_DEPENDENT (t))
7610             {
7611               *p = TREE_CHAIN (t);
7612               TREE_CHAIN (t) = NULL_TREE;
7613               /* If the first attribute argument is an identifier, don't
7614                  pass it through tsubst.  Attributes like mode, format,
7615                  cleanup and several target specific attributes expect it
7616                  unmodified.  */
7617               if (TREE_VALUE (t)
7618                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7619                   && TREE_VALUE (TREE_VALUE (t))
7620                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7621                       == IDENTIFIER_NODE))
7622                 {
7623                   tree chain
7624                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7625                                    in_decl,
7626                                    /*integral_constant_expression_p=*/false);
7627                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7628                     TREE_VALUE (t)
7629                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7630                                    chain);
7631                 }
7632               else
7633                 TREE_VALUE (t)
7634                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7635                                  /*integral_constant_expression_p=*/false);
7636               *q = t;
7637               q = &TREE_CHAIN (t);
7638             }
7639           else
7640             p = &TREE_CHAIN (t);
7641         }
7642
7643       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7644     }
7645 }
7646
7647 /* Perform (or defer) access check for typedefs that were referenced
7648    from within the template TMPL code.
7649    This is a subroutine of instantiate_template and instantiate_class_template.
7650    TMPL is the template to consider and TARGS is the list of arguments of
7651    that template.  */
7652
7653 static void
7654 perform_typedefs_access_check (tree tmpl, tree targs)
7655 {
7656   location_t saved_location;
7657   int i;
7658   qualified_typedef_usage_t *iter;
7659
7660   if (!tmpl
7661       || (!CLASS_TYPE_P (tmpl)
7662           && TREE_CODE (tmpl) != FUNCTION_DECL))
7663     return;
7664
7665   saved_location = input_location;
7666   for (i = 0;
7667        VEC_iterate (qualified_typedef_usage_t,
7668                     get_types_needing_access_check (tmpl),
7669                     i, iter);
7670         ++i)
7671     {
7672       tree type_decl = iter->typedef_decl;
7673       tree type_scope = iter->context;
7674
7675       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7676         continue;
7677
7678       if (uses_template_parms (type_decl))
7679         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7680       if (uses_template_parms (type_scope))
7681         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7682
7683       /* Make access check error messages point to the location
7684          of the use of the typedef.  */
7685       input_location = iter->locus;
7686       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7687                                      type_decl, type_decl);
7688     }
7689     input_location = saved_location;
7690 }
7691
7692 tree
7693 instantiate_class_template (tree type)
7694 {
7695   tree templ, args, pattern, t, member;
7696   tree typedecl;
7697   tree pbinfo;
7698   tree base_list;
7699   unsigned int saved_maximum_field_alignment;
7700
7701   if (type == error_mark_node)
7702     return error_mark_node;
7703
7704   if (TYPE_BEING_DEFINED (type)
7705       || COMPLETE_TYPE_P (type)
7706       || uses_template_parms (type))
7707     return type;
7708
7709   /* Figure out which template is being instantiated.  */
7710   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7711   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7712
7713   /* Determine what specialization of the original template to
7714      instantiate.  */
7715   t = most_specialized_class (type, templ);
7716   if (t == error_mark_node)
7717     {
7718       TYPE_BEING_DEFINED (type) = 1;
7719       return error_mark_node;
7720     }
7721   else if (t)
7722     {
7723       /* This TYPE is actually an instantiation of a partial
7724          specialization.  We replace the innermost set of ARGS with
7725          the arguments appropriate for substitution.  For example,
7726          given:
7727
7728            template <class T> struct S {};
7729            template <class T> struct S<T*> {};
7730
7731          and supposing that we are instantiating S<int*>, ARGS will
7732          presently be {int*} -- but we need {int}.  */
7733       pattern = TREE_TYPE (t);
7734       args = TREE_PURPOSE (t);
7735     }
7736   else
7737     {
7738       pattern = TREE_TYPE (templ);
7739       args = CLASSTYPE_TI_ARGS (type);
7740     }
7741
7742   /* If the template we're instantiating is incomplete, then clearly
7743      there's nothing we can do.  */
7744   if (!COMPLETE_TYPE_P (pattern))
7745     return type;
7746
7747   /* If we've recursively instantiated too many templates, stop.  */
7748   if (! push_tinst_level (type))
7749     return type;
7750
7751   /* Now we're really doing the instantiation.  Mark the type as in
7752      the process of being defined.  */
7753   TYPE_BEING_DEFINED (type) = 1;
7754
7755   /* We may be in the middle of deferred access check.  Disable
7756      it now.  */
7757   push_deferring_access_checks (dk_no_deferred);
7758
7759   push_to_top_level ();
7760   /* Use #pragma pack from the template context.  */
7761   saved_maximum_field_alignment = maximum_field_alignment;
7762   maximum_field_alignment = TYPE_PRECISION (pattern);
7763
7764   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7765
7766   /* Set the input location to the most specialized template definition.
7767      This is needed if tsubsting causes an error.  */
7768   typedecl = TYPE_MAIN_DECL (pattern);
7769   input_location = DECL_SOURCE_LOCATION (typedecl);
7770
7771   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7772   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7773   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7774   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7775   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7776   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7777   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7778   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7779   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7780   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7781   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7782   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7783   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7784   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7785   if (ANON_AGGR_TYPE_P (pattern))
7786     SET_ANON_AGGR_TYPE_P (type);
7787   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7788     {
7789       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7790       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7791     }
7792
7793   pbinfo = TYPE_BINFO (pattern);
7794
7795   /* We should never instantiate a nested class before its enclosing
7796      class; we need to look up the nested class by name before we can
7797      instantiate it, and that lookup should instantiate the enclosing
7798      class.  */
7799   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7800               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7801               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7802
7803   base_list = NULL_TREE;
7804   if (BINFO_N_BASE_BINFOS (pbinfo))
7805     {
7806       tree pbase_binfo;
7807       tree context = TYPE_CONTEXT (type);
7808       tree pushed_scope;
7809       int i;
7810
7811       /* We must enter the scope containing the type, as that is where
7812          the accessibility of types named in dependent bases are
7813          looked up from.  */
7814       pushed_scope = push_scope (context ? context : global_namespace);
7815
7816       /* Substitute into each of the bases to determine the actual
7817          basetypes.  */
7818       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7819         {
7820           tree base;
7821           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7822           tree expanded_bases = NULL_TREE;
7823           int idx, len = 1;
7824
7825           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7826             {
7827               expanded_bases = 
7828                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7829                                        args, tf_error, NULL_TREE);
7830               if (expanded_bases == error_mark_node)
7831                 continue;
7832
7833               len = TREE_VEC_LENGTH (expanded_bases);
7834             }
7835
7836           for (idx = 0; idx < len; idx++)
7837             {
7838               if (expanded_bases)
7839                 /* Extract the already-expanded base class.  */
7840                 base = TREE_VEC_ELT (expanded_bases, idx);
7841               else
7842                 /* Substitute to figure out the base class.  */
7843                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7844                                NULL_TREE);
7845
7846               if (base == error_mark_node)
7847                 continue;
7848
7849               base_list = tree_cons (access, base, base_list);
7850               if (BINFO_VIRTUAL_P (pbase_binfo))
7851                 TREE_TYPE (base_list) = integer_type_node;
7852             }
7853         }
7854
7855       /* The list is now in reverse order; correct that.  */
7856       base_list = nreverse (base_list);
7857
7858       if (pushed_scope)
7859         pop_scope (pushed_scope);
7860     }
7861   /* Now call xref_basetypes to set up all the base-class
7862      information.  */
7863   xref_basetypes (type, base_list);
7864
7865   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7866                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7867                                   args, tf_error, NULL_TREE);
7868
7869   /* Now that our base classes are set up, enter the scope of the
7870      class, so that name lookups into base classes, etc. will work
7871      correctly.  This is precisely analogous to what we do in
7872      begin_class_definition when defining an ordinary non-template
7873      class, except we also need to push the enclosing classes.  */
7874   push_nested_class (type);
7875
7876   /* Now members are processed in the order of declaration.  */
7877   for (member = CLASSTYPE_DECL_LIST (pattern);
7878        member; member = TREE_CHAIN (member))
7879     {
7880       tree t = TREE_VALUE (member);
7881
7882       if (TREE_PURPOSE (member))
7883         {
7884           if (TYPE_P (t))
7885             {
7886               /* Build new CLASSTYPE_NESTED_UTDS.  */
7887
7888               tree newtag;
7889               bool class_template_p;
7890
7891               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7892                                   && TYPE_LANG_SPECIFIC (t)
7893                                   && CLASSTYPE_IS_TEMPLATE (t));
7894               /* If the member is a class template, then -- even after
7895                  substitution -- there may be dependent types in the
7896                  template argument list for the class.  We increment
7897                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7898                  that function will assume that no types are dependent
7899                  when outside of a template.  */
7900               if (class_template_p)
7901                 ++processing_template_decl;
7902               newtag = tsubst (t, args, tf_error, NULL_TREE);
7903               if (class_template_p)
7904                 --processing_template_decl;
7905               if (newtag == error_mark_node)
7906                 continue;
7907
7908               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7909                 {
7910                   tree name = TYPE_IDENTIFIER (t);
7911
7912                   if (class_template_p)
7913                     /* Unfortunately, lookup_template_class sets
7914                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7915                        instantiation (i.e., for the type of a member
7916                        template class nested within a template class.)
7917                        This behavior is required for
7918                        maybe_process_partial_specialization to work
7919                        correctly, but is not accurate in this case;
7920                        the TAG is not an instantiation of anything.
7921                        (The corresponding TEMPLATE_DECL is an
7922                        instantiation, but the TYPE is not.) */
7923                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7924
7925                   /* Now, we call pushtag to put this NEWTAG into the scope of
7926                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7927                      pushtag calling push_template_decl.  We don't have to do
7928                      this for enums because it will already have been done in
7929                      tsubst_enum.  */
7930                   if (name)
7931                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7932                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7933                 }
7934             }
7935           else if (TREE_CODE (t) == FUNCTION_DECL
7936                    || DECL_FUNCTION_TEMPLATE_P (t))
7937             {
7938               /* Build new TYPE_METHODS.  */
7939               tree r;
7940
7941               if (TREE_CODE (t) == TEMPLATE_DECL)
7942                 ++processing_template_decl;
7943               r = tsubst (t, args, tf_error, NULL_TREE);
7944               if (TREE_CODE (t) == TEMPLATE_DECL)
7945                 --processing_template_decl;
7946               set_current_access_from_decl (r);
7947               finish_member_declaration (r);
7948             }
7949           else
7950             {
7951               /* Build new TYPE_FIELDS.  */
7952               if (TREE_CODE (t) == STATIC_ASSERT)
7953                 {
7954                   tree condition = 
7955                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7956                                  tf_warning_or_error, NULL_TREE,
7957                                  /*integral_constant_expression_p=*/true);
7958                   finish_static_assert (condition,
7959                                         STATIC_ASSERT_MESSAGE (t), 
7960                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7961                                         /*member_p=*/true);
7962                 }
7963               else if (TREE_CODE (t) != CONST_DECL)
7964                 {
7965                   tree r;
7966
7967                   /* The file and line for this declaration, to
7968                      assist in error message reporting.  Since we
7969                      called push_tinst_level above, we don't need to
7970                      restore these.  */
7971                   input_location = DECL_SOURCE_LOCATION (t);
7972
7973                   if (TREE_CODE (t) == TEMPLATE_DECL)
7974                     ++processing_template_decl;
7975                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7976                   if (TREE_CODE (t) == TEMPLATE_DECL)
7977                     --processing_template_decl;
7978                   if (TREE_CODE (r) == VAR_DECL)
7979                     {
7980                       /* In [temp.inst]:
7981
7982                            [t]he initialization (and any associated
7983                            side-effects) of a static data member does
7984                            not occur unless the static data member is
7985                            itself used in a way that requires the
7986                            definition of the static data member to
7987                            exist.
7988
7989                          Therefore, we do not substitute into the
7990                          initialized for the static data member here.  */
7991                       finish_static_data_member_decl
7992                         (r,
7993                          /*init=*/NULL_TREE,
7994                          /*init_const_expr_p=*/false,
7995                          /*asmspec_tree=*/NULL_TREE,
7996                          /*flags=*/0);
7997                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7998                         check_static_variable_definition (r, TREE_TYPE (r));
7999                     }
8000                   else if (TREE_CODE (r) == FIELD_DECL)
8001                     {
8002                       /* Determine whether R has a valid type and can be
8003                          completed later.  If R is invalid, then it is
8004                          replaced by error_mark_node so that it will not be
8005                          added to TYPE_FIELDS.  */
8006                       tree rtype = TREE_TYPE (r);
8007                       if (can_complete_type_without_circularity (rtype))
8008                         complete_type (rtype);
8009
8010                       if (!COMPLETE_TYPE_P (rtype))
8011                         {
8012                           cxx_incomplete_type_error (r, rtype);
8013                           r = error_mark_node;
8014                         }
8015                     }
8016
8017                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8018                      such a thing will already have been added to the field
8019                      list by tsubst_enum in finish_member_declaration in the
8020                      CLASSTYPE_NESTED_UTDS case above.  */
8021                   if (!(TREE_CODE (r) == TYPE_DECL
8022                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8023                         && DECL_ARTIFICIAL (r)))
8024                     {
8025                       set_current_access_from_decl (r);
8026                       finish_member_declaration (r);
8027                     }
8028                 }
8029             }
8030         }
8031       else
8032         {
8033           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8034             {
8035               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8036
8037               tree friend_type = t;
8038               bool adjust_processing_template_decl = false;
8039
8040               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8041                 {
8042                   /* template <class T> friend class C;  */
8043                   friend_type = tsubst_friend_class (friend_type, args);
8044                   adjust_processing_template_decl = true;
8045                 }
8046               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8047                 {
8048                   /* template <class T> friend class C::D;  */
8049                   friend_type = tsubst (friend_type, args,
8050                                         tf_warning_or_error, NULL_TREE);
8051                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8052                     friend_type = TREE_TYPE (friend_type);
8053                   adjust_processing_template_decl = true;
8054                 }
8055               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8056                 {
8057                   /* This could be either
8058
8059                        friend class T::C;
8060
8061                      when dependent_type_p is false or
8062
8063                        template <class U> friend class T::C;
8064
8065                      otherwise.  */
8066                   friend_type = tsubst (friend_type, args,
8067                                         tf_warning_or_error, NULL_TREE);
8068                   /* Bump processing_template_decl for correct
8069                      dependent_type_p calculation.  */
8070                   ++processing_template_decl;
8071                   if (dependent_type_p (friend_type))
8072                     adjust_processing_template_decl = true;
8073                   --processing_template_decl;
8074                 }
8075               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8076                        && hidden_name_p (TYPE_NAME (friend_type)))
8077                 {
8078                   /* friend class C;
8079
8080                      where C hasn't been declared yet.  Let's lookup name
8081                      from namespace scope directly, bypassing any name that
8082                      come from dependent base class.  */
8083                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8084
8085                   /* The call to xref_tag_from_type does injection for friend
8086                      classes.  */
8087                   push_nested_namespace (ns);
8088                   friend_type =
8089                     xref_tag_from_type (friend_type, NULL_TREE,
8090                                         /*tag_scope=*/ts_current);
8091                   pop_nested_namespace (ns);
8092                 }
8093               else if (uses_template_parms (friend_type))
8094                 /* friend class C<T>;  */
8095                 friend_type = tsubst (friend_type, args,
8096                                       tf_warning_or_error, NULL_TREE);
8097               /* Otherwise it's
8098
8099                    friend class C;
8100
8101                  where C is already declared or
8102
8103                    friend class C<int>;
8104
8105                  We don't have to do anything in these cases.  */
8106
8107               if (adjust_processing_template_decl)
8108                 /* Trick make_friend_class into realizing that the friend
8109                    we're adding is a template, not an ordinary class.  It's
8110                    important that we use make_friend_class since it will
8111                    perform some error-checking and output cross-reference
8112                    information.  */
8113                 ++processing_template_decl;
8114
8115               if (friend_type != error_mark_node)
8116                 make_friend_class (type, friend_type, /*complain=*/false);
8117
8118               if (adjust_processing_template_decl)
8119                 --processing_template_decl;
8120             }
8121           else
8122             {
8123               /* Build new DECL_FRIENDLIST.  */
8124               tree r;
8125
8126               /* The file and line for this declaration, to
8127                  assist in error message reporting.  Since we
8128                  called push_tinst_level above, we don't need to
8129                  restore these.  */
8130               input_location = DECL_SOURCE_LOCATION (t);
8131
8132               if (TREE_CODE (t) == TEMPLATE_DECL)
8133                 {
8134                   ++processing_template_decl;
8135                   push_deferring_access_checks (dk_no_check);
8136                 }
8137
8138               r = tsubst_friend_function (t, args);
8139               add_friend (type, r, /*complain=*/false);
8140               if (TREE_CODE (t) == TEMPLATE_DECL)
8141                 {
8142                   pop_deferring_access_checks ();
8143                   --processing_template_decl;
8144                 }
8145             }
8146         }
8147     }
8148
8149   /* Set the file and line number information to whatever is given for
8150      the class itself.  This puts error messages involving generated
8151      implicit functions at a predictable point, and the same point
8152      that would be used for non-template classes.  */
8153   input_location = DECL_SOURCE_LOCATION (typedecl);
8154
8155   unreverse_member_declarations (type);
8156   finish_struct_1 (type);
8157   TYPE_BEING_DEFINED (type) = 0;
8158
8159   /* Now that the class is complete, instantiate default arguments for
8160      any member functions.  We don't do this earlier because the
8161      default arguments may reference members of the class.  */
8162   if (!PRIMARY_TEMPLATE_P (templ))
8163     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8164       if (TREE_CODE (t) == FUNCTION_DECL
8165           /* Implicitly generated member functions will not have template
8166              information; they are not instantiations, but instead are
8167              created "fresh" for each instantiation.  */
8168           && DECL_TEMPLATE_INFO (t))
8169         tsubst_default_arguments (t);
8170
8171   /* Some typedefs referenced from within the template code need to be access
8172      checked at template instantiation time, i.e now. These types were
8173      added to the template at parsing time. Let's get those and perform
8174      the access checks then.  */
8175   perform_typedefs_access_check (pattern, args);
8176   perform_deferred_access_checks ();
8177   pop_nested_class ();
8178   maximum_field_alignment = saved_maximum_field_alignment;
8179   pop_from_top_level ();
8180   pop_deferring_access_checks ();
8181   pop_tinst_level ();
8182
8183   /* The vtable for a template class can be emitted in any translation
8184      unit in which the class is instantiated.  When there is no key
8185      method, however, finish_struct_1 will already have added TYPE to
8186      the keyed_classes list.  */
8187   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8188     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8189
8190   return type;
8191 }
8192
8193 static tree
8194 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8195 {
8196   tree r;
8197
8198   if (!t)
8199     r = t;
8200   else if (TYPE_P (t))
8201     r = tsubst (t, args, complain, in_decl);
8202   else
8203     {
8204       r = tsubst_expr (t, args, complain, in_decl,
8205                        /*integral_constant_expression_p=*/true);
8206       r = fold_non_dependent_expr (r);
8207     }
8208   return r;
8209 }
8210
8211 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8212    NONTYPE_ARGUMENT_PACK.  */
8213
8214 static tree
8215 make_fnparm_pack (tree spec_parm)
8216 {
8217   /* Collect all of the extra "packed" parameters into an
8218      argument pack.  */
8219   tree parmvec;
8220   tree parmtypevec;
8221   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8222   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8223   int i, len = list_length (spec_parm);
8224
8225   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8226   parmvec = make_tree_vec (len);
8227   parmtypevec = make_tree_vec (len);
8228   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8229     {
8230       TREE_VEC_ELT (parmvec, i) = spec_parm;
8231       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8232     }
8233
8234   /* Build the argument packs.  */
8235   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8236   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8237   TREE_TYPE (argpack) = argtypepack;
8238
8239   return argpack;
8240 }        
8241
8242 /* Substitute ARGS into T, which is an pack expansion
8243    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8244    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8245    (if only a partial substitution could be performed) or
8246    ERROR_MARK_NODE if there was an error.  */
8247 tree
8248 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8249                        tree in_decl)
8250 {
8251   tree pattern;
8252   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8253   int i, len = -1;
8254   tree result;
8255   int incomplete = 0;
8256   bool very_local_specializations = false;
8257
8258   gcc_assert (PACK_EXPANSION_P (t));
8259   pattern = PACK_EXPANSION_PATTERN (t);
8260
8261   /* Determine the argument packs that will instantiate the parameter
8262      packs used in the expansion expression. While we're at it,
8263      compute the number of arguments to be expanded and make sure it
8264      is consistent.  */
8265   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8266        pack = TREE_CHAIN (pack))
8267     {
8268       tree parm_pack = TREE_VALUE (pack);
8269       tree arg_pack = NULL_TREE;
8270       tree orig_arg = NULL_TREE;
8271
8272       if (TREE_CODE (parm_pack) == PARM_DECL)
8273         {
8274           arg_pack = retrieve_local_specialization (parm_pack);
8275           if (arg_pack == NULL_TREE)
8276             {
8277               /* This can happen for a parameter name used later in a function
8278                  declaration (such as in a late-specified return type).  Just
8279                  make a dummy decl, since it's only used for its type.  */
8280               gcc_assert (cp_unevaluated_operand != 0);
8281               arg_pack = tsubst_decl (parm_pack, args, complain);
8282               arg_pack = make_fnparm_pack (arg_pack);
8283             }
8284         }
8285       else
8286         {
8287           int level, idx, levels;
8288           template_parm_level_and_index (parm_pack, &level, &idx);
8289
8290           levels = TMPL_ARGS_DEPTH (args);
8291           if (level <= levels)
8292             arg_pack = TMPL_ARG (args, level, idx);
8293         }
8294
8295       orig_arg = arg_pack;
8296       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8297         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8298       
8299       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8300         /* This can only happen if we forget to expand an argument
8301            pack somewhere else. Just return an error, silently.  */
8302         {
8303           result = make_tree_vec (1);
8304           TREE_VEC_ELT (result, 0) = error_mark_node;
8305           return result;
8306         }
8307
8308       if (arg_pack
8309           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8310           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8311         {
8312           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8313           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8314           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8315               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8316             /* The argument pack that the parameter maps to is just an
8317                expansion of the parameter itself, such as one would
8318                find in the implicit typedef of a class inside the
8319                class itself.  Consider this parameter "unsubstituted",
8320                so that we will maintain the outer pack expansion.  */
8321             arg_pack = NULL_TREE;
8322         }
8323           
8324       if (arg_pack)
8325         {
8326           int my_len = 
8327             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8328
8329           /* It's all-or-nothing with incomplete argument packs.  */
8330           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8331             return error_mark_node;
8332           
8333           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8334             incomplete = 1;
8335
8336           if (len < 0)
8337             len = my_len;
8338           else if (len != my_len)
8339             {
8340               if (incomplete)
8341                 /* We got explicit args for some packs but not others;
8342                    do nothing now and try again after deduction.  */
8343                 return t;
8344               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8345                 error ("mismatched argument pack lengths while expanding "
8346                        "%<%T%>",
8347                        pattern);
8348               else
8349                 error ("mismatched argument pack lengths while expanding "
8350                        "%<%E%>",
8351                        pattern);
8352               return error_mark_node;
8353             }
8354
8355           /* Keep track of the parameter packs and their corresponding
8356              argument packs.  */
8357           packs = tree_cons (parm_pack, arg_pack, packs);
8358           TREE_TYPE (packs) = orig_arg;
8359         }
8360       else
8361         /* We can't substitute for this parameter pack.  */
8362         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8363                                          TREE_VALUE (pack),
8364                                          unsubstituted_packs);
8365     }
8366
8367   /* We cannot expand this expansion expression, because we don't have
8368      all of the argument packs we need. Substitute into the pattern
8369      and return a PACK_EXPANSION_*. The caller will need to deal with
8370      that.  */
8371   if (unsubstituted_packs)
8372     {
8373       tree new_pat;
8374       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8375         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8376                                /*integral_constant_expression_p=*/false);
8377       else
8378         new_pat = tsubst (pattern, args, complain, in_decl);
8379       return make_pack_expansion (new_pat);
8380     }
8381
8382   /* We could not find any argument packs that work.  */
8383   if (len < 0)
8384     return error_mark_node;
8385
8386   if (!local_specializations)
8387     {
8388       /* We're in a late-specified return type, so we don't have a local
8389          specializations table.  Create one for doing this expansion.  */
8390       very_local_specializations = true;
8391       local_specializations = htab_create (37,
8392                                            hash_local_specialization,
8393                                            eq_local_specializations,
8394                                            NULL);
8395     }
8396
8397   /* For each argument in each argument pack, substitute into the
8398      pattern.  */
8399   result = make_tree_vec (len + incomplete);
8400   for (i = 0; i < len + incomplete; ++i)
8401     {
8402       /* For parameter pack, change the substitution of the parameter
8403          pack to the ith argument in its argument pack, then expand
8404          the pattern.  */
8405       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8406         {
8407           tree parm = TREE_PURPOSE (pack);
8408
8409           if (TREE_CODE (parm) == PARM_DECL)
8410             {
8411               /* Select the Ith argument from the pack.  */
8412               tree arg = make_node (ARGUMENT_PACK_SELECT);
8413               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8414               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8415               mark_used (parm);
8416               register_local_specialization (arg, parm);
8417             }
8418           else
8419             {
8420               tree value = parm;
8421               int idx, level;
8422               template_parm_level_and_index (parm, &level, &idx);
8423               
8424               if (i < len) 
8425                 {
8426                   /* Select the Ith argument from the pack. */
8427                   value = make_node (ARGUMENT_PACK_SELECT);
8428                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8429                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8430                 }
8431
8432               /* Update the corresponding argument.  */
8433               TMPL_ARG (args, level, idx) = value;
8434             }
8435         }
8436
8437       /* Substitute into the PATTERN with the altered arguments.  */
8438       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8439         TREE_VEC_ELT (result, i) = 
8440           tsubst_expr (pattern, args, complain, in_decl,
8441                        /*integral_constant_expression_p=*/false);
8442       else
8443         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8444
8445       if (i == len)
8446         /* When we have incomplete argument packs, the last "expanded"
8447            result is itself a pack expansion, which allows us
8448            to deduce more arguments.  */
8449         TREE_VEC_ELT (result, i) = 
8450           make_pack_expansion (TREE_VEC_ELT (result, i));
8451
8452       if (TREE_VEC_ELT (result, i) == error_mark_node)
8453         {
8454           result = error_mark_node;
8455           break;
8456         }
8457     }
8458
8459   /* Update ARGS to restore the substitution from parameter packs to
8460      their argument packs.  */
8461   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8462     {
8463       tree parm = TREE_PURPOSE (pack);
8464
8465       if (TREE_CODE (parm) == PARM_DECL)
8466         register_local_specialization (TREE_TYPE (pack), parm);
8467       else
8468         {
8469           int idx, level;
8470           template_parm_level_and_index (parm, &level, &idx);
8471           
8472           /* Update the corresponding argument.  */
8473           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8474             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8475               TREE_TYPE (pack);
8476           else
8477             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8478         }
8479     }
8480
8481   if (very_local_specializations)
8482     {
8483       htab_delete (local_specializations);
8484       local_specializations = NULL;
8485     }
8486   
8487   return result;
8488 }
8489
8490 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8491    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8492    parameter packs; all parms generated from a function parameter pack will
8493    have the same DECL_PARM_INDEX.  */
8494
8495 tree
8496 get_pattern_parm (tree parm, tree tmpl)
8497 {
8498   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8499   tree patparm;
8500
8501   if (DECL_ARTIFICIAL (parm))
8502     {
8503       for (patparm = DECL_ARGUMENTS (pattern);
8504            patparm; patparm = TREE_CHAIN (patparm))
8505         if (DECL_ARTIFICIAL (patparm)
8506             && DECL_NAME (parm) == DECL_NAME (patparm))
8507           break;
8508     }
8509   else
8510     {
8511       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8512       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8513       gcc_assert (DECL_PARM_INDEX (patparm)
8514                   == DECL_PARM_INDEX (parm));
8515     }
8516
8517   return patparm;
8518 }
8519
8520 /* Substitute ARGS into the vector or list of template arguments T.  */
8521
8522 static tree
8523 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8524 {
8525   tree orig_t = t;
8526   int len = TREE_VEC_LENGTH (t);
8527   int need_new = 0, i, expanded_len_adjust = 0, out;
8528   tree *elts = (tree *) alloca (len * sizeof (tree));
8529
8530   for (i = 0; i < len; i++)
8531     {
8532       tree orig_arg = TREE_VEC_ELT (t, i);
8533       tree new_arg;
8534
8535       if (TREE_CODE (orig_arg) == TREE_VEC)
8536         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8537       else if (PACK_EXPANSION_P (orig_arg))
8538         {
8539           /* Substitute into an expansion expression.  */
8540           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8541
8542           if (TREE_CODE (new_arg) == TREE_VEC)
8543             /* Add to the expanded length adjustment the number of
8544                expanded arguments. We subtract one from this
8545                measurement, because the argument pack expression
8546                itself is already counted as 1 in
8547                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8548                the argument pack is empty.  */
8549             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8550         }
8551       else if (ARGUMENT_PACK_P (orig_arg))
8552         {
8553           /* Substitute into each of the arguments.  */
8554           new_arg = TYPE_P (orig_arg)
8555             ? cxx_make_type (TREE_CODE (orig_arg))
8556             : make_node (TREE_CODE (orig_arg));
8557           
8558           SET_ARGUMENT_PACK_ARGS (
8559             new_arg,
8560             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8561                                   args, complain, in_decl));
8562
8563           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8564             new_arg = error_mark_node;
8565
8566           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8567             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8568                                           complain, in_decl);
8569             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8570
8571             if (TREE_TYPE (new_arg) == error_mark_node)
8572               new_arg = error_mark_node;
8573           }
8574         }
8575       else
8576         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8577
8578       if (new_arg == error_mark_node)
8579         return error_mark_node;
8580
8581       elts[i] = new_arg;
8582       if (new_arg != orig_arg)
8583         need_new = 1;
8584     }
8585
8586   if (!need_new)
8587     return t;
8588
8589   /* Make space for the expanded arguments coming from template
8590      argument packs.  */
8591   t = make_tree_vec (len + expanded_len_adjust);
8592   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8593      arguments for a member template.
8594      In that case each TREE_VEC in ORIG_T represents a level of template
8595      arguments, and ORIG_T won't carry any non defaulted argument count.
8596      It will rather be the nested TREE_VECs that will carry one.
8597      In other words, ORIG_T carries a non defaulted argument count only
8598      if it doesn't contain any nested TREE_VEC.  */
8599   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8600     {
8601       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8602       count += expanded_len_adjust;
8603       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8604     }
8605   for (i = 0, out = 0; i < len; i++)
8606     {
8607       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8608            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8609           && TREE_CODE (elts[i]) == TREE_VEC)
8610         {
8611           int idx;
8612
8613           /* Now expand the template argument pack "in place".  */
8614           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8615             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8616         }
8617       else
8618         {
8619           TREE_VEC_ELT (t, out) = elts[i];
8620           out++;
8621         }
8622     }
8623
8624   return t;
8625 }
8626
8627 /* Return the result of substituting ARGS into the template parameters
8628    given by PARMS.  If there are m levels of ARGS and m + n levels of
8629    PARMS, then the result will contain n levels of PARMS.  For
8630    example, if PARMS is `template <class T> template <class U>
8631    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8632    result will be `template <int*, double, class V>'.  */
8633
8634 static tree
8635 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8636 {
8637   tree r = NULL_TREE;
8638   tree* new_parms;
8639
8640   /* When substituting into a template, we must set
8641      PROCESSING_TEMPLATE_DECL as the template parameters may be
8642      dependent if they are based on one-another, and the dependency
8643      predicates are short-circuit outside of templates.  */
8644   ++processing_template_decl;
8645
8646   for (new_parms = &r;
8647        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8648        new_parms = &(TREE_CHAIN (*new_parms)),
8649          parms = TREE_CHAIN (parms))
8650     {
8651       tree new_vec =
8652         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8653       int i;
8654
8655       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8656         {
8657           tree tuple;
8658           tree default_value;
8659           tree parm_decl;
8660
8661           if (parms == error_mark_node)
8662             continue;
8663
8664           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8665
8666           if (tuple == error_mark_node)
8667             continue;
8668
8669           default_value = TREE_PURPOSE (tuple);
8670           parm_decl = TREE_VALUE (tuple);
8671
8672           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8673           if (TREE_CODE (parm_decl) == PARM_DECL
8674               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8675             parm_decl = error_mark_node;
8676           default_value = tsubst_template_arg (default_value, args,
8677                                                complain, NULL_TREE);
8678
8679           tuple = build_tree_list (default_value, parm_decl);
8680           TREE_VEC_ELT (new_vec, i) = tuple;
8681         }
8682
8683       *new_parms =
8684         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8685                              - TMPL_ARGS_DEPTH (args)),
8686                    new_vec, NULL_TREE);
8687     }
8688
8689   --processing_template_decl;
8690
8691   return r;
8692 }
8693
8694 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8695    type T.  If T is not an aggregate or enumeration type, it is
8696    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8697    ENTERING_SCOPE is nonzero, T is the context for a template which
8698    we are presently tsubst'ing.  Return the substituted value.  */
8699
8700 static tree
8701 tsubst_aggr_type (tree t,
8702                   tree args,
8703                   tsubst_flags_t complain,
8704                   tree in_decl,
8705                   int entering_scope)
8706 {
8707   if (t == NULL_TREE)
8708     return NULL_TREE;
8709
8710   switch (TREE_CODE (t))
8711     {
8712     case RECORD_TYPE:
8713       if (TYPE_PTRMEMFUNC_P (t))
8714         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8715
8716       /* Else fall through.  */
8717     case ENUMERAL_TYPE:
8718     case UNION_TYPE:
8719       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8720         {
8721           tree argvec;
8722           tree context;
8723           tree r;
8724           int saved_unevaluated_operand;
8725           int saved_inhibit_evaluation_warnings;
8726
8727           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8728           saved_unevaluated_operand = cp_unevaluated_operand;
8729           cp_unevaluated_operand = 0;
8730           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8731           c_inhibit_evaluation_warnings = 0;
8732
8733           /* First, determine the context for the type we are looking
8734              up.  */
8735           context = TYPE_CONTEXT (t);
8736           if (context)
8737             {
8738               context = tsubst_aggr_type (context, args, complain,
8739                                           in_decl, /*entering_scope=*/1);
8740               /* If context is a nested class inside a class template,
8741                  it may still need to be instantiated (c++/33959).  */
8742               if (TYPE_P (context))
8743                 context = complete_type (context);
8744             }
8745
8746           /* Then, figure out what arguments are appropriate for the
8747              type we are trying to find.  For example, given:
8748
8749                template <class T> struct S;
8750                template <class T, class U> void f(T, U) { S<U> su; }
8751
8752              and supposing that we are instantiating f<int, double>,
8753              then our ARGS will be {int, double}, but, when looking up
8754              S we only want {double}.  */
8755           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8756                                          complain, in_decl);
8757           if (argvec == error_mark_node)
8758             r = error_mark_node;
8759           else
8760             {
8761               r = lookup_template_class (t, argvec, in_decl, context,
8762                                          entering_scope, complain);
8763               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8764             }
8765
8766           cp_unevaluated_operand = saved_unevaluated_operand;
8767           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8768
8769           return r;
8770         }
8771       else
8772         /* This is not a template type, so there's nothing to do.  */
8773         return t;
8774
8775     default:
8776       return tsubst (t, args, complain, in_decl);
8777     }
8778 }
8779
8780 /* Substitute into the default argument ARG (a default argument for
8781    FN), which has the indicated TYPE.  */
8782
8783 tree
8784 tsubst_default_argument (tree fn, tree type, tree arg)
8785 {
8786   tree saved_class_ptr = NULL_TREE;
8787   tree saved_class_ref = NULL_TREE;
8788
8789   /* This default argument came from a template.  Instantiate the
8790      default argument here, not in tsubst.  In the case of
8791      something like:
8792
8793        template <class T>
8794        struct S {
8795          static T t();
8796          void f(T = t());
8797        };
8798
8799      we must be careful to do name lookup in the scope of S<T>,
8800      rather than in the current class.  */
8801   push_access_scope (fn);
8802   /* The "this" pointer is not valid in a default argument.  */
8803   if (cfun)
8804     {
8805       saved_class_ptr = current_class_ptr;
8806       cp_function_chain->x_current_class_ptr = NULL_TREE;
8807       saved_class_ref = current_class_ref;
8808       cp_function_chain->x_current_class_ref = NULL_TREE;
8809     }
8810
8811   push_deferring_access_checks(dk_no_deferred);
8812   /* The default argument expression may cause implicitly defined
8813      member functions to be synthesized, which will result in garbage
8814      collection.  We must treat this situation as if we were within
8815      the body of function so as to avoid collecting live data on the
8816      stack.  */
8817   ++function_depth;
8818   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8819                      tf_warning_or_error, NULL_TREE,
8820                      /*integral_constant_expression_p=*/false);
8821   --function_depth;
8822   pop_deferring_access_checks();
8823
8824   /* Restore the "this" pointer.  */
8825   if (cfun)
8826     {
8827       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8828       cp_function_chain->x_current_class_ref = saved_class_ref;
8829     }
8830
8831   /* Make sure the default argument is reasonable.  */
8832   arg = check_default_argument (type, arg);
8833
8834   pop_access_scope (fn);
8835
8836   return arg;
8837 }
8838
8839 /* Substitute into all the default arguments for FN.  */
8840
8841 static void
8842 tsubst_default_arguments (tree fn)
8843 {
8844   tree arg;
8845   tree tmpl_args;
8846
8847   tmpl_args = DECL_TI_ARGS (fn);
8848
8849   /* If this function is not yet instantiated, we certainly don't need
8850      its default arguments.  */
8851   if (uses_template_parms (tmpl_args))
8852     return;
8853
8854   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8855        arg;
8856        arg = TREE_CHAIN (arg))
8857     if (TREE_PURPOSE (arg))
8858       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8859                                                     TREE_VALUE (arg),
8860                                                     TREE_PURPOSE (arg));
8861 }
8862
8863 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8864    result of the substitution.  Issue error and warning messages under
8865    control of COMPLAIN.  */
8866
8867 static tree
8868 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8869 {
8870 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8871   location_t saved_loc;
8872   tree r = NULL_TREE;
8873   tree in_decl = t;
8874   hashval_t hash = 0;
8875
8876   /* Set the filename and linenumber to improve error-reporting.  */
8877   saved_loc = input_location;
8878   input_location = DECL_SOURCE_LOCATION (t);
8879
8880   switch (TREE_CODE (t))
8881     {
8882     case TEMPLATE_DECL:
8883       {
8884         /* We can get here when processing a member function template,
8885            member class template, or template template parameter.  */
8886         tree decl = DECL_TEMPLATE_RESULT (t);
8887         tree spec;
8888         tree tmpl_args;
8889         tree full_args;
8890
8891         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8892           {
8893             /* Template template parameter is treated here.  */
8894             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8895             if (new_type == error_mark_node)
8896               RETURN (error_mark_node);
8897
8898             r = copy_decl (t);
8899             TREE_CHAIN (r) = NULL_TREE;
8900             TREE_TYPE (r) = new_type;
8901             DECL_TEMPLATE_RESULT (r)
8902               = build_decl (DECL_SOURCE_LOCATION (decl),
8903                             TYPE_DECL, DECL_NAME (decl), new_type);
8904             DECL_TEMPLATE_PARMS (r)
8905               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8906                                        complain);
8907             TYPE_NAME (new_type) = r;
8908             break;
8909           }
8910
8911         /* We might already have an instance of this template.
8912            The ARGS are for the surrounding class type, so the
8913            full args contain the tsubst'd args for the context,
8914            plus the innermost args from the template decl.  */
8915         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8916           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8917           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8918         /* Because this is a template, the arguments will still be
8919            dependent, even after substitution.  If
8920            PROCESSING_TEMPLATE_DECL is not set, the dependency
8921            predicates will short-circuit.  */
8922         ++processing_template_decl;
8923         full_args = tsubst_template_args (tmpl_args, args,
8924                                           complain, in_decl);
8925         --processing_template_decl;
8926         if (full_args == error_mark_node)
8927           RETURN (error_mark_node);
8928
8929         /* If this is a default template template argument,
8930            tsubst might not have changed anything.  */
8931         if (full_args == tmpl_args)
8932           RETURN (t);
8933
8934         hash = hash_tmpl_and_args (t, full_args);
8935         spec = retrieve_specialization (t, full_args, hash);
8936         if (spec != NULL_TREE)
8937           {
8938             r = spec;
8939             break;
8940           }
8941
8942         /* Make a new template decl.  It will be similar to the
8943            original, but will record the current template arguments.
8944            We also create a new function declaration, which is just
8945            like the old one, but points to this new template, rather
8946            than the old one.  */
8947         r = copy_decl (t);
8948         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8949         TREE_CHAIN (r) = NULL_TREE;
8950
8951         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8952
8953         if (TREE_CODE (decl) == TYPE_DECL)
8954           {
8955             tree new_type;
8956             ++processing_template_decl;
8957             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8958             --processing_template_decl;
8959             if (new_type == error_mark_node)
8960               RETURN (error_mark_node);
8961
8962             TREE_TYPE (r) = new_type;
8963             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8964             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8965             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8966             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8967           }
8968         else
8969           {
8970             tree new_decl;
8971             ++processing_template_decl;
8972             new_decl = tsubst (decl, args, complain, in_decl);
8973             --processing_template_decl;
8974             if (new_decl == error_mark_node)
8975               RETURN (error_mark_node);
8976
8977             DECL_TEMPLATE_RESULT (r) = new_decl;
8978             DECL_TI_TEMPLATE (new_decl) = r;
8979             TREE_TYPE (r) = TREE_TYPE (new_decl);
8980             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8981             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8982           }
8983
8984         SET_DECL_IMPLICIT_INSTANTIATION (r);
8985         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8986         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8987
8988         /* The template parameters for this new template are all the
8989            template parameters for the old template, except the
8990            outermost level of parameters.  */
8991         DECL_TEMPLATE_PARMS (r)
8992           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8993                                    complain);
8994
8995         if (PRIMARY_TEMPLATE_P (t))
8996           DECL_PRIMARY_TEMPLATE (r) = r;
8997
8998         if (TREE_CODE (decl) != TYPE_DECL)
8999           /* Record this non-type partial instantiation.  */
9000           register_specialization (r, t,
9001                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9002                                    false, hash);
9003       }
9004       break;
9005
9006     case FUNCTION_DECL:
9007       {
9008         tree ctx;
9009         tree argvec = NULL_TREE;
9010         tree *friends;
9011         tree gen_tmpl;
9012         tree type;
9013         int member;
9014         int args_depth;
9015         int parms_depth;
9016
9017         /* Nobody should be tsubst'ing into non-template functions.  */
9018         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9019
9020         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9021           {
9022             tree spec;
9023             bool dependent_p;
9024
9025             /* If T is not dependent, just return it.  We have to
9026                increment PROCESSING_TEMPLATE_DECL because
9027                value_dependent_expression_p assumes that nothing is
9028                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9029             ++processing_template_decl;
9030             dependent_p = value_dependent_expression_p (t);
9031             --processing_template_decl;
9032             if (!dependent_p)
9033               RETURN (t);
9034
9035             /* Calculate the most general template of which R is a
9036                specialization, and the complete set of arguments used to
9037                specialize R.  */
9038             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9039             argvec = tsubst_template_args (DECL_TI_ARGS
9040                                           (DECL_TEMPLATE_RESULT
9041                                                  (DECL_TI_TEMPLATE (t))),
9042                                            args, complain, in_decl);
9043
9044             /* Check to see if we already have this specialization.  */
9045             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9046             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9047
9048             if (spec)
9049               {
9050                 r = spec;
9051                 break;
9052               }
9053
9054             /* We can see more levels of arguments than parameters if
9055                there was a specialization of a member template, like
9056                this:
9057
9058                  template <class T> struct S { template <class U> void f(); }
9059                  template <> template <class U> void S<int>::f(U);
9060
9061                Here, we'll be substituting into the specialization,
9062                because that's where we can find the code we actually
9063                want to generate, but we'll have enough arguments for
9064                the most general template.
9065
9066                We also deal with the peculiar case:
9067
9068                  template <class T> struct S {
9069                    template <class U> friend void f();
9070                  };
9071                  template <class U> void f() {}
9072                  template S<int>;
9073                  template void f<double>();
9074
9075                Here, the ARGS for the instantiation of will be {int,
9076                double}.  But, we only need as many ARGS as there are
9077                levels of template parameters in CODE_PATTERN.  We are
9078                careful not to get fooled into reducing the ARGS in
9079                situations like:
9080
9081                  template <class T> struct S { template <class U> void f(U); }
9082                  template <class T> template <> void S<T>::f(int) {}
9083
9084                which we can spot because the pattern will be a
9085                specialization in this case.  */
9086             args_depth = TMPL_ARGS_DEPTH (args);
9087             parms_depth =
9088               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9089             if (args_depth > parms_depth
9090                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9091               args = get_innermost_template_args (args, parms_depth);
9092           }
9093         else
9094           {
9095             /* This special case arises when we have something like this:
9096
9097                  template <class T> struct S {
9098                    friend void f<int>(int, double);
9099                  };
9100
9101                Here, the DECL_TI_TEMPLATE for the friend declaration
9102                will be an IDENTIFIER_NODE.  We are being called from
9103                tsubst_friend_function, and we want only to create a
9104                new decl (R) with appropriate types so that we can call
9105                determine_specialization.  */
9106             gen_tmpl = NULL_TREE;
9107           }
9108
9109         if (DECL_CLASS_SCOPE_P (t))
9110           {
9111             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9112               member = 2;
9113             else
9114               member = 1;
9115             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9116                                     complain, t, /*entering_scope=*/1);
9117           }
9118         else
9119           {
9120             member = 0;
9121             ctx = DECL_CONTEXT (t);
9122           }
9123         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9124         if (type == error_mark_node)
9125           RETURN (error_mark_node);
9126
9127         /* We do NOT check for matching decls pushed separately at this
9128            point, as they may not represent instantiations of this
9129            template, and in any case are considered separate under the
9130            discrete model.  */
9131         r = copy_decl (t);
9132         DECL_USE_TEMPLATE (r) = 0;
9133         TREE_TYPE (r) = type;
9134         /* Clear out the mangled name and RTL for the instantiation.  */
9135         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9136         SET_DECL_RTL (r, NULL_RTX);
9137         /* Leave DECL_INITIAL set on deleted instantiations.  */
9138         if (!DECL_DELETED_FN (r))
9139           DECL_INITIAL (r) = NULL_TREE;
9140         DECL_CONTEXT (r) = ctx;
9141
9142         if (member && DECL_CONV_FN_P (r))
9143           /* Type-conversion operator.  Reconstruct the name, in
9144              case it's the name of one of the template's parameters.  */
9145           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9146
9147         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9148                                      complain, t);
9149         DECL_RESULT (r) = NULL_TREE;
9150
9151         TREE_STATIC (r) = 0;
9152         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9153         DECL_EXTERNAL (r) = 1;
9154         /* If this is an instantiation of a function with internal
9155            linkage, we already know what object file linkage will be
9156            assigned to the instantiation.  */
9157         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9158         DECL_DEFER_OUTPUT (r) = 0;
9159         TREE_CHAIN (r) = NULL_TREE;
9160         DECL_PENDING_INLINE_INFO (r) = 0;
9161         DECL_PENDING_INLINE_P (r) = 0;
9162         DECL_SAVED_TREE (r) = NULL_TREE;
9163         DECL_STRUCT_FUNCTION (r) = NULL;
9164         TREE_USED (r) = 0;
9165         /* We'll re-clone as appropriate in instantiate_template.  */
9166         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9167
9168         /* If we aren't complaining now, return on error before we register
9169            the specialization so that we'll complain eventually.  */
9170         if ((complain & tf_error) == 0
9171             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9172             && !grok_op_properties (r, /*complain=*/false))
9173           RETURN (error_mark_node);
9174
9175         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9176            this in the special friend case mentioned above where
9177            GEN_TMPL is NULL.  */
9178         if (gen_tmpl)
9179           {
9180             DECL_TEMPLATE_INFO (r)
9181               = build_template_info (gen_tmpl, argvec);
9182             SET_DECL_IMPLICIT_INSTANTIATION (r);
9183             register_specialization (r, gen_tmpl, argvec, false, hash);
9184
9185             /* We're not supposed to instantiate default arguments
9186                until they are called, for a template.  But, for a
9187                declaration like:
9188
9189                  template <class T> void f ()
9190                  { extern void g(int i = T()); }
9191
9192                we should do the substitution when the template is
9193                instantiated.  We handle the member function case in
9194                instantiate_class_template since the default arguments
9195                might refer to other members of the class.  */
9196             if (!member
9197                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9198                 && !uses_template_parms (argvec))
9199               tsubst_default_arguments (r);
9200           }
9201         else
9202           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9203
9204         /* Copy the list of befriending classes.  */
9205         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9206              *friends;
9207              friends = &TREE_CHAIN (*friends))
9208           {
9209             *friends = copy_node (*friends);
9210             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9211                                             args, complain,
9212                                             in_decl);
9213           }
9214
9215         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9216           {
9217             maybe_retrofit_in_chrg (r);
9218             if (DECL_CONSTRUCTOR_P (r))
9219               grok_ctor_properties (ctx, r);
9220             /* If this is an instantiation of a member template, clone it.
9221                If it isn't, that'll be handled by
9222                clone_constructors_and_destructors.  */
9223             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9224               clone_function_decl (r, /*update_method_vec_p=*/0);
9225           }
9226         else if ((complain & tf_error) != 0
9227                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9228                  && !grok_op_properties (r, /*complain=*/true))
9229           RETURN (error_mark_node);
9230
9231         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9232           SET_DECL_FRIEND_CONTEXT (r,
9233                                    tsubst (DECL_FRIEND_CONTEXT (t),
9234                                             args, complain, in_decl));
9235
9236         /* Possibly limit visibility based on template args.  */
9237         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9238         if (DECL_VISIBILITY_SPECIFIED (t))
9239           {
9240             DECL_VISIBILITY_SPECIFIED (r) = 0;
9241             DECL_ATTRIBUTES (r)
9242               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9243           }
9244         determine_visibility (r);
9245         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9246             && !processing_template_decl)
9247           defaulted_late_check (r);
9248
9249         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9250                                         args, complain, in_decl);
9251       }
9252       break;
9253
9254     case PARM_DECL:
9255       {
9256         tree type = NULL_TREE;
9257         int i, len = 1;
9258         tree expanded_types = NULL_TREE;
9259         tree prev_r = NULL_TREE;
9260         tree first_r = NULL_TREE;
9261
9262         if (FUNCTION_PARAMETER_PACK_P (t))
9263           {
9264             /* If there is a local specialization that isn't a
9265                parameter pack, it means that we're doing a "simple"
9266                substitution from inside tsubst_pack_expansion. Just
9267                return the local specialization (which will be a single
9268                parm).  */
9269             tree spec = retrieve_local_specialization (t);
9270             if (spec 
9271                 && TREE_CODE (spec) == PARM_DECL
9272                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9273               RETURN (spec);
9274
9275             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9276                the parameters in this function parameter pack.  */
9277             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9278                                                     complain, in_decl);
9279             if (TREE_CODE (expanded_types) == TREE_VEC)
9280               {
9281                 len = TREE_VEC_LENGTH (expanded_types);
9282
9283                 /* Zero-length parameter packs are boring. Just substitute
9284                    into the chain.  */
9285                 if (len == 0)
9286                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9287                                   TREE_CHAIN (t)));
9288               }
9289             else
9290               {
9291                 /* All we did was update the type. Make a note of that.  */
9292                 type = expanded_types;
9293                 expanded_types = NULL_TREE;
9294               }
9295           }
9296
9297         /* Loop through all of the parameter's we'll build. When T is
9298            a function parameter pack, LEN is the number of expanded
9299            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9300         r = NULL_TREE;
9301         for (i = 0; i < len; ++i)
9302           {
9303             prev_r = r;
9304             r = copy_node (t);
9305             if (DECL_TEMPLATE_PARM_P (t))
9306               SET_DECL_TEMPLATE_PARM_P (r);
9307
9308             /* An argument of a function parameter pack is not a parameter
9309                pack.  */
9310             FUNCTION_PARAMETER_PACK_P (r) = false;
9311
9312             if (expanded_types)
9313               /* We're on the Ith parameter of the function parameter
9314                  pack.  */
9315               {
9316                 /* Get the Ith type.  */
9317                 type = TREE_VEC_ELT (expanded_types, i);
9318
9319                 if (DECL_NAME (r))
9320                   /* Rename the parameter to include the index.  */
9321                   DECL_NAME (r) =
9322                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9323               }
9324             else if (!type)
9325               /* We're dealing with a normal parameter.  */
9326               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9327
9328             type = type_decays_to (type);
9329             TREE_TYPE (r) = type;
9330             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9331
9332             if (DECL_INITIAL (r))
9333               {
9334                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9335                   DECL_INITIAL (r) = TREE_TYPE (r);
9336                 else
9337                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9338                                              complain, in_decl);
9339               }
9340
9341             DECL_CONTEXT (r) = NULL_TREE;
9342
9343             if (!DECL_TEMPLATE_PARM_P (r))
9344               DECL_ARG_TYPE (r) = type_passed_as (type);
9345
9346             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9347                                             args, complain, in_decl);
9348
9349             /* Keep track of the first new parameter we
9350                generate. That's what will be returned to the
9351                caller.  */
9352             if (!first_r)
9353               first_r = r;
9354
9355             /* Build a proper chain of parameters when substituting
9356                into a function parameter pack.  */
9357             if (prev_r)
9358               TREE_CHAIN (prev_r) = r;
9359           }
9360
9361         if (TREE_CHAIN (t))
9362           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9363                                    complain, TREE_CHAIN (t));
9364
9365         /* FIRST_R contains the start of the chain we've built.  */
9366         r = first_r;
9367       }
9368       break;
9369
9370     case FIELD_DECL:
9371       {
9372         tree type;
9373
9374         r = copy_decl (t);
9375         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9376         if (type == error_mark_node)
9377           RETURN (error_mark_node);
9378         TREE_TYPE (r) = type;
9379         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9380
9381         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9382         DECL_INITIAL (r)
9383           = tsubst_expr (DECL_INITIAL (t), args,
9384                          complain, in_decl,
9385                          /*integral_constant_expression_p=*/true);
9386         /* We don't have to set DECL_CONTEXT here; it is set by
9387            finish_member_declaration.  */
9388         TREE_CHAIN (r) = NULL_TREE;
9389         if (VOID_TYPE_P (type))
9390           error ("instantiation of %q+D as type %qT", r, type);
9391
9392         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9393                                         args, complain, in_decl);
9394       }
9395       break;
9396
9397     case USING_DECL:
9398       /* We reach here only for member using decls.  */
9399       if (DECL_DEPENDENT_P (t))
9400         {
9401           r = do_class_using_decl
9402             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9403              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9404           if (!r)
9405             r = error_mark_node;
9406           else
9407             {
9408               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9409               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9410             }
9411         }
9412       else
9413         {
9414           r = copy_node (t);
9415           TREE_CHAIN (r) = NULL_TREE;
9416         }
9417       break;
9418
9419     case TYPE_DECL:
9420     case VAR_DECL:
9421       {
9422         tree argvec = NULL_TREE;
9423         tree gen_tmpl = NULL_TREE;
9424         tree spec;
9425         tree tmpl = NULL_TREE;
9426         tree ctx;
9427         tree type = NULL_TREE;
9428         bool local_p;
9429
9430         if (TREE_CODE (t) == TYPE_DECL
9431             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9432           {
9433             /* If this is the canonical decl, we don't have to
9434                mess with instantiations, and often we can't (for
9435                typename, template type parms and such).  Note that
9436                TYPE_NAME is not correct for the above test if
9437                we've copied the type for a typedef.  */
9438             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9439             if (type == error_mark_node)
9440               RETURN (error_mark_node);
9441             r = TYPE_NAME (type);
9442             break;
9443           }
9444
9445         /* Check to see if we already have the specialization we
9446            need.  */
9447         spec = NULL_TREE;
9448         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9449           {
9450             /* T is a static data member or namespace-scope entity.
9451                We have to substitute into namespace-scope variables
9452                (even though such entities are never templates) because
9453                of cases like:
9454                
9455                  template <class T> void f() { extern T t; }
9456
9457                where the entity referenced is not known until
9458                instantiation time.  */
9459             local_p = false;
9460             ctx = DECL_CONTEXT (t);
9461             if (DECL_CLASS_SCOPE_P (t))
9462               {
9463                 ctx = tsubst_aggr_type (ctx, args,
9464                                         complain,
9465                                         in_decl, /*entering_scope=*/1);
9466                 /* If CTX is unchanged, then T is in fact the
9467                    specialization we want.  That situation occurs when
9468                    referencing a static data member within in its own
9469                    class.  We can use pointer equality, rather than
9470                    same_type_p, because DECL_CONTEXT is always
9471                    canonical.  */
9472                 if (ctx == DECL_CONTEXT (t))
9473                   spec = t;
9474               }
9475
9476             if (!spec)
9477               {
9478                 tmpl = DECL_TI_TEMPLATE (t);
9479                 gen_tmpl = most_general_template (tmpl);
9480                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9481                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9482                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9483               }
9484           }
9485         else
9486           {
9487             /* A local variable.  */
9488             local_p = true;
9489             /* Subsequent calls to pushdecl will fill this in.  */
9490             ctx = NULL_TREE;
9491             spec = retrieve_local_specialization (t);
9492           }
9493         /* If we already have the specialization we need, there is
9494            nothing more to do.  */ 
9495         if (spec)
9496           {
9497             r = spec;
9498             break;
9499           }
9500
9501         /* Create a new node for the specialization we need.  */
9502         r = copy_decl (t);
9503         if (type == NULL_TREE)
9504           {
9505             if (is_typedef_decl (t))
9506               type = DECL_ORIGINAL_TYPE (t);
9507             else
9508               type = TREE_TYPE (t);
9509             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9510               type = strip_array_domain (type);
9511             type = tsubst (type, args, complain, in_decl);
9512           }
9513         if (TREE_CODE (r) == VAR_DECL)
9514           {
9515             /* Even if the original location is out of scope, the
9516                newly substituted one is not.  */
9517             DECL_DEAD_FOR_LOCAL (r) = 0;
9518             DECL_INITIALIZED_P (r) = 0;
9519             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9520             if (type == error_mark_node)
9521               RETURN (error_mark_node);
9522             if (TREE_CODE (type) == FUNCTION_TYPE)
9523               {
9524                 /* It may seem that this case cannot occur, since:
9525
9526                      typedef void f();
9527                      void g() { f x; }
9528
9529                    declares a function, not a variable.  However:
9530       
9531                      typedef void f();
9532                      template <typename T> void g() { T t; }
9533                      template void g<f>();
9534
9535                    is an attempt to declare a variable with function
9536                    type.  */
9537                 error ("variable %qD has function type",
9538                        /* R is not yet sufficiently initialized, so we
9539                           just use its name.  */
9540                        DECL_NAME (r));
9541                 RETURN (error_mark_node);
9542               }
9543             type = complete_type (type);
9544             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9545               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9546             type = check_var_type (DECL_NAME (r), type);
9547
9548             if (DECL_HAS_VALUE_EXPR_P (t))
9549               {
9550                 tree ve = DECL_VALUE_EXPR (t);
9551                 ve = tsubst_expr (ve, args, complain, in_decl,
9552                                   /*constant_expression_p=*/false);
9553                 SET_DECL_VALUE_EXPR (r, ve);
9554               }
9555           }
9556         else if (DECL_SELF_REFERENCE_P (t))
9557           SET_DECL_SELF_REFERENCE_P (r);
9558         TREE_TYPE (r) = type;
9559         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9560         DECL_CONTEXT (r) = ctx;
9561         /* Clear out the mangled name and RTL for the instantiation.  */
9562         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9563         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9564           SET_DECL_RTL (r, NULL_RTX);
9565         /* The initializer must not be expanded until it is required;
9566            see [temp.inst].  */
9567         DECL_INITIAL (r) = NULL_TREE;
9568         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9569           SET_DECL_RTL (r, NULL_RTX);
9570         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9571         if (TREE_CODE (r) == VAR_DECL)
9572           {
9573             /* Possibly limit visibility based on template args.  */
9574             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9575             if (DECL_VISIBILITY_SPECIFIED (t))
9576               {
9577                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9578                 DECL_ATTRIBUTES (r)
9579                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9580               }
9581             determine_visibility (r);
9582           }
9583
9584         if (!local_p)
9585           {
9586             /* A static data member declaration is always marked
9587                external when it is declared in-class, even if an
9588                initializer is present.  We mimic the non-template
9589                processing here.  */
9590             DECL_EXTERNAL (r) = 1;
9591
9592             register_specialization (r, gen_tmpl, argvec, false, hash);
9593             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9594             SET_DECL_IMPLICIT_INSTANTIATION (r);
9595           }
9596         else if (cp_unevaluated_operand)
9597           {
9598             /* We're substituting this var in a decltype outside of its
9599                scope, such as for a lambda return type.  Don't add it to
9600                local_specializations, do perform auto deduction.  */
9601             tree auto_node = type_uses_auto (type);
9602             tree init
9603               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9604                              /*constant_expression_p=*/false);
9605
9606             if (auto_node && init && describable_type (init))
9607               {
9608                 type = do_auto_deduction (type, init, auto_node);
9609                 TREE_TYPE (r) = type;
9610               }
9611           }
9612         else
9613           register_local_specialization (r, t);
9614
9615         TREE_CHAIN (r) = NULL_TREE;
9616
9617         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9618                                         /*flags=*/0,
9619                                         args, complain, in_decl);
9620
9621         /* Preserve a typedef that names a type.  */
9622         if (is_typedef_decl (r))
9623           {
9624             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9625             set_underlying_type (r);
9626           }
9627
9628         layout_decl (r, 0);
9629       }
9630       break;
9631
9632     default:
9633       gcc_unreachable ();
9634     }
9635 #undef RETURN
9636
9637  out:
9638   /* Restore the file and line information.  */
9639   input_location = saved_loc;
9640
9641   return r;
9642 }
9643
9644 /* Substitute into the ARG_TYPES of a function type.  */
9645
9646 static tree
9647 tsubst_arg_types (tree arg_types,
9648                   tree args,
9649                   tsubst_flags_t complain,
9650                   tree in_decl)
9651 {
9652   tree remaining_arg_types;
9653   tree type = NULL_TREE;
9654   int i = 1;
9655   tree expanded_args = NULL_TREE;
9656   tree default_arg;
9657
9658   if (!arg_types || arg_types == void_list_node)
9659     return arg_types;
9660
9661   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9662                                           args, complain, in_decl);
9663   if (remaining_arg_types == error_mark_node)
9664     return error_mark_node;
9665
9666   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9667     {
9668       /* For a pack expansion, perform substitution on the
9669          entire expression. Later on, we'll handle the arguments
9670          one-by-one.  */
9671       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9672                                             args, complain, in_decl);
9673
9674       if (TREE_CODE (expanded_args) == TREE_VEC)
9675         /* So that we'll spin through the parameters, one by one.  */
9676         i = TREE_VEC_LENGTH (expanded_args);
9677       else
9678         {
9679           /* We only partially substituted into the parameter
9680              pack. Our type is TYPE_PACK_EXPANSION.  */
9681           type = expanded_args;
9682           expanded_args = NULL_TREE;
9683         }
9684     }
9685
9686   while (i > 0) {
9687     --i;
9688     
9689     if (expanded_args)
9690       type = TREE_VEC_ELT (expanded_args, i);
9691     else if (!type)
9692       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9693
9694     if (type == error_mark_node)
9695       return error_mark_node;
9696     if (VOID_TYPE_P (type))
9697       {
9698         if (complain & tf_error)
9699           {
9700             error ("invalid parameter type %qT", type);
9701             if (in_decl)
9702               error ("in declaration %q+D", in_decl);
9703           }
9704         return error_mark_node;
9705     }
9706     
9707     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9708        top-level qualifiers as required.  */
9709     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9710
9711     /* We do not substitute into default arguments here.  The standard
9712        mandates that they be instantiated only when needed, which is
9713        done in build_over_call.  */
9714     default_arg = TREE_PURPOSE (arg_types);
9715
9716     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9717       {
9718         /* We've instantiated a template before its default arguments
9719            have been parsed.  This can happen for a nested template
9720            class, and is not an error unless we require the default
9721            argument in a call of this function.  */
9722         remaining_arg_types = 
9723           tree_cons (default_arg, type, remaining_arg_types);
9724         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9725                        remaining_arg_types);
9726       }
9727     else
9728       remaining_arg_types = 
9729         hash_tree_cons (default_arg, type, remaining_arg_types);
9730   }
9731         
9732   return remaining_arg_types;
9733 }
9734
9735 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9736    *not* handle the exception-specification for FNTYPE, because the
9737    initial substitution of explicitly provided template parameters
9738    during argument deduction forbids substitution into the
9739    exception-specification:
9740
9741      [temp.deduct]
9742
9743      All references in the function type of the function template to  the
9744      corresponding template parameters are replaced by the specified tem-
9745      plate argument values.  If a substitution in a template parameter or
9746      in  the function type of the function template results in an invalid
9747      type, type deduction fails.  [Note: The equivalent  substitution  in
9748      exception specifications is done only when the function is instanti-
9749      ated, at which point a program is  ill-formed  if  the  substitution
9750      results in an invalid type.]  */
9751
9752 static tree
9753 tsubst_function_type (tree t,
9754                       tree args,
9755                       tsubst_flags_t complain,
9756                       tree in_decl)
9757 {
9758   tree return_type;
9759   tree arg_types;
9760   tree fntype;
9761
9762   /* The TYPE_CONTEXT is not used for function/method types.  */
9763   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9764
9765   /* Substitute the return type.  */
9766   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9767   if (return_type == error_mark_node)
9768     return error_mark_node;
9769   /* The standard does not presently indicate that creation of a
9770      function type with an invalid return type is a deduction failure.
9771      However, that is clearly analogous to creating an array of "void"
9772      or a reference to a reference.  This is core issue #486.  */
9773   if (TREE_CODE (return_type) == ARRAY_TYPE
9774       || TREE_CODE (return_type) == FUNCTION_TYPE)
9775     {
9776       if (complain & tf_error)
9777         {
9778           if (TREE_CODE (return_type) == ARRAY_TYPE)
9779             error ("function returning an array");
9780           else
9781             error ("function returning a function");
9782         }
9783       return error_mark_node;
9784     }
9785
9786   /* Substitute the argument types.  */
9787   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9788                                 complain, in_decl);
9789   if (arg_types == error_mark_node)
9790     return error_mark_node;
9791
9792   /* Construct a new type node and return it.  */
9793   if (TREE_CODE (t) == FUNCTION_TYPE)
9794     fntype = build_function_type (return_type, arg_types);
9795   else
9796     {
9797       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9798       if (! MAYBE_CLASS_TYPE_P (r))
9799         {
9800           /* [temp.deduct]
9801
9802              Type deduction may fail for any of the following
9803              reasons:
9804
9805              -- Attempting to create "pointer to member of T" when T
9806              is not a class type.  */
9807           if (complain & tf_error)
9808             error ("creating pointer to member function of non-class type %qT",
9809                       r);
9810           return error_mark_node;
9811         }
9812
9813       fntype = build_method_type_directly (r, return_type,
9814                                            TREE_CHAIN (arg_types));
9815     }
9816   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9817   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9818
9819   return fntype;
9820 }
9821
9822 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9823    ARGS into that specification, and return the substituted
9824    specification.  If there is no specification, return NULL_TREE.  */
9825
9826 static tree
9827 tsubst_exception_specification (tree fntype,
9828                                 tree args,
9829                                 tsubst_flags_t complain,
9830                                 tree in_decl)
9831 {
9832   tree specs;
9833   tree new_specs;
9834
9835   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9836   new_specs = NULL_TREE;
9837   if (specs)
9838     {
9839       if (! TREE_VALUE (specs))
9840         new_specs = specs;
9841       else
9842         while (specs)
9843           {
9844             tree spec;
9845             int i, len = 1;
9846             tree expanded_specs = NULL_TREE;
9847
9848             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9849               {
9850                 /* Expand the pack expansion type.  */
9851                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9852                                                        args, complain,
9853                                                        in_decl);
9854
9855                 if (expanded_specs == error_mark_node)
9856                   return error_mark_node;
9857                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9858                   len = TREE_VEC_LENGTH (expanded_specs);
9859                 else
9860                   {
9861                     /* We're substituting into a member template, so
9862                        we got a TYPE_PACK_EXPANSION back.  Add that
9863                        expansion and move on.  */
9864                     gcc_assert (TREE_CODE (expanded_specs) 
9865                                 == TYPE_PACK_EXPANSION);
9866                     new_specs = add_exception_specifier (new_specs,
9867                                                          expanded_specs,
9868                                                          complain);
9869                     specs = TREE_CHAIN (specs);
9870                     continue;
9871                   }
9872               }
9873
9874             for (i = 0; i < len; ++i)
9875               {
9876                 if (expanded_specs)
9877                   spec = TREE_VEC_ELT (expanded_specs, i);
9878                 else
9879                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9880                 if (spec == error_mark_node)
9881                   return spec;
9882                 new_specs = add_exception_specifier (new_specs, spec, 
9883                                                      complain);
9884               }
9885
9886             specs = TREE_CHAIN (specs);
9887           }
9888     }
9889   return new_specs;
9890 }
9891
9892 /* Take the tree structure T and replace template parameters used
9893    therein with the argument vector ARGS.  IN_DECL is an associated
9894    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9895    Issue error and warning messages under control of COMPLAIN.  Note
9896    that we must be relatively non-tolerant of extensions here, in
9897    order to preserve conformance; if we allow substitutions that
9898    should not be allowed, we may allow argument deductions that should
9899    not succeed, and therefore report ambiguous overload situations
9900    where there are none.  In theory, we could allow the substitution,
9901    but indicate that it should have failed, and allow our caller to
9902    make sure that the right thing happens, but we don't try to do this
9903    yet.
9904
9905    This function is used for dealing with types, decls and the like;
9906    for expressions, use tsubst_expr or tsubst_copy.  */
9907
9908 tree
9909 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9910 {
9911   tree type, r;
9912
9913   if (t == NULL_TREE || t == error_mark_node
9914       || t == integer_type_node
9915       || t == void_type_node
9916       || t == char_type_node
9917       || t == unknown_type_node
9918       || TREE_CODE (t) == NAMESPACE_DECL)
9919     return t;
9920
9921   if (DECL_P (t))
9922     return tsubst_decl (t, args, complain);
9923
9924   if (args == NULL_TREE)
9925     return t;
9926
9927   if (TREE_CODE (t) == IDENTIFIER_NODE)
9928     type = IDENTIFIER_TYPE_VALUE (t);
9929   else
9930     type = TREE_TYPE (t);
9931
9932   gcc_assert (type != unknown_type_node);
9933
9934   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9935      such as attribute aligned.  */
9936   if (TYPE_P (t)
9937       && TYPE_NAME (t)
9938       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9939     {
9940       tree decl = TYPE_NAME (t);
9941       
9942       if (DECL_CLASS_SCOPE_P (decl)
9943           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9944           && uses_template_parms (DECL_CONTEXT (decl)))
9945         {
9946           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9947           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9948           r = retrieve_specialization (tmpl, gen_args, 0);
9949         }
9950       else if (DECL_FUNCTION_SCOPE_P (decl)
9951                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9952                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9953         r = retrieve_local_specialization (decl);
9954       else
9955         /* The typedef is from a non-template context.  */
9956         return t;
9957
9958       if (r)
9959         {
9960           r = TREE_TYPE (r);
9961           r = cp_build_qualified_type_real
9962             (r, cp_type_quals (t) | cp_type_quals (r),
9963              complain | tf_ignore_bad_quals);
9964           return r;
9965         }
9966       /* Else we must be instantiating the typedef, so fall through.  */
9967     }
9968
9969   if (type
9970       && TREE_CODE (t) != TYPENAME_TYPE
9971       && TREE_CODE (t) != TEMPLATE_TYPE_PARM
9972       && TREE_CODE (t) != IDENTIFIER_NODE
9973       && TREE_CODE (t) != FUNCTION_TYPE
9974       && TREE_CODE (t) != METHOD_TYPE)
9975     type = tsubst (type, args, complain, in_decl);
9976   if (type == error_mark_node)
9977     return error_mark_node;
9978
9979   switch (TREE_CODE (t))
9980     {
9981     case RECORD_TYPE:
9982     case UNION_TYPE:
9983     case ENUMERAL_TYPE:
9984       return tsubst_aggr_type (t, args, complain, in_decl,
9985                                /*entering_scope=*/0);
9986
9987     case ERROR_MARK:
9988     case IDENTIFIER_NODE:
9989     case VOID_TYPE:
9990     case REAL_TYPE:
9991     case COMPLEX_TYPE:
9992     case VECTOR_TYPE:
9993     case BOOLEAN_TYPE:
9994     case INTEGER_CST:
9995     case REAL_CST:
9996     case STRING_CST:
9997       return t;
9998
9999     case INTEGER_TYPE:
10000       if (t == integer_type_node)
10001         return t;
10002
10003       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10004           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10005         return t;
10006
10007       {
10008         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10009
10010         max = tsubst_expr (omax, args, complain, in_decl,
10011                            /*integral_constant_expression_p=*/false);
10012
10013         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10014            needed.  */
10015         if (TREE_CODE (max) == NOP_EXPR
10016             && TREE_SIDE_EFFECTS (omax)
10017             && !TREE_TYPE (max))
10018           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10019
10020         max = fold_decl_constant_value (max);
10021
10022         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10023            with TREE_SIDE_EFFECTS that indicates this is not an integral
10024            constant expression.  */
10025         if (processing_template_decl
10026             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10027           {
10028             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10029             TREE_SIDE_EFFECTS (max) = 1;
10030           }
10031
10032         if (TREE_CODE (max) != INTEGER_CST
10033             && !at_function_scope_p ()
10034             && !TREE_SIDE_EFFECTS (max)
10035             && !value_dependent_expression_p (max))
10036           {
10037             if (complain & tf_error)
10038               error ("array bound is not an integer constant");
10039             return error_mark_node;
10040           }
10041
10042         /* [temp.deduct]
10043
10044            Type deduction may fail for any of the following
10045            reasons:
10046
10047              Attempting to create an array with a size that is
10048              zero or negative.  */
10049         if (integer_zerop (max) && !(complain & tf_error))
10050           /* We must fail if performing argument deduction (as
10051              indicated by the state of complain), so that
10052              another substitution can be found.  */
10053           return error_mark_node;
10054         else if (TREE_CODE (max) == INTEGER_CST
10055                  && INT_CST_LT (max, integer_zero_node))
10056           {
10057             if (complain & tf_error)
10058               error ("creating array with negative size (%qE)", max);
10059
10060             return error_mark_node;
10061           }
10062
10063         return compute_array_index_type (NULL_TREE, max);
10064       }
10065
10066     case TEMPLATE_TYPE_PARM:
10067     case TEMPLATE_TEMPLATE_PARM:
10068     case BOUND_TEMPLATE_TEMPLATE_PARM:
10069     case TEMPLATE_PARM_INDEX:
10070       {
10071         int idx;
10072         int level;
10073         int levels;
10074         tree arg = NULL_TREE;
10075
10076         r = NULL_TREE;
10077
10078         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10079         template_parm_level_and_index (t, &level, &idx); 
10080
10081         levels = TMPL_ARGS_DEPTH (args);
10082         if (level <= levels)
10083           {
10084             arg = TMPL_ARG (args, level, idx);
10085
10086             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10087               /* See through ARGUMENT_PACK_SELECT arguments. */
10088               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10089           }
10090
10091         if (arg == error_mark_node)
10092           return error_mark_node;
10093         else if (arg != NULL_TREE)
10094           {
10095             if (ARGUMENT_PACK_P (arg))
10096               /* If ARG is an argument pack, we don't actually want to
10097                  perform a substitution here, because substitutions
10098                  for argument packs are only done
10099                  element-by-element. We can get to this point when
10100                  substituting the type of a non-type template
10101                  parameter pack, when that type actually contains
10102                  template parameter packs from an outer template, e.g.,
10103
10104                  template<typename... Types> struct A {
10105                    template<Types... Values> struct B { };
10106                  };  */
10107               return t;
10108
10109             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10110               {
10111                 int quals;
10112                 gcc_assert (TYPE_P (arg));
10113
10114                 /* cv-quals from the template are discarded when
10115                    substituting in a function or reference type.  */
10116                 if (TREE_CODE (arg) == FUNCTION_TYPE
10117                     || TREE_CODE (arg) == METHOD_TYPE
10118                     || TREE_CODE (arg) == REFERENCE_TYPE)
10119                   quals = cp_type_quals (arg);
10120                 else
10121                   quals = cp_type_quals (arg) | cp_type_quals (t);
10122                   
10123                 return cp_build_qualified_type_real
10124                   (arg, quals, complain | tf_ignore_bad_quals);
10125               }
10126             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10127               {
10128                 /* We are processing a type constructed from a
10129                    template template parameter.  */
10130                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10131                                       args, complain, in_decl);
10132                 if (argvec == error_mark_node)
10133                   return error_mark_node;
10134
10135                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10136                    are resolving nested-types in the signature of a
10137                    member function templates.  Otherwise ARG is a
10138                    TEMPLATE_DECL and is the real template to be
10139                    instantiated.  */
10140                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10141                   arg = TYPE_NAME (arg);
10142
10143                 r = lookup_template_class (arg,
10144                                            argvec, in_decl,
10145                                            DECL_CONTEXT (arg),
10146                                             /*entering_scope=*/0,
10147                                            complain);
10148                 return cp_build_qualified_type_real
10149                   (r, TYPE_QUALS (t), complain);
10150               }
10151             else
10152               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10153               return unshare_expr (arg);
10154           }
10155
10156         if (level == 1)
10157           /* This can happen during the attempted tsubst'ing in
10158              unify.  This means that we don't yet have any information
10159              about the template parameter in question.  */
10160           return t;
10161
10162         /* If we get here, we must have been looking at a parm for a
10163            more deeply nested template.  Make a new version of this
10164            template parameter, but with a lower level.  */
10165         switch (TREE_CODE (t))
10166           {
10167           case TEMPLATE_TYPE_PARM:
10168           case TEMPLATE_TEMPLATE_PARM:
10169           case BOUND_TEMPLATE_TEMPLATE_PARM:
10170             if (cp_type_quals (t))
10171               {
10172                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10173                 r = cp_build_qualified_type_real
10174                   (r, cp_type_quals (t),
10175                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10176                                ? tf_ignore_bad_quals : 0));
10177               }
10178             else
10179               {
10180                 r = copy_type (t);
10181                 TEMPLATE_TYPE_PARM_INDEX (r)
10182                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10183                                                 r, levels, args, complain);
10184                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10185                 TYPE_MAIN_VARIANT (r) = r;
10186                 TYPE_POINTER_TO (r) = NULL_TREE;
10187                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10188
10189                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10190                   /* We have reduced the level of the template
10191                      template parameter, but not the levels of its
10192                      template parameters, so canonical_type_parameter
10193                      will not be able to find the canonical template
10194                      template parameter for this level. Thus, we
10195                      require structural equality checking to compare
10196                      TEMPLATE_TEMPLATE_PARMs. */
10197                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10198                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10199                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10200                 else
10201                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10202
10203                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10204                   {
10205                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10206                                           complain, in_decl);
10207                     if (argvec == error_mark_node)
10208                       return error_mark_node;
10209
10210                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10211                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10212                   }
10213               }
10214             break;
10215
10216           case TEMPLATE_PARM_INDEX:
10217             r = reduce_template_parm_level (t, type, levels, args, complain);
10218             break;
10219
10220           default:
10221             gcc_unreachable ();
10222           }
10223
10224         return r;
10225       }
10226
10227     case TREE_LIST:
10228       {
10229         tree purpose, value, chain;
10230
10231         if (t == void_list_node)
10232           return t;
10233
10234         purpose = TREE_PURPOSE (t);
10235         if (purpose)
10236           {
10237             purpose = tsubst (purpose, args, complain, in_decl);
10238             if (purpose == error_mark_node)
10239               return error_mark_node;
10240           }
10241         value = TREE_VALUE (t);
10242         if (value)
10243           {
10244             value = tsubst (value, args, complain, in_decl);
10245             if (value == error_mark_node)
10246               return error_mark_node;
10247           }
10248         chain = TREE_CHAIN (t);
10249         if (chain && chain != void_type_node)
10250           {
10251             chain = tsubst (chain, args, complain, in_decl);
10252             if (chain == error_mark_node)
10253               return error_mark_node;
10254           }
10255         if (purpose == TREE_PURPOSE (t)
10256             && value == TREE_VALUE (t)
10257             && chain == TREE_CHAIN (t))
10258           return t;
10259         return hash_tree_cons (purpose, value, chain);
10260       }
10261
10262     case TREE_BINFO:
10263       /* We should never be tsubsting a binfo.  */
10264       gcc_unreachable ();
10265
10266     case TREE_VEC:
10267       /* A vector of template arguments.  */
10268       gcc_assert (!type);
10269       return tsubst_template_args (t, args, complain, in_decl);
10270
10271     case POINTER_TYPE:
10272     case REFERENCE_TYPE:
10273       {
10274         enum tree_code code;
10275
10276         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10277           return t;
10278
10279         code = TREE_CODE (t);
10280
10281
10282         /* [temp.deduct]
10283
10284            Type deduction may fail for any of the following
10285            reasons:
10286
10287            -- Attempting to create a pointer to reference type.
10288            -- Attempting to create a reference to a reference type or
10289               a reference to void.
10290
10291           Core issue 106 says that creating a reference to a reference
10292           during instantiation is no longer a cause for failure. We
10293           only enforce this check in strict C++98 mode.  */
10294         if ((TREE_CODE (type) == REFERENCE_TYPE
10295              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10296             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10297           {
10298             static location_t last_loc;
10299
10300             /* We keep track of the last time we issued this error
10301                message to avoid spewing a ton of messages during a
10302                single bad template instantiation.  */
10303             if (complain & tf_error
10304                 && last_loc != input_location)
10305               {
10306                 if (TREE_CODE (type) == VOID_TYPE)
10307                   error ("forming reference to void");
10308                else if (code == POINTER_TYPE)
10309                  error ("forming pointer to reference type %qT", type);
10310                else
10311                   error ("forming reference to reference type %qT", type);
10312                 last_loc = input_location;
10313               }
10314
10315             return error_mark_node;
10316           }
10317         else if (code == POINTER_TYPE)
10318           {
10319             r = build_pointer_type (type);
10320             if (TREE_CODE (type) == METHOD_TYPE)
10321               r = build_ptrmemfunc_type (r);
10322           }
10323         else if (TREE_CODE (type) == REFERENCE_TYPE)
10324           /* In C++0x, during template argument substitution, when there is an
10325              attempt to create a reference to a reference type, reference
10326              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10327
10328              "If a template-argument for a template-parameter T names a type
10329              that is a reference to a type A, an attempt to create the type
10330              'lvalue reference to cv T' creates the type 'lvalue reference to
10331              A,' while an attempt to create the type type rvalue reference to
10332              cv T' creates the type T"
10333           */
10334           r = cp_build_reference_type
10335               (TREE_TYPE (type),
10336                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10337         else
10338           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10339         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10340
10341         if (r != error_mark_node)
10342           /* Will this ever be needed for TYPE_..._TO values?  */
10343           layout_type (r);
10344
10345         return r;
10346       }
10347     case OFFSET_TYPE:
10348       {
10349         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10350         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10351           {
10352             /* [temp.deduct]
10353
10354                Type deduction may fail for any of the following
10355                reasons:
10356
10357                -- Attempting to create "pointer to member of T" when T
10358                   is not a class type.  */
10359             if (complain & tf_error)
10360               error ("creating pointer to member of non-class type %qT", r);
10361             return error_mark_node;
10362           }
10363         if (TREE_CODE (type) == REFERENCE_TYPE)
10364           {
10365             if (complain & tf_error)
10366               error ("creating pointer to member reference type %qT", type);
10367             return error_mark_node;
10368           }
10369         if (TREE_CODE (type) == VOID_TYPE)
10370           {
10371             if (complain & tf_error)
10372               error ("creating pointer to member of type void");
10373             return error_mark_node;
10374           }
10375         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10376         if (TREE_CODE (type) == FUNCTION_TYPE)
10377           {
10378             /* The type of the implicit object parameter gets its
10379                cv-qualifiers from the FUNCTION_TYPE. */
10380             tree memptr;
10381             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10382             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10383             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10384                                                  complain);
10385           }
10386         else
10387           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10388                                                TYPE_QUALS (t),
10389                                                complain);
10390       }
10391     case FUNCTION_TYPE:
10392     case METHOD_TYPE:
10393       {
10394         tree fntype;
10395         tree specs;
10396         fntype = tsubst_function_type (t, args, complain, in_decl);
10397         if (fntype == error_mark_node)
10398           return error_mark_node;
10399
10400         /* Substitute the exception specification.  */
10401         specs = tsubst_exception_specification (t, args, complain,
10402                                                 in_decl);
10403         if (specs == error_mark_node)
10404           return error_mark_node;
10405         if (specs)
10406           fntype = build_exception_variant (fntype, specs);
10407         return fntype;
10408       }
10409     case ARRAY_TYPE:
10410       {
10411         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10412         if (domain == error_mark_node)
10413           return error_mark_node;
10414
10415         /* As an optimization, we avoid regenerating the array type if
10416            it will obviously be the same as T.  */
10417         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10418           return t;
10419
10420         /* These checks should match the ones in grokdeclarator.
10421
10422            [temp.deduct]
10423
10424            The deduction may fail for any of the following reasons:
10425
10426            -- Attempting to create an array with an element type that
10427               is void, a function type, or a reference type, or [DR337]
10428               an abstract class type.  */
10429         if (TREE_CODE (type) == VOID_TYPE
10430             || TREE_CODE (type) == FUNCTION_TYPE
10431             || TREE_CODE (type) == REFERENCE_TYPE)
10432           {
10433             if (complain & tf_error)
10434               error ("creating array of %qT", type);
10435             return error_mark_node;
10436           }
10437         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10438           {
10439             if (complain & tf_error)
10440               error ("creating array of %qT, which is an abstract class type",
10441                      type);
10442             return error_mark_node;
10443           }
10444
10445         r = build_cplus_array_type (type, domain);
10446
10447         if (TYPE_USER_ALIGN (t))
10448           {
10449             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10450             TYPE_USER_ALIGN (r) = 1;
10451           }
10452
10453         return r;
10454       }
10455
10456     case PLUS_EXPR:
10457     case MINUS_EXPR:
10458       {
10459         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10460         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10461
10462         if (e1 == error_mark_node || e2 == error_mark_node)
10463           return error_mark_node;
10464
10465         return fold_build2_loc (input_location,
10466                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10467       }
10468
10469     case NEGATE_EXPR:
10470     case NOP_EXPR:
10471       {
10472         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10473         if (e == error_mark_node)
10474           return error_mark_node;
10475
10476         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10477       }
10478
10479     case TYPENAME_TYPE:
10480       {
10481         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10482                                      in_decl, /*entering_scope=*/1);
10483         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10484                               complain, in_decl);
10485
10486         if (ctx == error_mark_node || f == error_mark_node)
10487           return error_mark_node;
10488
10489         if (!MAYBE_CLASS_TYPE_P (ctx))
10490           {
10491             if (complain & tf_error)
10492               error ("%qT is not a class, struct, or union type", ctx);
10493             return error_mark_node;
10494           }
10495         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10496           {
10497             /* Normally, make_typename_type does not require that the CTX
10498                have complete type in order to allow things like:
10499
10500                  template <class T> struct S { typename S<T>::X Y; };
10501
10502                But, such constructs have already been resolved by this
10503                point, so here CTX really should have complete type, unless
10504                it's a partial instantiation.  */
10505             if (!(complain & tf_no_class_instantiations))
10506               ctx = complete_type (ctx);
10507             if (!COMPLETE_TYPE_P (ctx))
10508               {
10509                 if (complain & tf_error)
10510                   cxx_incomplete_type_error (NULL_TREE, ctx);
10511                 return error_mark_node;
10512               }
10513           }
10514
10515         f = make_typename_type (ctx, f, typename_type,
10516                                 (complain & tf_error) | tf_keep_type_decl);
10517         if (f == error_mark_node)
10518           return f;
10519         if (TREE_CODE (f) == TYPE_DECL)
10520           {
10521             complain |= tf_ignore_bad_quals;
10522             f = TREE_TYPE (f);
10523           }
10524
10525         if (TREE_CODE (f) != TYPENAME_TYPE)
10526           {
10527             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10528               error ("%qT resolves to %qT, which is not an enumeration type",
10529                      t, f);
10530             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10531               error ("%qT resolves to %qT, which is is not a class type",
10532                      t, f);
10533           }
10534
10535         return cp_build_qualified_type_real
10536           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10537       }
10538
10539     case UNBOUND_CLASS_TEMPLATE:
10540       {
10541         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10542                                      in_decl, /*entering_scope=*/1);
10543         tree name = TYPE_IDENTIFIER (t);
10544         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10545
10546         if (ctx == error_mark_node || name == error_mark_node)
10547           return error_mark_node;
10548
10549         if (parm_list)
10550           parm_list = tsubst_template_parms (parm_list, args, complain);
10551         return make_unbound_class_template (ctx, name, parm_list, complain);
10552       }
10553
10554     case INDIRECT_REF:
10555     case ADDR_EXPR:
10556     case CALL_EXPR:
10557       gcc_unreachable ();
10558
10559     case ARRAY_REF:
10560       {
10561         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10562         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10563                                /*integral_constant_expression_p=*/false);
10564         if (e1 == error_mark_node || e2 == error_mark_node)
10565           return error_mark_node;
10566
10567         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10568       }
10569
10570     case SCOPE_REF:
10571       {
10572         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10573         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10574         if (e1 == error_mark_node || e2 == error_mark_node)
10575           return error_mark_node;
10576
10577         return build_qualified_name (/*type=*/NULL_TREE,
10578                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10579       }
10580
10581     case TYPEOF_TYPE:
10582       {
10583         tree type;
10584
10585         ++cp_unevaluated_operand;
10586         ++c_inhibit_evaluation_warnings;
10587
10588         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10589                             complain, in_decl,
10590                             /*integral_constant_expression_p=*/false);
10591
10592         --cp_unevaluated_operand;
10593         --c_inhibit_evaluation_warnings;
10594
10595         type = finish_typeof (type);
10596         return cp_build_qualified_type_real (type,
10597                                              cp_type_quals (t)
10598                                              | cp_type_quals (type),
10599                                              complain);
10600       }
10601
10602     case DECLTYPE_TYPE:
10603       {
10604         tree type;
10605
10606         ++cp_unevaluated_operand;
10607         ++c_inhibit_evaluation_warnings;
10608
10609         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10610                             complain, in_decl,
10611                             /*integral_constant_expression_p=*/false);
10612
10613         --cp_unevaluated_operand;
10614         --c_inhibit_evaluation_warnings;
10615
10616         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10617           type = lambda_capture_field_type (type);
10618         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10619           type = lambda_return_type (type);
10620         else
10621           type = finish_decltype_type
10622             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10623         return cp_build_qualified_type_real (type,
10624                                              cp_type_quals (t)
10625                                              | cp_type_quals (type),
10626                                              complain);
10627       }
10628
10629     case TYPE_ARGUMENT_PACK:
10630     case NONTYPE_ARGUMENT_PACK:
10631       {
10632         tree r = TYPE_P (t)
10633           ? cxx_make_type (TREE_CODE (t))
10634           : make_node (TREE_CODE (t));
10635         tree packed_out = 
10636           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10637                                 args,
10638                                 complain,
10639                                 in_decl);
10640         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10641
10642         /* For template nontype argument packs, also substitute into
10643            the type.  */
10644         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10645           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10646
10647         return r;
10648       }
10649       break;
10650
10651     default:
10652       sorry ("use of %qs in template",
10653              tree_code_name [(int) TREE_CODE (t)]);
10654       return error_mark_node;
10655     }
10656 }
10657
10658 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10659    type of the expression on the left-hand side of the "." or "->"
10660    operator.  */
10661
10662 static tree
10663 tsubst_baselink (tree baselink, tree object_type,
10664                  tree args, tsubst_flags_t complain, tree in_decl)
10665 {
10666     tree name;
10667     tree qualifying_scope;
10668     tree fns;
10669     tree optype;
10670     tree template_args = 0;
10671     bool template_id_p = false;
10672
10673     /* A baselink indicates a function from a base class.  Both the
10674        BASELINK_ACCESS_BINFO and the base class referenced may
10675        indicate bases of the template class, rather than the
10676        instantiated class.  In addition, lookups that were not
10677        ambiguous before may be ambiguous now.  Therefore, we perform
10678        the lookup again.  */
10679     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10680     qualifying_scope = tsubst (qualifying_scope, args,
10681                                complain, in_decl);
10682     fns = BASELINK_FUNCTIONS (baselink);
10683     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10684     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10685       {
10686         template_id_p = true;
10687         template_args = TREE_OPERAND (fns, 1);
10688         fns = TREE_OPERAND (fns, 0);
10689         if (template_args)
10690           template_args = tsubst_template_args (template_args, args,
10691                                                 complain, in_decl);
10692       }
10693     name = DECL_NAME (get_first_fn (fns));
10694     if (IDENTIFIER_TYPENAME_P (name))
10695       name = mangle_conv_op_name_for_type (optype);
10696     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10697
10698     /* If lookup found a single function, mark it as used at this
10699        point.  (If it lookup found multiple functions the one selected
10700        later by overload resolution will be marked as used at that
10701        point.)  */
10702     if (BASELINK_P (baselink))
10703       fns = BASELINK_FUNCTIONS (baselink);
10704     if (!template_id_p && !really_overloaded_fn (fns))
10705       mark_used (OVL_CURRENT (fns));
10706
10707     /* Add back the template arguments, if present.  */
10708     if (BASELINK_P (baselink) && template_id_p)
10709       BASELINK_FUNCTIONS (baselink)
10710         = build_nt (TEMPLATE_ID_EXPR,
10711                     BASELINK_FUNCTIONS (baselink),
10712                     template_args);
10713     /* Update the conversion operator type.  */
10714     BASELINK_OPTYPE (baselink) = optype;
10715
10716     if (!object_type)
10717       object_type = current_class_type;
10718     return adjust_result_of_qualified_name_lookup (baselink,
10719                                                    qualifying_scope,
10720                                                    object_type);
10721 }
10722
10723 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10724    true if the qualified-id will be a postfix-expression in-and-of
10725    itself; false if more of the postfix-expression follows the
10726    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10727    of "&".  */
10728
10729 static tree
10730 tsubst_qualified_id (tree qualified_id, tree args,
10731                      tsubst_flags_t complain, tree in_decl,
10732                      bool done, bool address_p)
10733 {
10734   tree expr;
10735   tree scope;
10736   tree name;
10737   bool is_template;
10738   tree template_args;
10739
10740   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10741
10742   /* Figure out what name to look up.  */
10743   name = TREE_OPERAND (qualified_id, 1);
10744   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10745     {
10746       is_template = true;
10747       template_args = TREE_OPERAND (name, 1);
10748       if (template_args)
10749         template_args = tsubst_template_args (template_args, args,
10750                                               complain, in_decl);
10751       name = TREE_OPERAND (name, 0);
10752     }
10753   else
10754     {
10755       is_template = false;
10756       template_args = NULL_TREE;
10757     }
10758
10759   /* Substitute into the qualifying scope.  When there are no ARGS, we
10760      are just trying to simplify a non-dependent expression.  In that
10761      case the qualifying scope may be dependent, and, in any case,
10762      substituting will not help.  */
10763   scope = TREE_OPERAND (qualified_id, 0);
10764   if (args)
10765     {
10766       scope = tsubst (scope, args, complain, in_decl);
10767       expr = tsubst_copy (name, args, complain, in_decl);
10768     }
10769   else
10770     expr = name;
10771
10772   if (dependent_scope_p (scope))
10773     return build_qualified_name (NULL_TREE, scope, expr,
10774                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10775
10776   if (!BASELINK_P (name) && !DECL_P (expr))
10777     {
10778       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10779         {
10780           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10781           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10782             {
10783               error ("qualifying type %qT does not match destructor name ~%qT",
10784                      scope, TREE_OPERAND (expr, 0));
10785               expr = error_mark_node;
10786             }
10787           else
10788             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10789                                           /*is_type_p=*/0, false);
10790         }
10791       else
10792         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10793       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10794                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10795         {
10796           if (complain & tf_error)
10797             {
10798               error ("dependent-name %qE is parsed as a non-type, but "
10799                      "instantiation yields a type", qualified_id);
10800               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10801             }
10802           return error_mark_node;
10803         }
10804     }
10805
10806   if (DECL_P (expr))
10807     {
10808       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10809                                            scope);
10810       /* Remember that there was a reference to this entity.  */
10811       mark_used (expr);
10812     }
10813
10814   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10815     {
10816       if (complain & tf_error)
10817         qualified_name_lookup_error (scope,
10818                                      TREE_OPERAND (qualified_id, 1),
10819                                      expr, input_location);
10820       return error_mark_node;
10821     }
10822
10823   if (is_template)
10824     expr = lookup_template_function (expr, template_args);
10825
10826   if (expr == error_mark_node && complain & tf_error)
10827     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10828                                  expr, input_location);
10829   else if (TYPE_P (scope))
10830     {
10831       expr = (adjust_result_of_qualified_name_lookup
10832               (expr, scope, current_class_type));
10833       expr = (finish_qualified_id_expr
10834               (scope, expr, done, address_p,
10835                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10836                /*template_arg_p=*/false));
10837     }
10838
10839   /* Expressions do not generally have reference type.  */
10840   if (TREE_CODE (expr) != SCOPE_REF
10841       /* However, if we're about to form a pointer-to-member, we just
10842          want the referenced member referenced.  */
10843       && TREE_CODE (expr) != OFFSET_REF)
10844     expr = convert_from_reference (expr);
10845
10846   return expr;
10847 }
10848
10849 /* Like tsubst, but deals with expressions.  This function just replaces
10850    template parms; to finish processing the resultant expression, use
10851    tsubst_expr.  */
10852
10853 static tree
10854 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10855 {
10856   enum tree_code code;
10857   tree r;
10858
10859   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10860     return t;
10861
10862   code = TREE_CODE (t);
10863
10864   switch (code)
10865     {
10866     case PARM_DECL:
10867       r = retrieve_local_specialization (t);
10868
10869       if (r == NULL)
10870         {
10871           tree c;
10872           /* This can happen for a parameter name used later in a function
10873              declaration (such as in a late-specified return type).  Just
10874              make a dummy decl, since it's only used for its type.  */
10875           gcc_assert (cp_unevaluated_operand != 0);
10876           /* We copy T because want to tsubst the PARM_DECL only,
10877              not the following PARM_DECLs that are chained to T.  */
10878           c = copy_node (t);
10879           r = tsubst_decl (c, args, complain);
10880           /* Give it the template pattern as its context; its true context
10881              hasn't been instantiated yet and this is good enough for
10882              mangling.  */
10883           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10884         }
10885       
10886       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10887         r = ARGUMENT_PACK_SELECT_ARG (r);
10888       mark_used (r);
10889       return r;
10890
10891     case CONST_DECL:
10892       {
10893         tree enum_type;
10894         tree v;
10895
10896         if (DECL_TEMPLATE_PARM_P (t))
10897           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10898         /* There is no need to substitute into namespace-scope
10899            enumerators.  */
10900         if (DECL_NAMESPACE_SCOPE_P (t))
10901           return t;
10902         /* If ARGS is NULL, then T is known to be non-dependent.  */
10903         if (args == NULL_TREE)
10904           return integral_constant_value (t);
10905
10906         /* Unfortunately, we cannot just call lookup_name here.
10907            Consider:
10908
10909              template <int I> int f() {
10910              enum E { a = I };
10911              struct S { void g() { E e = a; } };
10912              };
10913
10914            When we instantiate f<7>::S::g(), say, lookup_name is not
10915            clever enough to find f<7>::a.  */
10916         enum_type
10917           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10918                               /*entering_scope=*/0);
10919
10920         for (v = TYPE_VALUES (enum_type);
10921              v != NULL_TREE;
10922              v = TREE_CHAIN (v))
10923           if (TREE_PURPOSE (v) == DECL_NAME (t))
10924             return TREE_VALUE (v);
10925
10926           /* We didn't find the name.  That should never happen; if
10927              name-lookup found it during preliminary parsing, we
10928              should find it again here during instantiation.  */
10929         gcc_unreachable ();
10930       }
10931       return t;
10932
10933     case FIELD_DECL:
10934       if (DECL_CONTEXT (t))
10935         {
10936           tree ctx;
10937
10938           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10939                                   /*entering_scope=*/1);
10940           if (ctx != DECL_CONTEXT (t))
10941             {
10942               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10943               if (!r)
10944                 {
10945                   if (complain & tf_error)
10946                     error ("using invalid field %qD", t);
10947                   return error_mark_node;
10948                 }
10949               return r;
10950             }
10951         }
10952
10953       return t;
10954
10955     case VAR_DECL:
10956     case FUNCTION_DECL:
10957       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10958           || local_variable_p (t))
10959         t = tsubst (t, args, complain, in_decl);
10960       mark_used (t);
10961       return t;
10962
10963     case BASELINK:
10964       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10965
10966     case TEMPLATE_DECL:
10967       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10968         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10969                        args, complain, in_decl);
10970       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10971         return tsubst (t, args, complain, in_decl);
10972       else if (DECL_CLASS_SCOPE_P (t)
10973                && uses_template_parms (DECL_CONTEXT (t)))
10974         {
10975           /* Template template argument like the following example need
10976              special treatment:
10977
10978                template <template <class> class TT> struct C {};
10979                template <class T> struct D {
10980                  template <class U> struct E {};
10981                  C<E> c;                                // #1
10982                };
10983                D<int> d;                                // #2
10984
10985              We are processing the template argument `E' in #1 for
10986              the template instantiation #2.  Originally, `E' is a
10987              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10988              have to substitute this with one having context `D<int>'.  */
10989
10990           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10991           return lookup_field (context, DECL_NAME(t), 0, false);
10992         }
10993       else
10994         /* Ordinary template template argument.  */
10995         return t;
10996
10997     case CAST_EXPR:
10998     case REINTERPRET_CAST_EXPR:
10999     case CONST_CAST_EXPR:
11000     case STATIC_CAST_EXPR:
11001     case DYNAMIC_CAST_EXPR:
11002     case NOP_EXPR:
11003       return build1
11004         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11005          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11006
11007     case SIZEOF_EXPR:
11008       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11009         {
11010           /* We only want to compute the number of arguments.  */
11011           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11012                                                 complain, in_decl);
11013           int len = 0;
11014
11015           if (TREE_CODE (expanded) == TREE_VEC)
11016             len = TREE_VEC_LENGTH (expanded);
11017
11018           if (expanded == error_mark_node)
11019             return error_mark_node;
11020           else if (PACK_EXPANSION_P (expanded)
11021                    || (TREE_CODE (expanded) == TREE_VEC
11022                        && len > 0
11023                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11024             {
11025               if (TREE_CODE (expanded) == TREE_VEC)
11026                 expanded = TREE_VEC_ELT (expanded, len - 1);
11027
11028               if (TYPE_P (expanded))
11029                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11030                                                    complain & tf_error);
11031               else
11032                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11033                                                    complain & tf_error);
11034             }
11035           else
11036             return build_int_cst (size_type_node, len);
11037         }
11038       /* Fall through */
11039
11040     case INDIRECT_REF:
11041     case NEGATE_EXPR:
11042     case TRUTH_NOT_EXPR:
11043     case BIT_NOT_EXPR:
11044     case ADDR_EXPR:
11045     case UNARY_PLUS_EXPR:      /* Unary + */
11046     case ALIGNOF_EXPR:
11047     case ARROW_EXPR:
11048     case THROW_EXPR:
11049     case TYPEID_EXPR:
11050     case REALPART_EXPR:
11051     case IMAGPART_EXPR:
11052       return build1
11053         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11054          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11055
11056     case COMPONENT_REF:
11057       {
11058         tree object;
11059         tree name;
11060
11061         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11062         name = TREE_OPERAND (t, 1);
11063         if (TREE_CODE (name) == BIT_NOT_EXPR)
11064           {
11065             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11066                                 complain, in_decl);
11067             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11068           }
11069         else if (TREE_CODE (name) == SCOPE_REF
11070                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11071           {
11072             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11073                                      complain, in_decl);
11074             name = TREE_OPERAND (name, 1);
11075             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11076                                 complain, in_decl);
11077             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11078             name = build_qualified_name (/*type=*/NULL_TREE,
11079                                          base, name,
11080                                          /*template_p=*/false);
11081           }
11082         else if (TREE_CODE (name) == BASELINK)
11083           name = tsubst_baselink (name,
11084                                   non_reference (TREE_TYPE (object)),
11085                                   args, complain,
11086                                   in_decl);
11087         else
11088           name = tsubst_copy (name, args, complain, in_decl);
11089         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11090       }
11091
11092     case PLUS_EXPR:
11093     case MINUS_EXPR:
11094     case MULT_EXPR:
11095     case TRUNC_DIV_EXPR:
11096     case CEIL_DIV_EXPR:
11097     case FLOOR_DIV_EXPR:
11098     case ROUND_DIV_EXPR:
11099     case EXACT_DIV_EXPR:
11100     case BIT_AND_EXPR:
11101     case BIT_IOR_EXPR:
11102     case BIT_XOR_EXPR:
11103     case TRUNC_MOD_EXPR:
11104     case FLOOR_MOD_EXPR:
11105     case TRUTH_ANDIF_EXPR:
11106     case TRUTH_ORIF_EXPR:
11107     case TRUTH_AND_EXPR:
11108     case TRUTH_OR_EXPR:
11109     case RSHIFT_EXPR:
11110     case LSHIFT_EXPR:
11111     case RROTATE_EXPR:
11112     case LROTATE_EXPR:
11113     case EQ_EXPR:
11114     case NE_EXPR:
11115     case MAX_EXPR:
11116     case MIN_EXPR:
11117     case LE_EXPR:
11118     case GE_EXPR:
11119     case LT_EXPR:
11120     case GT_EXPR:
11121     case COMPOUND_EXPR:
11122     case DOTSTAR_EXPR:
11123     case MEMBER_REF:
11124     case PREDECREMENT_EXPR:
11125     case PREINCREMENT_EXPR:
11126     case POSTDECREMENT_EXPR:
11127     case POSTINCREMENT_EXPR:
11128       return build_nt
11129         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11130          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11131
11132     case SCOPE_REF:
11133       return build_qualified_name (/*type=*/NULL_TREE,
11134                                    tsubst_copy (TREE_OPERAND (t, 0),
11135                                                 args, complain, in_decl),
11136                                    tsubst_copy (TREE_OPERAND (t, 1),
11137                                                 args, complain, in_decl),
11138                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11139
11140     case ARRAY_REF:
11141       return build_nt
11142         (ARRAY_REF,
11143          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11144          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11145          NULL_TREE, NULL_TREE);
11146
11147     case CALL_EXPR:
11148       {
11149         int n = VL_EXP_OPERAND_LENGTH (t);
11150         tree result = build_vl_exp (CALL_EXPR, n);
11151         int i;
11152         for (i = 0; i < n; i++)
11153           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11154                                              complain, in_decl);
11155         return result;
11156       }
11157
11158     case COND_EXPR:
11159     case MODOP_EXPR:
11160     case PSEUDO_DTOR_EXPR:
11161       {
11162         r = build_nt
11163           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11164            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11165            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11166         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11167         return r;
11168       }
11169
11170     case NEW_EXPR:
11171       {
11172         r = build_nt
11173         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11174          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11175          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11176         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11177         return r;
11178       }
11179
11180     case DELETE_EXPR:
11181       {
11182         r = build_nt
11183         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11184          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11185         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11186         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11187         return r;
11188       }
11189
11190     case TEMPLATE_ID_EXPR:
11191       {
11192         /* Substituted template arguments */
11193         tree fn = TREE_OPERAND (t, 0);
11194         tree targs = TREE_OPERAND (t, 1);
11195
11196         fn = tsubst_copy (fn, args, complain, in_decl);
11197         if (targs)
11198           targs = tsubst_template_args (targs, args, complain, in_decl);
11199
11200         return lookup_template_function (fn, targs);
11201       }
11202
11203     case TREE_LIST:
11204       {
11205         tree purpose, value, chain;
11206
11207         if (t == void_list_node)
11208           return t;
11209
11210         purpose = TREE_PURPOSE (t);
11211         if (purpose)
11212           purpose = tsubst_copy (purpose, args, complain, in_decl);
11213         value = TREE_VALUE (t);
11214         if (value)
11215           value = tsubst_copy (value, args, complain, in_decl);
11216         chain = TREE_CHAIN (t);
11217         if (chain && chain != void_type_node)
11218           chain = tsubst_copy (chain, args, complain, in_decl);
11219         if (purpose == TREE_PURPOSE (t)
11220             && value == TREE_VALUE (t)
11221             && chain == TREE_CHAIN (t))
11222           return t;
11223         return tree_cons (purpose, value, chain);
11224       }
11225
11226     case RECORD_TYPE:
11227     case UNION_TYPE:
11228     case ENUMERAL_TYPE:
11229     case INTEGER_TYPE:
11230     case TEMPLATE_TYPE_PARM:
11231     case TEMPLATE_TEMPLATE_PARM:
11232     case BOUND_TEMPLATE_TEMPLATE_PARM:
11233     case TEMPLATE_PARM_INDEX:
11234     case POINTER_TYPE:
11235     case REFERENCE_TYPE:
11236     case OFFSET_TYPE:
11237     case FUNCTION_TYPE:
11238     case METHOD_TYPE:
11239     case ARRAY_TYPE:
11240     case TYPENAME_TYPE:
11241     case UNBOUND_CLASS_TEMPLATE:
11242     case TYPEOF_TYPE:
11243     case DECLTYPE_TYPE:
11244     case TYPE_DECL:
11245       return tsubst (t, args, complain, in_decl);
11246
11247     case IDENTIFIER_NODE:
11248       if (IDENTIFIER_TYPENAME_P (t))
11249         {
11250           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11251           return mangle_conv_op_name_for_type (new_type);
11252         }
11253       else
11254         return t;
11255
11256     case CONSTRUCTOR:
11257       /* This is handled by tsubst_copy_and_build.  */
11258       gcc_unreachable ();
11259
11260     case VA_ARG_EXPR:
11261       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11262                                           in_decl),
11263                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11264
11265     case CLEANUP_POINT_EXPR:
11266       /* We shouldn't have built any of these during initial template
11267          generation.  Instead, they should be built during instantiation
11268          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11269       gcc_unreachable ();
11270
11271     case OFFSET_REF:
11272       mark_used (TREE_OPERAND (t, 1));
11273       return t;
11274
11275     case EXPR_PACK_EXPANSION:
11276       error ("invalid use of pack expansion expression");
11277       return error_mark_node;
11278
11279     case NONTYPE_ARGUMENT_PACK:
11280       error ("use %<...%> to expand argument pack");
11281       return error_mark_node;
11282
11283     default:
11284       return t;
11285     }
11286 }
11287
11288 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11289
11290 static tree
11291 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11292                     tree in_decl)
11293 {
11294   tree new_clauses = NULL, nc, oc;
11295
11296   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11297     {
11298       nc = copy_node (oc);
11299       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11300       new_clauses = nc;
11301
11302       switch (OMP_CLAUSE_CODE (nc))
11303         {
11304         case OMP_CLAUSE_LASTPRIVATE:
11305           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11306             {
11307               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11308               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11309                            in_decl, /*integral_constant_expression_p=*/false);
11310               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11311                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11312             }
11313           /* FALLTHRU */
11314         case OMP_CLAUSE_PRIVATE:
11315         case OMP_CLAUSE_SHARED:
11316         case OMP_CLAUSE_FIRSTPRIVATE:
11317         case OMP_CLAUSE_REDUCTION:
11318         case OMP_CLAUSE_COPYIN:
11319         case OMP_CLAUSE_COPYPRIVATE:
11320         case OMP_CLAUSE_IF:
11321         case OMP_CLAUSE_NUM_THREADS:
11322         case OMP_CLAUSE_SCHEDULE:
11323         case OMP_CLAUSE_COLLAPSE:
11324           OMP_CLAUSE_OPERAND (nc, 0)
11325             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11326                            in_decl, /*integral_constant_expression_p=*/false);
11327           break;
11328         case OMP_CLAUSE_NOWAIT:
11329         case OMP_CLAUSE_ORDERED:
11330         case OMP_CLAUSE_DEFAULT:
11331         case OMP_CLAUSE_UNTIED:
11332           break;
11333         default:
11334           gcc_unreachable ();
11335         }
11336     }
11337
11338   return finish_omp_clauses (nreverse (new_clauses));
11339 }
11340
11341 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11342
11343 static tree
11344 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11345                           tree in_decl)
11346 {
11347 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11348
11349   tree purpose, value, chain;
11350
11351   if (t == NULL)
11352     return t;
11353
11354   if (TREE_CODE (t) != TREE_LIST)
11355     return tsubst_copy_and_build (t, args, complain, in_decl,
11356                                   /*function_p=*/false,
11357                                   /*integral_constant_expression_p=*/false);
11358
11359   if (t == void_list_node)
11360     return t;
11361
11362   purpose = TREE_PURPOSE (t);
11363   if (purpose)
11364     purpose = RECUR (purpose);
11365   value = TREE_VALUE (t);
11366   if (value && TREE_CODE (value) != LABEL_DECL)
11367     value = RECUR (value);
11368   chain = TREE_CHAIN (t);
11369   if (chain && chain != void_type_node)
11370     chain = RECUR (chain);
11371   return tree_cons (purpose, value, chain);
11372 #undef RECUR
11373 }
11374
11375 /* Substitute one OMP_FOR iterator.  */
11376
11377 static void
11378 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11379                          tree condv, tree incrv, tree *clauses,
11380                          tree args, tsubst_flags_t complain, tree in_decl,
11381                          bool integral_constant_expression_p)
11382 {
11383 #define RECUR(NODE)                             \
11384   tsubst_expr ((NODE), args, complain, in_decl, \
11385                integral_constant_expression_p)
11386   tree decl, init, cond, incr, auto_node;
11387
11388   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11389   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11390   decl = RECUR (TREE_OPERAND (init, 0));
11391   init = TREE_OPERAND (init, 1);
11392   auto_node = type_uses_auto (TREE_TYPE (decl));
11393   if (auto_node && init)
11394     {
11395       tree init_expr = init;
11396       if (TREE_CODE (init_expr) == DECL_EXPR)
11397         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11398       init_expr = RECUR (init_expr);
11399       TREE_TYPE (decl)
11400         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11401     }
11402   gcc_assert (!type_dependent_expression_p (decl));
11403
11404   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11405     {
11406       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11407       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11408       if (TREE_CODE (incr) == MODIFY_EXPR)
11409         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11410                                     RECUR (TREE_OPERAND (incr, 1)),
11411                                     complain);
11412       else
11413         incr = RECUR (incr);
11414       TREE_VEC_ELT (declv, i) = decl;
11415       TREE_VEC_ELT (initv, i) = init;
11416       TREE_VEC_ELT (condv, i) = cond;
11417       TREE_VEC_ELT (incrv, i) = incr;
11418       return;
11419     }
11420
11421   if (init && TREE_CODE (init) != DECL_EXPR)
11422     {
11423       tree c;
11424       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11425         {
11426           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11427                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11428               && OMP_CLAUSE_DECL (c) == decl)
11429             break;
11430           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11431                    && OMP_CLAUSE_DECL (c) == decl)
11432             error ("iteration variable %qD should not be firstprivate", decl);
11433           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11434                    && OMP_CLAUSE_DECL (c) == decl)
11435             error ("iteration variable %qD should not be reduction", decl);
11436         }
11437       if (c == NULL)
11438         {
11439           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11440           OMP_CLAUSE_DECL (c) = decl;
11441           c = finish_omp_clauses (c);
11442           if (c)
11443             {
11444               OMP_CLAUSE_CHAIN (c) = *clauses;
11445               *clauses = c;
11446             }
11447         }
11448     }
11449   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11450   if (COMPARISON_CLASS_P (cond))
11451     cond = build2 (TREE_CODE (cond), boolean_type_node,
11452                    RECUR (TREE_OPERAND (cond, 0)),
11453                    RECUR (TREE_OPERAND (cond, 1)));
11454   else
11455     cond = RECUR (cond);
11456   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11457   switch (TREE_CODE (incr))
11458     {
11459     case PREINCREMENT_EXPR:
11460     case PREDECREMENT_EXPR:
11461     case POSTINCREMENT_EXPR:
11462     case POSTDECREMENT_EXPR:
11463       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11464                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11465       break;
11466     case MODIFY_EXPR:
11467       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11468           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11469         {
11470           tree rhs = TREE_OPERAND (incr, 1);
11471           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11472                          RECUR (TREE_OPERAND (incr, 0)),
11473                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11474                                  RECUR (TREE_OPERAND (rhs, 0)),
11475                                  RECUR (TREE_OPERAND (rhs, 1))));
11476         }
11477       else
11478         incr = RECUR (incr);
11479       break;
11480     case MODOP_EXPR:
11481       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11482           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11483         {
11484           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11485           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11486                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11487                                  TREE_TYPE (decl), lhs,
11488                                  RECUR (TREE_OPERAND (incr, 2))));
11489         }
11490       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11491                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11492                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11493         {
11494           tree rhs = TREE_OPERAND (incr, 2);
11495           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11496                          RECUR (TREE_OPERAND (incr, 0)),
11497                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11498                                  RECUR (TREE_OPERAND (rhs, 0)),
11499                                  RECUR (TREE_OPERAND (rhs, 1))));
11500         }
11501       else
11502         incr = RECUR (incr);
11503       break;
11504     default:
11505       incr = RECUR (incr);
11506       break;
11507     }
11508
11509   TREE_VEC_ELT (declv, i) = decl;
11510   TREE_VEC_ELT (initv, i) = init;
11511   TREE_VEC_ELT (condv, i) = cond;
11512   TREE_VEC_ELT (incrv, i) = incr;
11513 #undef RECUR
11514 }
11515
11516 /* Like tsubst_copy for expressions, etc. but also does semantic
11517    processing.  */
11518
11519 static tree
11520 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11521              bool integral_constant_expression_p)
11522 {
11523 #define RECUR(NODE)                             \
11524   tsubst_expr ((NODE), args, complain, in_decl, \
11525                integral_constant_expression_p)
11526
11527   tree stmt, tmp;
11528
11529   if (t == NULL_TREE || t == error_mark_node)
11530     return t;
11531
11532   if (EXPR_HAS_LOCATION (t))
11533     input_location = EXPR_LOCATION (t);
11534   if (STATEMENT_CODE_P (TREE_CODE (t)))
11535     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11536
11537   switch (TREE_CODE (t))
11538     {
11539     case STATEMENT_LIST:
11540       {
11541         tree_stmt_iterator i;
11542         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11543           RECUR (tsi_stmt (i));
11544         break;
11545       }
11546
11547     case CTOR_INITIALIZER:
11548       finish_mem_initializers (tsubst_initializer_list
11549                                (TREE_OPERAND (t, 0), args));
11550       break;
11551
11552     case RETURN_EXPR:
11553       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11554       break;
11555
11556     case EXPR_STMT:
11557       tmp = RECUR (EXPR_STMT_EXPR (t));
11558       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11559         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11560       else
11561         finish_expr_stmt (tmp);
11562       break;
11563
11564     case USING_STMT:
11565       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11566       break;
11567
11568     case DECL_EXPR:
11569       {
11570         tree decl;
11571         tree init;
11572
11573         decl = DECL_EXPR_DECL (t);
11574         if (TREE_CODE (decl) == LABEL_DECL)
11575           finish_label_decl (DECL_NAME (decl));
11576         else if (TREE_CODE (decl) == USING_DECL)
11577           {
11578             tree scope = USING_DECL_SCOPE (decl);
11579             tree name = DECL_NAME (decl);
11580             tree decl;
11581
11582             scope = RECUR (scope);
11583             decl = lookup_qualified_name (scope, name,
11584                                           /*is_type_p=*/false,
11585                                           /*complain=*/false);
11586             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11587               qualified_name_lookup_error (scope, name, decl, input_location);
11588             else
11589               do_local_using_decl (decl, scope, name);
11590           }
11591         else
11592           {
11593             init = DECL_INITIAL (decl);
11594             decl = tsubst (decl, args, complain, in_decl);
11595             if (decl != error_mark_node)
11596               {
11597                 /* By marking the declaration as instantiated, we avoid
11598                    trying to instantiate it.  Since instantiate_decl can't
11599                    handle local variables, and since we've already done
11600                    all that needs to be done, that's the right thing to
11601                    do.  */
11602                 if (TREE_CODE (decl) == VAR_DECL)
11603                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11604                 if (TREE_CODE (decl) == VAR_DECL
11605                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11606                   /* Anonymous aggregates are a special case.  */
11607                   finish_anon_union (decl);
11608                 else
11609                   {
11610                     maybe_push_decl (decl);
11611                     if (TREE_CODE (decl) == VAR_DECL
11612                         && DECL_PRETTY_FUNCTION_P (decl))
11613                       {
11614                         /* For __PRETTY_FUNCTION__ we have to adjust the
11615                            initializer.  */
11616                         const char *const name
11617                           = cxx_printable_name (current_function_decl, 2);
11618                         init = cp_fname_init (name, &TREE_TYPE (decl));
11619                       }
11620                     else
11621                       {
11622                         tree t = RECUR (init);
11623
11624                         if (init && !t)
11625                           /* If we had an initializer but it
11626                              instantiated to nothing,
11627                              value-initialize the object.  This will
11628                              only occur when the initializer was a
11629                              pack expansion where the parameter packs
11630                              used in that expansion were of length
11631                              zero.  */
11632                           init = build_value_init (TREE_TYPE (decl));
11633                         else
11634                           init = t;
11635                       }
11636
11637                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11638                   }
11639               }
11640           }
11641
11642         /* A DECL_EXPR can also be used as an expression, in the condition
11643            clause of an if/for/while construct.  */
11644         return decl;
11645       }
11646
11647     case FOR_STMT:
11648       stmt = begin_for_stmt ();
11649                           RECUR (FOR_INIT_STMT (t));
11650       finish_for_init_stmt (stmt);
11651       tmp = RECUR (FOR_COND (t));
11652       finish_for_cond (tmp, stmt);
11653       tmp = RECUR (FOR_EXPR (t));
11654       finish_for_expr (tmp, stmt);
11655       RECUR (FOR_BODY (t));
11656       finish_for_stmt (stmt);
11657       break;
11658
11659     case WHILE_STMT:
11660       stmt = begin_while_stmt ();
11661       tmp = RECUR (WHILE_COND (t));
11662       finish_while_stmt_cond (tmp, stmt);
11663       RECUR (WHILE_BODY (t));
11664       finish_while_stmt (stmt);
11665       break;
11666
11667     case DO_STMT:
11668       stmt = begin_do_stmt ();
11669       RECUR (DO_BODY (t));
11670       finish_do_body (stmt);
11671       tmp = RECUR (DO_COND (t));
11672       finish_do_stmt (tmp, stmt);
11673       break;
11674
11675     case IF_STMT:
11676       stmt = begin_if_stmt ();
11677       tmp = RECUR (IF_COND (t));
11678       finish_if_stmt_cond (tmp, stmt);
11679       RECUR (THEN_CLAUSE (t));
11680       finish_then_clause (stmt);
11681
11682       if (ELSE_CLAUSE (t))
11683         {
11684           begin_else_clause (stmt);
11685           RECUR (ELSE_CLAUSE (t));
11686           finish_else_clause (stmt);
11687         }
11688
11689       finish_if_stmt (stmt);
11690       break;
11691
11692     case BIND_EXPR:
11693       if (BIND_EXPR_BODY_BLOCK (t))
11694         stmt = begin_function_body ();
11695       else
11696         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11697                                     ? BCS_TRY_BLOCK : 0);
11698
11699       RECUR (BIND_EXPR_BODY (t));
11700
11701       if (BIND_EXPR_BODY_BLOCK (t))
11702         finish_function_body (stmt);
11703       else
11704         finish_compound_stmt (stmt);
11705       break;
11706
11707     case BREAK_STMT:
11708       finish_break_stmt ();
11709       break;
11710
11711     case CONTINUE_STMT:
11712       finish_continue_stmt ();
11713       break;
11714
11715     case SWITCH_STMT:
11716       stmt = begin_switch_stmt ();
11717       tmp = RECUR (SWITCH_STMT_COND (t));
11718       finish_switch_cond (tmp, stmt);
11719       RECUR (SWITCH_STMT_BODY (t));
11720       finish_switch_stmt (stmt);
11721       break;
11722
11723     case CASE_LABEL_EXPR:
11724       finish_case_label (EXPR_LOCATION (t),
11725                          RECUR (CASE_LOW (t)),
11726                          RECUR (CASE_HIGH (t)));
11727       break;
11728
11729     case LABEL_EXPR:
11730       {
11731         tree decl = LABEL_EXPR_LABEL (t);
11732         tree label;
11733
11734         label = finish_label_stmt (DECL_NAME (decl));
11735         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11736           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11737       }
11738       break;
11739
11740     case GOTO_EXPR:
11741       tmp = GOTO_DESTINATION (t);
11742       if (TREE_CODE (tmp) != LABEL_DECL)
11743         /* Computed goto's must be tsubst'd into.  On the other hand,
11744            non-computed gotos must not be; the identifier in question
11745            will have no binding.  */
11746         tmp = RECUR (tmp);
11747       else
11748         tmp = DECL_NAME (tmp);
11749       finish_goto_stmt (tmp);
11750       break;
11751
11752     case ASM_EXPR:
11753       tmp = finish_asm_stmt
11754         (ASM_VOLATILE_P (t),
11755          RECUR (ASM_STRING (t)),
11756          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11757          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11758          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11759          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11760       {
11761         tree asm_expr = tmp;
11762         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11763           asm_expr = TREE_OPERAND (asm_expr, 0);
11764         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11765       }
11766       break;
11767
11768     case TRY_BLOCK:
11769       if (CLEANUP_P (t))
11770         {
11771           stmt = begin_try_block ();
11772           RECUR (TRY_STMTS (t));
11773           finish_cleanup_try_block (stmt);
11774           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11775         }
11776       else
11777         {
11778           tree compound_stmt = NULL_TREE;
11779
11780           if (FN_TRY_BLOCK_P (t))
11781             stmt = begin_function_try_block (&compound_stmt);
11782           else
11783             stmt = begin_try_block ();
11784
11785           RECUR (TRY_STMTS (t));
11786
11787           if (FN_TRY_BLOCK_P (t))
11788             finish_function_try_block (stmt);
11789           else
11790             finish_try_block (stmt);
11791
11792           RECUR (TRY_HANDLERS (t));
11793           if (FN_TRY_BLOCK_P (t))
11794             finish_function_handler_sequence (stmt, compound_stmt);
11795           else
11796             finish_handler_sequence (stmt);
11797         }
11798       break;
11799
11800     case HANDLER:
11801       {
11802         tree decl = HANDLER_PARMS (t);
11803
11804         if (decl)
11805           {
11806             decl = tsubst (decl, args, complain, in_decl);
11807             /* Prevent instantiate_decl from trying to instantiate
11808                this variable.  We've already done all that needs to be
11809                done.  */
11810             if (decl != error_mark_node)
11811               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11812           }
11813         stmt = begin_handler ();
11814         finish_handler_parms (decl, stmt);
11815         RECUR (HANDLER_BODY (t));
11816         finish_handler (stmt);
11817       }
11818       break;
11819
11820     case TAG_DEFN:
11821       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11822       break;
11823
11824     case STATIC_ASSERT:
11825       {
11826         tree condition = 
11827           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11828                        args,
11829                        complain, in_decl,
11830                        /*integral_constant_expression_p=*/true);
11831         finish_static_assert (condition,
11832                               STATIC_ASSERT_MESSAGE (t),
11833                               STATIC_ASSERT_SOURCE_LOCATION (t),
11834                               /*member_p=*/false);
11835       }
11836       break;
11837
11838     case OMP_PARALLEL:
11839       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11840                                 args, complain, in_decl);
11841       stmt = begin_omp_parallel ();
11842       RECUR (OMP_PARALLEL_BODY (t));
11843       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11844         = OMP_PARALLEL_COMBINED (t);
11845       break;
11846
11847     case OMP_TASK:
11848       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11849                                 args, complain, in_decl);
11850       stmt = begin_omp_task ();
11851       RECUR (OMP_TASK_BODY (t));
11852       finish_omp_task (tmp, stmt);
11853       break;
11854
11855     case OMP_FOR:
11856       {
11857         tree clauses, body, pre_body;
11858         tree declv, initv, condv, incrv;
11859         int i;
11860
11861         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11862                                       args, complain, in_decl);
11863         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11864         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11865         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11866         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11867
11868         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11869           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11870                                    &clauses, args, complain, in_decl,
11871                                    integral_constant_expression_p);
11872
11873         stmt = begin_omp_structured_block ();
11874
11875         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11876           if (TREE_VEC_ELT (initv, i) == NULL
11877               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11878             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11879           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11880             {
11881               tree init = RECUR (TREE_VEC_ELT (initv, i));
11882               gcc_assert (init == TREE_VEC_ELT (declv, i));
11883               TREE_VEC_ELT (initv, i) = NULL_TREE;
11884             }
11885           else
11886             {
11887               tree decl_expr = TREE_VEC_ELT (initv, i);
11888               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11889               gcc_assert (init != NULL);
11890               TREE_VEC_ELT (initv, i) = RECUR (init);
11891               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11892               RECUR (decl_expr);
11893               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11894             }
11895
11896         pre_body = push_stmt_list ();
11897         RECUR (OMP_FOR_PRE_BODY (t));
11898         pre_body = pop_stmt_list (pre_body);
11899
11900         body = push_stmt_list ();
11901         RECUR (OMP_FOR_BODY (t));
11902         body = pop_stmt_list (body);
11903
11904         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11905                             body, pre_body, clauses);
11906
11907         add_stmt (finish_omp_structured_block (stmt));
11908       }
11909       break;
11910
11911     case OMP_SECTIONS:
11912     case OMP_SINGLE:
11913       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11914       stmt = push_stmt_list ();
11915       RECUR (OMP_BODY (t));
11916       stmt = pop_stmt_list (stmt);
11917
11918       t = copy_node (t);
11919       OMP_BODY (t) = stmt;
11920       OMP_CLAUSES (t) = tmp;
11921       add_stmt (t);
11922       break;
11923
11924     case OMP_SECTION:
11925     case OMP_CRITICAL:
11926     case OMP_MASTER:
11927     case OMP_ORDERED:
11928       stmt = push_stmt_list ();
11929       RECUR (OMP_BODY (t));
11930       stmt = pop_stmt_list (stmt);
11931
11932       t = copy_node (t);
11933       OMP_BODY (t) = stmt;
11934       add_stmt (t);
11935       break;
11936
11937     case OMP_ATOMIC:
11938       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11939       {
11940         tree op1 = TREE_OPERAND (t, 1);
11941         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11942         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11943         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11944       }
11945       break;
11946
11947     case EXPR_PACK_EXPANSION:
11948       error ("invalid use of pack expansion expression");
11949       return error_mark_node;
11950
11951     case NONTYPE_ARGUMENT_PACK:
11952       error ("use %<...%> to expand argument pack");
11953       return error_mark_node;
11954
11955     default:
11956       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11957
11958       return tsubst_copy_and_build (t, args, complain, in_decl,
11959                                     /*function_p=*/false,
11960                                     integral_constant_expression_p);
11961     }
11962
11963   return NULL_TREE;
11964 #undef RECUR
11965 }
11966
11967 /* T is a postfix-expression that is not being used in a function
11968    call.  Return the substituted version of T.  */
11969
11970 static tree
11971 tsubst_non_call_postfix_expression (tree t, tree args,
11972                                     tsubst_flags_t complain,
11973                                     tree in_decl)
11974 {
11975   if (TREE_CODE (t) == SCOPE_REF)
11976     t = tsubst_qualified_id (t, args, complain, in_decl,
11977                              /*done=*/false, /*address_p=*/false);
11978   else
11979     t = tsubst_copy_and_build (t, args, complain, in_decl,
11980                                /*function_p=*/false,
11981                                /*integral_constant_expression_p=*/false);
11982
11983   return t;
11984 }
11985
11986 /* Like tsubst but deals with expressions and performs semantic
11987    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11988
11989 tree
11990 tsubst_copy_and_build (tree t,
11991                        tree args,
11992                        tsubst_flags_t complain,
11993                        tree in_decl,
11994                        bool function_p,
11995                        bool integral_constant_expression_p)
11996 {
11997 #define RECUR(NODE)                                             \
11998   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11999                          /*function_p=*/false,                  \
12000                          integral_constant_expression_p)
12001
12002   tree op1;
12003
12004   if (t == NULL_TREE || t == error_mark_node)
12005     return t;
12006
12007   switch (TREE_CODE (t))
12008     {
12009     case USING_DECL:
12010       t = DECL_NAME (t);
12011       /* Fall through.  */
12012     case IDENTIFIER_NODE:
12013       {
12014         tree decl;
12015         cp_id_kind idk;
12016         bool non_integral_constant_expression_p;
12017         const char *error_msg;
12018
12019         if (IDENTIFIER_TYPENAME_P (t))
12020           {
12021             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12022             t = mangle_conv_op_name_for_type (new_type);
12023           }
12024
12025         /* Look up the name.  */
12026         decl = lookup_name (t);
12027
12028         /* By convention, expressions use ERROR_MARK_NODE to indicate
12029            failure, not NULL_TREE.  */
12030         if (decl == NULL_TREE)
12031           decl = error_mark_node;
12032
12033         decl = finish_id_expression (t, decl, NULL_TREE,
12034                                      &idk,
12035                                      integral_constant_expression_p,
12036                                      /*allow_non_integral_constant_expression_p=*/false,
12037                                      &non_integral_constant_expression_p,
12038                                      /*template_p=*/false,
12039                                      /*done=*/true,
12040                                      /*address_p=*/false,
12041                                      /*template_arg_p=*/false,
12042                                      &error_msg,
12043                                      input_location);
12044         if (error_msg)
12045           error (error_msg);
12046         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12047           decl = unqualified_name_lookup_error (decl);
12048         return decl;
12049       }
12050
12051     case TEMPLATE_ID_EXPR:
12052       {
12053         tree object;
12054         tree templ = RECUR (TREE_OPERAND (t, 0));
12055         tree targs = TREE_OPERAND (t, 1);
12056
12057         if (targs)
12058           targs = tsubst_template_args (targs, args, complain, in_decl);
12059
12060         if (TREE_CODE (templ) == COMPONENT_REF)
12061           {
12062             object = TREE_OPERAND (templ, 0);
12063             templ = TREE_OPERAND (templ, 1);
12064           }
12065         else
12066           object = NULL_TREE;
12067         templ = lookup_template_function (templ, targs);
12068
12069         if (object)
12070           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12071                          object, templ, NULL_TREE);
12072         else
12073           return baselink_for_fns (templ);
12074       }
12075
12076     case INDIRECT_REF:
12077       {
12078         tree r = RECUR (TREE_OPERAND (t, 0));
12079
12080         if (REFERENCE_REF_P (t))
12081           {
12082             /* A type conversion to reference type will be enclosed in
12083                such an indirect ref, but the substitution of the cast
12084                will have also added such an indirect ref.  */
12085             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12086               r = convert_from_reference (r);
12087           }
12088         else
12089           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12090         return r;
12091       }
12092
12093     case NOP_EXPR:
12094       return build_nop
12095         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12096          RECUR (TREE_OPERAND (t, 0)));
12097
12098     case CAST_EXPR:
12099     case REINTERPRET_CAST_EXPR:
12100     case CONST_CAST_EXPR:
12101     case DYNAMIC_CAST_EXPR:
12102     case STATIC_CAST_EXPR:
12103       {
12104         tree type;
12105         tree op;
12106
12107         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12108         if (integral_constant_expression_p
12109             && !cast_valid_in_integral_constant_expression_p (type))
12110           {
12111             if (complain & tf_error)
12112               error ("a cast to a type other than an integral or "
12113                      "enumeration type cannot appear in a constant-expression");
12114             return error_mark_node; 
12115           }
12116
12117         op = RECUR (TREE_OPERAND (t, 0));
12118
12119         switch (TREE_CODE (t))
12120           {
12121           case CAST_EXPR:
12122             return build_functional_cast (type, op, complain);
12123           case REINTERPRET_CAST_EXPR:
12124             return build_reinterpret_cast (type, op, complain);
12125           case CONST_CAST_EXPR:
12126             return build_const_cast (type, op, complain);
12127           case DYNAMIC_CAST_EXPR:
12128             return build_dynamic_cast (type, op, complain);
12129           case STATIC_CAST_EXPR:
12130             return build_static_cast (type, op, complain);
12131           default:
12132             gcc_unreachable ();
12133           }
12134       }
12135
12136     case POSTDECREMENT_EXPR:
12137     case POSTINCREMENT_EXPR:
12138       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12139                                                 args, complain, in_decl);
12140       return build_x_unary_op (TREE_CODE (t), op1, complain);
12141
12142     case PREDECREMENT_EXPR:
12143     case PREINCREMENT_EXPR:
12144     case NEGATE_EXPR:
12145     case BIT_NOT_EXPR:
12146     case ABS_EXPR:
12147     case TRUTH_NOT_EXPR:
12148     case UNARY_PLUS_EXPR:  /* Unary + */
12149     case REALPART_EXPR:
12150     case IMAGPART_EXPR:
12151       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12152                                complain);
12153
12154     case ADDR_EXPR:
12155       op1 = TREE_OPERAND (t, 0);
12156       if (TREE_CODE (op1) == SCOPE_REF)
12157         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12158                                    /*done=*/true, /*address_p=*/true);
12159       else
12160         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12161                                                   in_decl);
12162       if (TREE_CODE (op1) == LABEL_DECL)
12163         return finish_label_address_expr (DECL_NAME (op1),
12164                                           EXPR_LOCATION (op1));
12165       return build_x_unary_op (ADDR_EXPR, op1, complain);
12166
12167     case PLUS_EXPR:
12168     case MINUS_EXPR:
12169     case MULT_EXPR:
12170     case TRUNC_DIV_EXPR:
12171     case CEIL_DIV_EXPR:
12172     case FLOOR_DIV_EXPR:
12173     case ROUND_DIV_EXPR:
12174     case EXACT_DIV_EXPR:
12175     case BIT_AND_EXPR:
12176     case BIT_IOR_EXPR:
12177     case BIT_XOR_EXPR:
12178     case TRUNC_MOD_EXPR:
12179     case FLOOR_MOD_EXPR:
12180     case TRUTH_ANDIF_EXPR:
12181     case TRUTH_ORIF_EXPR:
12182     case TRUTH_AND_EXPR:
12183     case TRUTH_OR_EXPR:
12184     case RSHIFT_EXPR:
12185     case LSHIFT_EXPR:
12186     case RROTATE_EXPR:
12187     case LROTATE_EXPR:
12188     case EQ_EXPR:
12189     case NE_EXPR:
12190     case MAX_EXPR:
12191     case MIN_EXPR:
12192     case LE_EXPR:
12193     case GE_EXPR:
12194     case LT_EXPR:
12195     case GT_EXPR:
12196     case MEMBER_REF:
12197     case DOTSTAR_EXPR:
12198       return build_x_binary_op
12199         (TREE_CODE (t),
12200          RECUR (TREE_OPERAND (t, 0)),
12201          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12202           ? ERROR_MARK
12203           : TREE_CODE (TREE_OPERAND (t, 0))),
12204          RECUR (TREE_OPERAND (t, 1)),
12205          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12206           ? ERROR_MARK
12207           : TREE_CODE (TREE_OPERAND (t, 1))),
12208          /*overloaded_p=*/NULL,
12209          complain);
12210
12211     case SCOPE_REF:
12212       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12213                                   /*address_p=*/false);
12214     case ARRAY_REF:
12215       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12216                                                 args, complain, in_decl);
12217       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12218
12219     case SIZEOF_EXPR:
12220       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12221         return tsubst_copy (t, args, complain, in_decl);
12222       /* Fall through */
12223       
12224     case ALIGNOF_EXPR:
12225       op1 = TREE_OPERAND (t, 0);
12226       if (!args)
12227         {
12228           /* When there are no ARGS, we are trying to evaluate a
12229              non-dependent expression from the parser.  Trying to do
12230              the substitutions may not work.  */
12231           if (!TYPE_P (op1))
12232             op1 = TREE_TYPE (op1);
12233         }
12234       else
12235         {
12236           ++cp_unevaluated_operand;
12237           ++c_inhibit_evaluation_warnings;
12238           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12239                                        /*function_p=*/false,
12240                                        /*integral_constant_expression_p=*/false);
12241           --cp_unevaluated_operand;
12242           --c_inhibit_evaluation_warnings;
12243         }
12244       if (TYPE_P (op1))
12245         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12246                                            complain & tf_error);
12247       else
12248         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12249                                            complain & tf_error);
12250
12251     case MODOP_EXPR:
12252       {
12253         tree r = build_x_modify_expr
12254           (RECUR (TREE_OPERAND (t, 0)),
12255            TREE_CODE (TREE_OPERAND (t, 1)),
12256            RECUR (TREE_OPERAND (t, 2)),
12257            complain);
12258         /* TREE_NO_WARNING must be set if either the expression was
12259            parenthesized or it uses an operator such as >>= rather
12260            than plain assignment.  In the former case, it was already
12261            set and must be copied.  In the latter case,
12262            build_x_modify_expr sets it and it must not be reset
12263            here.  */
12264         if (TREE_NO_WARNING (t))
12265           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12266         return r;
12267       }
12268
12269     case ARROW_EXPR:
12270       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12271                                                 args, complain, in_decl);
12272       /* Remember that there was a reference to this entity.  */
12273       if (DECL_P (op1))
12274         mark_used (op1);
12275       return build_x_arrow (op1);
12276
12277     case NEW_EXPR:
12278       {
12279         tree placement = RECUR (TREE_OPERAND (t, 0));
12280         tree init = RECUR (TREE_OPERAND (t, 3));
12281         VEC(tree,gc) *placement_vec;
12282         VEC(tree,gc) *init_vec;
12283         tree ret;
12284
12285         if (placement == NULL_TREE)
12286           placement_vec = NULL;
12287         else
12288           {
12289             placement_vec = make_tree_vector ();
12290             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12291               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12292           }
12293
12294         /* If there was an initializer in the original tree, but it
12295            instantiated to an empty list, then we should pass a
12296            non-NULL empty vector to tell build_new that it was an
12297            empty initializer() rather than no initializer.  This can
12298            only happen when the initializer is a pack expansion whose
12299            parameter packs are of length zero.  */
12300         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12301           init_vec = NULL;
12302         else
12303           {
12304             init_vec = make_tree_vector ();
12305             if (init == void_zero_node)
12306               gcc_assert (init_vec != NULL);
12307             else
12308               {
12309                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12310                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12311               }
12312           }
12313
12314         ret = build_new (&placement_vec,
12315                          RECUR (TREE_OPERAND (t, 1)),
12316                          RECUR (TREE_OPERAND (t, 2)),
12317                          &init_vec,
12318                          NEW_EXPR_USE_GLOBAL (t),
12319                          complain);
12320
12321         if (placement_vec != NULL)
12322           release_tree_vector (placement_vec);
12323         if (init_vec != NULL)
12324           release_tree_vector (init_vec);
12325
12326         return ret;
12327       }
12328
12329     case DELETE_EXPR:
12330      return delete_sanity
12331        (RECUR (TREE_OPERAND (t, 0)),
12332         RECUR (TREE_OPERAND (t, 1)),
12333         DELETE_EXPR_USE_VEC (t),
12334         DELETE_EXPR_USE_GLOBAL (t));
12335
12336     case COMPOUND_EXPR:
12337       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12338                                     RECUR (TREE_OPERAND (t, 1)),
12339                                     complain);
12340
12341     case CALL_EXPR:
12342       {
12343         tree function;
12344         VEC(tree,gc) *call_args;
12345         unsigned int nargs, i;
12346         bool qualified_p;
12347         bool koenig_p;
12348         tree ret;
12349
12350         function = CALL_EXPR_FN (t);
12351         /* When we parsed the expression,  we determined whether or
12352            not Koenig lookup should be performed.  */
12353         koenig_p = KOENIG_LOOKUP_P (t);
12354         if (TREE_CODE (function) == SCOPE_REF)
12355           {
12356             qualified_p = true;
12357             function = tsubst_qualified_id (function, args, complain, in_decl,
12358                                             /*done=*/false,
12359                                             /*address_p=*/false);
12360           }
12361         else
12362           {
12363             if (TREE_CODE (function) == COMPONENT_REF)
12364               {
12365                 tree op = TREE_OPERAND (function, 1);
12366
12367                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12368                                || (BASELINK_P (op)
12369                                    && BASELINK_QUALIFIED_P (op)));
12370               }
12371             else
12372               qualified_p = false;
12373
12374             function = tsubst_copy_and_build (function, args, complain,
12375                                               in_decl,
12376                                               !qualified_p,
12377                                               integral_constant_expression_p);
12378
12379             if (BASELINK_P (function))
12380               qualified_p = true;
12381           }
12382
12383         nargs = call_expr_nargs (t);
12384         call_args = make_tree_vector ();
12385         for (i = 0; i < nargs; ++i)
12386           {
12387             tree arg = CALL_EXPR_ARG (t, i);
12388
12389             if (!PACK_EXPANSION_P (arg))
12390               VEC_safe_push (tree, gc, call_args,
12391                              RECUR (CALL_EXPR_ARG (t, i)));
12392             else
12393               {
12394                 /* Expand the pack expansion and push each entry onto
12395                    CALL_ARGS.  */
12396                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12397                 if (TREE_CODE (arg) == TREE_VEC)
12398                   {
12399                     unsigned int len, j;
12400
12401                     len = TREE_VEC_LENGTH (arg);
12402                     for (j = 0; j < len; ++j)
12403                       {
12404                         tree value = TREE_VEC_ELT (arg, j);
12405                         if (value != NULL_TREE)
12406                           value = convert_from_reference (value);
12407                         VEC_safe_push (tree, gc, call_args, value);
12408                       }
12409                   }
12410                 else
12411                   {
12412                     /* A partial substitution.  Add one entry.  */
12413                     VEC_safe_push (tree, gc, call_args, arg);
12414                   }
12415               }
12416           }
12417
12418         /* We do not perform argument-dependent lookup if normal
12419            lookup finds a non-function, in accordance with the
12420            expected resolution of DR 218.  */
12421         if (koenig_p
12422             && ((is_overloaded_fn (function)
12423                  /* If lookup found a member function, the Koenig lookup is
12424                     not appropriate, even if an unqualified-name was used
12425                     to denote the function.  */
12426                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12427                 || TREE_CODE (function) == IDENTIFIER_NODE)
12428             /* Only do this when substitution turns a dependent call
12429                into a non-dependent call.  */
12430             && type_dependent_expression_p_push (t)
12431             && !any_type_dependent_arguments_p (call_args))
12432           function = perform_koenig_lookup (function, call_args);
12433
12434         if (TREE_CODE (function) == IDENTIFIER_NODE)
12435           {
12436             unqualified_name_lookup_error (function);
12437             release_tree_vector (call_args);
12438             return error_mark_node;
12439           }
12440
12441         /* Remember that there was a reference to this entity.  */
12442         if (DECL_P (function))
12443           mark_used (function);
12444
12445         if (TREE_CODE (function) == OFFSET_REF)
12446           ret = build_offset_ref_call_from_tree (function, &call_args);
12447         else if (TREE_CODE (function) == COMPONENT_REF)
12448           {
12449             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12450               ret = finish_call_expr (function, &call_args,
12451                                        /*disallow_virtual=*/false,
12452                                        /*koenig_p=*/false,
12453                                        complain);
12454             else
12455               ret = (build_new_method_call
12456                       (TREE_OPERAND (function, 0),
12457                        TREE_OPERAND (function, 1),
12458                        &call_args, NULL_TREE,
12459                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12460                        /*fn_p=*/NULL,
12461                        complain));
12462           }
12463         else
12464           ret = finish_call_expr (function, &call_args,
12465                                   /*disallow_virtual=*/qualified_p,
12466                                   koenig_p,
12467                                   complain);
12468
12469         release_tree_vector (call_args);
12470
12471         return ret;
12472       }
12473
12474     case COND_EXPR:
12475       return build_x_conditional_expr
12476         (RECUR (TREE_OPERAND (t, 0)),
12477          RECUR (TREE_OPERAND (t, 1)),
12478          RECUR (TREE_OPERAND (t, 2)),
12479          complain);
12480
12481     case PSEUDO_DTOR_EXPR:
12482       return finish_pseudo_destructor_expr
12483         (RECUR (TREE_OPERAND (t, 0)),
12484          RECUR (TREE_OPERAND (t, 1)),
12485          RECUR (TREE_OPERAND (t, 2)));
12486
12487     case TREE_LIST:
12488       {
12489         tree purpose, value, chain;
12490
12491         if (t == void_list_node)
12492           return t;
12493
12494         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12495             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12496           {
12497             /* We have pack expansions, so expand those and
12498                create a new list out of it.  */
12499             tree purposevec = NULL_TREE;
12500             tree valuevec = NULL_TREE;
12501             tree chain;
12502             int i, len = -1;
12503
12504             /* Expand the argument expressions.  */
12505             if (TREE_PURPOSE (t))
12506               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12507                                                  complain, in_decl);
12508             if (TREE_VALUE (t))
12509               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12510                                                complain, in_decl);
12511
12512             /* Build the rest of the list.  */
12513             chain = TREE_CHAIN (t);
12514             if (chain && chain != void_type_node)
12515               chain = RECUR (chain);
12516
12517             /* Determine the number of arguments.  */
12518             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12519               {
12520                 len = TREE_VEC_LENGTH (purposevec);
12521                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12522               }
12523             else if (TREE_CODE (valuevec) == TREE_VEC)
12524               len = TREE_VEC_LENGTH (valuevec);
12525             else
12526               {
12527                 /* Since we only performed a partial substitution into
12528                    the argument pack, we only return a single list
12529                    node.  */
12530                 if (purposevec == TREE_PURPOSE (t)
12531                     && valuevec == TREE_VALUE (t)
12532                     && chain == TREE_CHAIN (t))
12533                   return t;
12534
12535                 return tree_cons (purposevec, valuevec, chain);
12536               }
12537             
12538             /* Convert the argument vectors into a TREE_LIST */
12539             i = len;
12540             while (i > 0)
12541               {
12542                 /* Grab the Ith values.  */
12543                 i--;
12544                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12545                                      : NULL_TREE;
12546                 value 
12547                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12548                              : NULL_TREE;
12549
12550                 /* Build the list (backwards).  */
12551                 chain = tree_cons (purpose, value, chain);
12552               }
12553
12554             return chain;
12555           }
12556
12557         purpose = TREE_PURPOSE (t);
12558         if (purpose)
12559           purpose = RECUR (purpose);
12560         value = TREE_VALUE (t);
12561         if (value)
12562           value = RECUR (value);
12563         chain = TREE_CHAIN (t);
12564         if (chain && chain != void_type_node)
12565           chain = RECUR (chain);
12566         if (purpose == TREE_PURPOSE (t)
12567             && value == TREE_VALUE (t)
12568             && chain == TREE_CHAIN (t))
12569           return t;
12570         return tree_cons (purpose, value, chain);
12571       }
12572
12573     case COMPONENT_REF:
12574       {
12575         tree object;
12576         tree object_type;
12577         tree member;
12578
12579         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12580                                                      args, complain, in_decl);
12581         /* Remember that there was a reference to this entity.  */
12582         if (DECL_P (object))
12583           mark_used (object);
12584         object_type = TREE_TYPE (object);
12585
12586         member = TREE_OPERAND (t, 1);
12587         if (BASELINK_P (member))
12588           member = tsubst_baselink (member,
12589                                     non_reference (TREE_TYPE (object)),
12590                                     args, complain, in_decl);
12591         else
12592           member = tsubst_copy (member, args, complain, in_decl);
12593         if (member == error_mark_node)
12594           return error_mark_node;
12595
12596         if (object_type && !CLASS_TYPE_P (object_type))
12597           {
12598             if (SCALAR_TYPE_P (object_type))
12599               {
12600                 tree s = NULL_TREE;
12601                 tree dtor = member;
12602
12603                 if (TREE_CODE (dtor) == SCOPE_REF)
12604                   {
12605                     s = TREE_OPERAND (dtor, 0);
12606                     dtor = TREE_OPERAND (dtor, 1);
12607                   }
12608                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12609                   {
12610                     dtor = TREE_OPERAND (dtor, 0);
12611                     if (TYPE_P (dtor))
12612                       return finish_pseudo_destructor_expr (object, s, dtor);
12613                   }
12614               }
12615           }
12616         else if (TREE_CODE (member) == SCOPE_REF
12617                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12618           {
12619             tree tmpl;
12620             tree args;
12621
12622             /* Lookup the template functions now that we know what the
12623                scope is.  */
12624             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12625             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12626             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12627                                             /*is_type_p=*/false,
12628                                             /*complain=*/false);
12629             if (BASELINK_P (member))
12630               {
12631                 BASELINK_FUNCTIONS (member)
12632                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12633                               args);
12634                 member = (adjust_result_of_qualified_name_lookup
12635                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12636                            object_type));
12637               }
12638             else
12639               {
12640                 qualified_name_lookup_error (object_type, tmpl, member,
12641                                              input_location);
12642                 return error_mark_node;
12643               }
12644           }
12645         else if (TREE_CODE (member) == SCOPE_REF
12646                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12647                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12648           {
12649             if (complain & tf_error)
12650               {
12651                 if (TYPE_P (TREE_OPERAND (member, 0)))
12652                   error ("%qT is not a class or namespace",
12653                          TREE_OPERAND (member, 0));
12654                 else
12655                   error ("%qD is not a class or namespace",
12656                          TREE_OPERAND (member, 0));
12657               }
12658             return error_mark_node;
12659           }
12660         else if (TREE_CODE (member) == FIELD_DECL)
12661           return finish_non_static_data_member (member, object, NULL_TREE);
12662
12663         return finish_class_member_access_expr (object, member,
12664                                                 /*template_p=*/false,
12665                                                 complain);
12666       }
12667
12668     case THROW_EXPR:
12669       return build_throw
12670         (RECUR (TREE_OPERAND (t, 0)));
12671
12672     case CONSTRUCTOR:
12673       {
12674         VEC(constructor_elt,gc) *n;
12675         constructor_elt *ce;
12676         unsigned HOST_WIDE_INT idx;
12677         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12678         bool process_index_p;
12679         int newlen;
12680         bool need_copy_p = false;
12681         tree r;
12682
12683         if (type == error_mark_node)
12684           return error_mark_node;
12685
12686         /* digest_init will do the wrong thing if we let it.  */
12687         if (type && TYPE_PTRMEMFUNC_P (type))
12688           return t;
12689
12690         /* We do not want to process the index of aggregate
12691            initializers as they are identifier nodes which will be
12692            looked up by digest_init.  */
12693         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12694
12695         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12696         newlen = VEC_length (constructor_elt, n);
12697         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12698           {
12699             if (ce->index && process_index_p)
12700               ce->index = RECUR (ce->index);
12701
12702             if (PACK_EXPANSION_P (ce->value))
12703               {
12704                 /* Substitute into the pack expansion.  */
12705                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12706                                                   in_decl);
12707
12708                 if (ce->value == error_mark_node)
12709                   ;
12710                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12711                   /* Just move the argument into place.  */
12712                   ce->value = TREE_VEC_ELT (ce->value, 0);
12713                 else
12714                   {
12715                     /* Update the length of the final CONSTRUCTOR
12716                        arguments vector, and note that we will need to
12717                        copy.*/
12718                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12719                     need_copy_p = true;
12720                   }
12721               }
12722             else
12723               ce->value = RECUR (ce->value);
12724           }
12725
12726         if (need_copy_p)
12727           {
12728             VEC(constructor_elt,gc) *old_n = n;
12729
12730             n = VEC_alloc (constructor_elt, gc, newlen);
12731             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12732                  idx++)
12733               {
12734                 if (TREE_CODE (ce->value) == TREE_VEC)
12735                   {
12736                     int i, len = TREE_VEC_LENGTH (ce->value);
12737                     for (i = 0; i < len; ++i)
12738                       CONSTRUCTOR_APPEND_ELT (n, 0,
12739                                               TREE_VEC_ELT (ce->value, i));
12740                   }
12741                 else
12742                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12743               }
12744           }
12745
12746         r = build_constructor (init_list_type_node, n);
12747         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12748
12749         if (TREE_HAS_CONSTRUCTOR (t))
12750           return finish_compound_literal (type, r);
12751
12752         return r;
12753       }
12754
12755     case TYPEID_EXPR:
12756       {
12757         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12758         if (TYPE_P (operand_0))
12759           return get_typeid (operand_0);
12760         return build_typeid (operand_0);
12761       }
12762
12763     case VAR_DECL:
12764       if (!args)
12765         return t;
12766       /* Fall through */
12767
12768     case PARM_DECL:
12769       {
12770         tree r = tsubst_copy (t, args, complain, in_decl);
12771
12772         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12773           /* If the original type was a reference, we'll be wrapped in
12774              the appropriate INDIRECT_REF.  */
12775           r = convert_from_reference (r);
12776         return r;
12777       }
12778
12779     case VA_ARG_EXPR:
12780       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12781                              tsubst_copy (TREE_TYPE (t), args, complain,
12782                                           in_decl));
12783
12784     case OFFSETOF_EXPR:
12785       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12786
12787     case TRAIT_EXPR:
12788       {
12789         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12790                                   complain, in_decl);
12791
12792         tree type2 = TRAIT_EXPR_TYPE2 (t);
12793         if (type2)
12794           type2 = tsubst_copy (type2, args, complain, in_decl);
12795         
12796         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12797       }
12798
12799     case STMT_EXPR:
12800       {
12801         tree old_stmt_expr = cur_stmt_expr;
12802         tree stmt_expr = begin_stmt_expr ();
12803
12804         cur_stmt_expr = stmt_expr;
12805         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12806                      integral_constant_expression_p);
12807         stmt_expr = finish_stmt_expr (stmt_expr, false);
12808         cur_stmt_expr = old_stmt_expr;
12809
12810         /* If the resulting list of expression statement is empty,
12811            fold it further into void_zero_node.  */
12812         if (empty_expr_stmt_p (stmt_expr))
12813           stmt_expr = void_zero_node;
12814
12815         return stmt_expr;
12816       }
12817
12818     case CONST_DECL:
12819       t = tsubst_copy (t, args, complain, in_decl);
12820       /* As in finish_id_expression, we resolve enumeration constants
12821          to their underlying values.  */
12822       if (TREE_CODE (t) == CONST_DECL)
12823         {
12824           used_types_insert (TREE_TYPE (t));
12825           return DECL_INITIAL (t);
12826         }
12827       return t;
12828
12829     case LAMBDA_EXPR:
12830       {
12831         tree r = build_lambda_expr ();
12832
12833         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12834         TREE_TYPE (r) = type;
12835         CLASSTYPE_LAMBDA_EXPR (type) = r;
12836
12837         LAMBDA_EXPR_LOCATION (r)
12838           = LAMBDA_EXPR_LOCATION (t);
12839         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12840           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12841         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12842         LAMBDA_EXPR_DISCRIMINATOR (r)
12843           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12844         LAMBDA_EXPR_CAPTURE_LIST (r)
12845           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12846         LAMBDA_EXPR_THIS_CAPTURE (r)
12847           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12848         LAMBDA_EXPR_EXTRA_SCOPE (r)
12849           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12850
12851         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12852         determine_visibility (TYPE_NAME (type));
12853         /* Now that we know visibility, instantiate the type so we have a
12854            declaration of the op() for later calls to lambda_function.  */
12855         complete_type (type);
12856
12857         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12858         if (type)
12859           apply_lambda_return_type (r, type);
12860
12861         return build_lambda_object (r);
12862       }
12863
12864     default:
12865       /* Handle Objective-C++ constructs, if appropriate.  */
12866       {
12867         tree subst
12868           = objcp_tsubst_copy_and_build (t, args, complain,
12869                                          in_decl, /*function_p=*/false);
12870         if (subst)
12871           return subst;
12872       }
12873       return tsubst_copy (t, args, complain, in_decl);
12874     }
12875
12876 #undef RECUR
12877 }
12878
12879 /* Verify that the instantiated ARGS are valid. For type arguments,
12880    make sure that the type's linkage is ok. For non-type arguments,
12881    make sure they are constants if they are integral or enumerations.
12882    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12883
12884 static bool
12885 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12886 {
12887   if (ARGUMENT_PACK_P (t))
12888     {
12889       tree vec = ARGUMENT_PACK_ARGS (t);
12890       int len = TREE_VEC_LENGTH (vec);
12891       bool result = false;
12892       int i;
12893
12894       for (i = 0; i < len; ++i)
12895         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12896           result = true;
12897       return result;
12898     }
12899   else if (TYPE_P (t))
12900     {
12901       /* [basic.link]: A name with no linkage (notably, the name
12902          of a class or enumeration declared in a local scope)
12903          shall not be used to declare an entity with linkage.
12904          This implies that names with no linkage cannot be used as
12905          template arguments
12906
12907          DR 757 relaxes this restriction for C++0x.  */
12908       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12909                  : no_linkage_check (t, /*relaxed_p=*/false));
12910
12911       if (nt)
12912         {
12913           /* DR 488 makes use of a type with no linkage cause
12914              type deduction to fail.  */
12915           if (complain & tf_error)
12916             {
12917               if (TYPE_ANONYMOUS_P (nt))
12918                 error ("%qT is/uses anonymous type", t);
12919               else
12920                 error ("template argument for %qD uses local type %qT",
12921                        tmpl, t);
12922             }
12923           return true;
12924         }
12925       /* In order to avoid all sorts of complications, we do not
12926          allow variably-modified types as template arguments.  */
12927       else if (variably_modified_type_p (t, NULL_TREE))
12928         {
12929           if (complain & tf_error)
12930             error ("%qT is a variably modified type", t);
12931           return true;
12932         }
12933     }
12934   /* A non-type argument of integral or enumerated type must be a
12935      constant.  */
12936   else if (TREE_TYPE (t)
12937            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12938            && !TREE_CONSTANT (t))
12939     {
12940       if (complain & tf_error)
12941         error ("integral expression %qE is not constant", t);
12942       return true;
12943     }
12944   return false;
12945 }
12946
12947 static bool
12948 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12949 {
12950   int ix, len = DECL_NTPARMS (tmpl);
12951   bool result = false;
12952
12953   for (ix = 0; ix != len; ix++)
12954     {
12955       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12956         result = true;
12957     }
12958   if (result && (complain & tf_error))
12959     error ("  trying to instantiate %qD", tmpl);
12960   return result;
12961 }
12962
12963 /* Instantiate the indicated variable or function template TMPL with
12964    the template arguments in TARG_PTR.  */
12965
12966 tree
12967 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12968 {
12969   tree targ_ptr = orig_args;
12970   tree fndecl;
12971   tree gen_tmpl;
12972   tree spec;
12973   HOST_WIDE_INT saved_processing_template_decl;
12974
12975   if (tmpl == error_mark_node)
12976     return error_mark_node;
12977
12978   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12979
12980   /* If this function is a clone, handle it specially.  */
12981   if (DECL_CLONED_FUNCTION_P (tmpl))
12982     {
12983       tree spec;
12984       tree clone;
12985
12986       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12987          DECL_CLONED_FUNCTION.  */
12988       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12989                                    targ_ptr, complain);
12990       if (spec == error_mark_node)
12991         return error_mark_node;
12992
12993       /* Look for the clone.  */
12994       FOR_EACH_CLONE (clone, spec)
12995         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12996           return clone;
12997       /* We should always have found the clone by now.  */
12998       gcc_unreachable ();
12999       return NULL_TREE;
13000     }
13001
13002   /* Check to see if we already have this specialization.  */
13003   gen_tmpl = most_general_template (tmpl);
13004   if (tmpl != gen_tmpl)
13005     /* The TMPL is a partial instantiation.  To get a full set of
13006        arguments we must add the arguments used to perform the
13007        partial instantiation.  */
13008     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13009                                             targ_ptr);
13010
13011   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13012      but it doesn't seem to be on the hot path.  */
13013   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13014
13015   gcc_assert (tmpl == gen_tmpl
13016               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13017                   == spec)
13018               || fndecl == NULL_TREE);
13019
13020   if (spec != NULL_TREE)
13021     return spec;
13022
13023   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13024                                complain))
13025     return error_mark_node;
13026
13027   /* We are building a FUNCTION_DECL, during which the access of its
13028      parameters and return types have to be checked.  However this
13029      FUNCTION_DECL which is the desired context for access checking
13030      is not built yet.  We solve this chicken-and-egg problem by
13031      deferring all checks until we have the FUNCTION_DECL.  */
13032   push_deferring_access_checks (dk_deferred);
13033
13034   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13035      (because, for example, we have encountered a non-dependent
13036      function call in the body of a template function and must now
13037      determine which of several overloaded functions will be called),
13038      within the instantiation itself we are not processing a
13039      template.  */  
13040   saved_processing_template_decl = processing_template_decl;
13041   processing_template_decl = 0;
13042   /* Substitute template parameters to obtain the specialization.  */
13043   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13044                    targ_ptr, complain, gen_tmpl);
13045   processing_template_decl = saved_processing_template_decl;
13046   if (fndecl == error_mark_node)
13047     return error_mark_node;
13048
13049   /* Now we know the specialization, compute access previously
13050      deferred.  */
13051   push_access_scope (fndecl);
13052
13053   /* Some typedefs referenced from within the template code need to be access
13054      checked at template instantiation time, i.e now. These types were
13055      added to the template at parsing time. Let's get those and perfom
13056      the acces checks then.  */
13057   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13058   perform_deferred_access_checks ();
13059   pop_access_scope (fndecl);
13060   pop_deferring_access_checks ();
13061
13062   /* The DECL_TI_TEMPLATE should always be the immediate parent
13063      template, not the most general template.  */
13064   DECL_TI_TEMPLATE (fndecl) = tmpl;
13065
13066   /* If we've just instantiated the main entry point for a function,
13067      instantiate all the alternate entry points as well.  We do this
13068      by cloning the instantiation of the main entry point, not by
13069      instantiating the template clones.  */
13070   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13071     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13072
13073   return fndecl;
13074 }
13075
13076 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13077    NARGS elements of the arguments that are being used when calling
13078    it.  TARGS is a vector into which the deduced template arguments
13079    are placed.
13080
13081    Return zero for success, 2 for an incomplete match that doesn't resolve
13082    all the types, and 1 for complete failure.  An error message will be
13083    printed only for an incomplete match.
13084
13085    If FN is a conversion operator, or we are trying to produce a specific
13086    specialization, RETURN_TYPE is the return type desired.
13087
13088    The EXPLICIT_TARGS are explicit template arguments provided via a
13089    template-id.
13090
13091    The parameter STRICT is one of:
13092
13093    DEDUCE_CALL:
13094      We are deducing arguments for a function call, as in
13095      [temp.deduct.call].
13096
13097    DEDUCE_CONV:
13098      We are deducing arguments for a conversion function, as in
13099      [temp.deduct.conv].
13100
13101    DEDUCE_EXACT:
13102      We are deducing arguments when doing an explicit instantiation
13103      as in [temp.explicit], when determining an explicit specialization
13104      as in [temp.expl.spec], or when taking the address of a function
13105      template, as in [temp.deduct.funcaddr].  */
13106
13107 int
13108 fn_type_unification (tree fn,
13109                      tree explicit_targs,
13110                      tree targs,
13111                      const tree *args,
13112                      unsigned int nargs,
13113                      tree return_type,
13114                      unification_kind_t strict,
13115                      int flags)
13116 {
13117   tree parms;
13118   tree fntype;
13119   int result;
13120   bool incomplete_argument_packs_p = false;
13121
13122   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13123
13124   fntype = TREE_TYPE (fn);
13125   if (explicit_targs)
13126     {
13127       /* [temp.deduct]
13128
13129          The specified template arguments must match the template
13130          parameters in kind (i.e., type, nontype, template), and there
13131          must not be more arguments than there are parameters;
13132          otherwise type deduction fails.
13133
13134          Nontype arguments must match the types of the corresponding
13135          nontype template parameters, or must be convertible to the
13136          types of the corresponding nontype parameters as specified in
13137          _temp.arg.nontype_, otherwise type deduction fails.
13138
13139          All references in the function type of the function template
13140          to the corresponding template parameters are replaced by the
13141          specified template argument values.  If a substitution in a
13142          template parameter or in the function type of the function
13143          template results in an invalid type, type deduction fails.  */
13144       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13145       int i, len = TREE_VEC_LENGTH (tparms);
13146       tree converted_args;
13147       bool incomplete = false;
13148
13149       if (explicit_targs == error_mark_node)
13150         return 1;
13151
13152       converted_args
13153         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13154                                   /*require_all_args=*/false,
13155                                   /*use_default_args=*/false));
13156       if (converted_args == error_mark_node)
13157         return 1;
13158
13159       /* Substitute the explicit args into the function type.  This is
13160          necessary so that, for instance, explicitly declared function
13161          arguments can match null pointed constants.  If we were given
13162          an incomplete set of explicit args, we must not do semantic
13163          processing during substitution as we could create partial
13164          instantiations.  */
13165       for (i = 0; i < len; i++)
13166         {
13167           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13168           bool parameter_pack = false;
13169
13170           /* Dig out the actual parm.  */
13171           if (TREE_CODE (parm) == TYPE_DECL
13172               || TREE_CODE (parm) == TEMPLATE_DECL)
13173             {
13174               parm = TREE_TYPE (parm);
13175               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13176             }
13177           else if (TREE_CODE (parm) == PARM_DECL)
13178             {
13179               parm = DECL_INITIAL (parm);
13180               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13181             }
13182
13183           if (parameter_pack)
13184             {
13185               int level, idx;
13186               tree targ;
13187               template_parm_level_and_index (parm, &level, &idx);
13188
13189               /* Mark the argument pack as "incomplete". We could
13190                  still deduce more arguments during unification.  */
13191               targ = TMPL_ARG (converted_args, level, idx);
13192               if (targ)
13193                 {
13194                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13195                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13196                     = ARGUMENT_PACK_ARGS (targ);
13197                 }
13198
13199               /* We have some incomplete argument packs.  */
13200               incomplete_argument_packs_p = true;
13201             }
13202         }
13203
13204       if (incomplete_argument_packs_p)
13205         /* Any substitution is guaranteed to be incomplete if there
13206            are incomplete argument packs, because we can still deduce
13207            more arguments.  */
13208         incomplete = 1;
13209       else
13210         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13211
13212       processing_template_decl += incomplete;
13213       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13214       processing_template_decl -= incomplete;
13215
13216       if (fntype == error_mark_node)
13217         return 1;
13218
13219       /* Place the explicitly specified arguments in TARGS.  */
13220       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13221         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13222     }
13223
13224   /* Never do unification on the 'this' parameter.  */
13225   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13226
13227   if (return_type)
13228     {
13229       tree *new_args;
13230
13231       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13232       new_args = XALLOCAVEC (tree, nargs + 1);
13233       new_args[0] = return_type;
13234       memcpy (new_args + 1, args, nargs * sizeof (tree));
13235       args = new_args;
13236       ++nargs;
13237     }
13238
13239   /* We allow incomplete unification without an error message here
13240      because the standard doesn't seem to explicitly prohibit it.  Our
13241      callers must be ready to deal with unification failures in any
13242      event.  */
13243   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13244                                   targs, parms, args, nargs, /*subr=*/0,
13245                                   strict, flags);
13246
13247   if (result == 0 && incomplete_argument_packs_p)
13248     {
13249       int i, len = NUM_TMPL_ARGS (targs);
13250
13251       /* Clear the "incomplete" flags on all argument packs.  */
13252       for (i = 0; i < len; i++)
13253         {
13254           tree arg = TREE_VEC_ELT (targs, i);
13255           if (ARGUMENT_PACK_P (arg))
13256             {
13257               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13258               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13259             }
13260         }
13261     }
13262
13263   /* Now that we have bindings for all of the template arguments,
13264      ensure that the arguments deduced for the template template
13265      parameters have compatible template parameter lists.  We cannot
13266      check this property before we have deduced all template
13267      arguments, because the template parameter types of a template
13268      template parameter might depend on prior template parameters
13269      deduced after the template template parameter.  The following
13270      ill-formed example illustrates this issue:
13271
13272        template<typename T, template<T> class C> void f(C<5>, T);
13273
13274        template<int N> struct X {};
13275
13276        void g() {
13277          f(X<5>(), 5l); // error: template argument deduction fails
13278        }
13279
13280      The template parameter list of 'C' depends on the template type
13281      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13282      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13283      time that we deduce 'C'.  */
13284   if (result == 0
13285       && !template_template_parm_bindings_ok_p 
13286            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13287     return 1;
13288
13289   if (result == 0)
13290     /* All is well so far.  Now, check:
13291
13292        [temp.deduct]
13293
13294        When all template arguments have been deduced, all uses of
13295        template parameters in nondeduced contexts are replaced with
13296        the corresponding deduced argument values.  If the
13297        substitution results in an invalid type, as described above,
13298        type deduction fails.  */
13299     {
13300       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13301       if (substed == error_mark_node)
13302         return 1;
13303
13304       /* If we're looking for an exact match, check that what we got
13305          is indeed an exact match.  It might not be if some template
13306          parameters are used in non-deduced contexts.  */
13307       if (strict == DEDUCE_EXACT)
13308         {
13309           unsigned int i;
13310
13311           tree sarg
13312             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13313           if (return_type)
13314             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13315           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13316             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13317               return 1;
13318         }
13319     }
13320
13321   return result;
13322 }
13323
13324 /* Adjust types before performing type deduction, as described in
13325    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13326    sections are symmetric.  PARM is the type of a function parameter
13327    or the return type of the conversion function.  ARG is the type of
13328    the argument passed to the call, or the type of the value
13329    initialized with the result of the conversion function.
13330    ARG_EXPR is the original argument expression, which may be null.  */
13331
13332 static int
13333 maybe_adjust_types_for_deduction (unification_kind_t strict,
13334                                   tree* parm,
13335                                   tree* arg,
13336                                   tree arg_expr)
13337 {
13338   int result = 0;
13339
13340   switch (strict)
13341     {
13342     case DEDUCE_CALL:
13343       break;
13344
13345     case DEDUCE_CONV:
13346       {
13347         /* Swap PARM and ARG throughout the remainder of this
13348            function; the handling is precisely symmetric since PARM
13349            will initialize ARG rather than vice versa.  */
13350         tree* temp = parm;
13351         parm = arg;
13352         arg = temp;
13353         break;
13354       }
13355
13356     case DEDUCE_EXACT:
13357       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13358          too, but here handle it by stripping the reference from PARM
13359          rather than by adding it to ARG.  */
13360       if (TREE_CODE (*parm) == REFERENCE_TYPE
13361           && TYPE_REF_IS_RVALUE (*parm)
13362           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13363           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13364           && TREE_CODE (*arg) == REFERENCE_TYPE
13365           && !TYPE_REF_IS_RVALUE (*arg))
13366         *parm = TREE_TYPE (*parm);
13367       /* Nothing else to do in this case.  */
13368       return 0;
13369
13370     default:
13371       gcc_unreachable ();
13372     }
13373
13374   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13375     {
13376       /* [temp.deduct.call]
13377
13378          If P is not a reference type:
13379
13380          --If A is an array type, the pointer type produced by the
13381          array-to-pointer standard conversion (_conv.array_) is
13382          used in place of A for type deduction; otherwise,
13383
13384          --If A is a function type, the pointer type produced by
13385          the function-to-pointer standard conversion
13386          (_conv.func_) is used in place of A for type deduction;
13387          otherwise,
13388
13389          --If A is a cv-qualified type, the top level
13390          cv-qualifiers of A's type are ignored for type
13391          deduction.  */
13392       if (TREE_CODE (*arg) == ARRAY_TYPE)
13393         *arg = build_pointer_type (TREE_TYPE (*arg));
13394       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13395         *arg = build_pointer_type (*arg);
13396       else
13397         *arg = TYPE_MAIN_VARIANT (*arg);
13398     }
13399
13400   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13401      of the form T&&, where T is a template parameter, and the argument
13402      is an lvalue, T is deduced as A& */
13403   if (TREE_CODE (*parm) == REFERENCE_TYPE
13404       && TYPE_REF_IS_RVALUE (*parm)
13405       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13406       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13407       && arg_expr && real_lvalue_p (arg_expr))
13408     *arg = build_reference_type (*arg);
13409
13410   /* [temp.deduct.call]
13411
13412      If P is a cv-qualified type, the top level cv-qualifiers
13413      of P's type are ignored for type deduction.  If P is a
13414      reference type, the type referred to by P is used for
13415      type deduction.  */
13416   *parm = TYPE_MAIN_VARIANT (*parm);
13417   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13418     {
13419       *parm = TREE_TYPE (*parm);
13420       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13421     }
13422
13423   /* DR 322. For conversion deduction, remove a reference type on parm
13424      too (which has been swapped into ARG).  */
13425   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13426     *arg = TREE_TYPE (*arg);
13427
13428   return result;
13429 }
13430
13431 /* Most parms like fn_type_unification.
13432
13433    If SUBR is 1, we're being called recursively (to unify the
13434    arguments of a function or method parameter of a function
13435    template). */
13436
13437 static int
13438 type_unification_real (tree tparms,
13439                        tree targs,
13440                        tree xparms,
13441                        const tree *xargs,
13442                        unsigned int xnargs,
13443                        int subr,
13444                        unification_kind_t strict,
13445                        int flags)
13446 {
13447   tree parm, arg, arg_expr;
13448   int i;
13449   int ntparms = TREE_VEC_LENGTH (tparms);
13450   int sub_strict;
13451   int saw_undeduced = 0;
13452   tree parms;
13453   const tree *args;
13454   unsigned int nargs;
13455   unsigned int ia;
13456
13457   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13458   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13459   gcc_assert (ntparms > 0);
13460
13461   /* Reset the number of non-defaulted template arguments contained
13462      in in TARGS.  */
13463   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13464
13465   switch (strict)
13466     {
13467     case DEDUCE_CALL:
13468       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13469                     | UNIFY_ALLOW_DERIVED);
13470       break;
13471
13472     case DEDUCE_CONV:
13473       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13474       break;
13475
13476     case DEDUCE_EXACT:
13477       sub_strict = UNIFY_ALLOW_NONE;
13478       break;
13479
13480     default:
13481       gcc_unreachable ();
13482     }
13483
13484  again:
13485   parms = xparms;
13486   args = xargs;
13487   nargs = xnargs;
13488
13489   ia = 0;
13490   while (parms && parms != void_list_node
13491          && ia < nargs)
13492     {
13493       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13494         break;
13495
13496       parm = TREE_VALUE (parms);
13497       parms = TREE_CHAIN (parms);
13498       arg = args[ia];
13499       ++ia;
13500       arg_expr = NULL;
13501
13502       if (arg == error_mark_node)
13503         return 1;
13504       if (arg == unknown_type_node)
13505         /* We can't deduce anything from this, but we might get all the
13506            template args from other function args.  */
13507         continue;
13508
13509       /* Conversions will be performed on a function argument that
13510          corresponds with a function parameter that contains only
13511          non-deducible template parameters and explicitly specified
13512          template parameters.  */
13513       if (!uses_template_parms (parm))
13514         {
13515           tree type;
13516
13517           if (!TYPE_P (arg))
13518             type = TREE_TYPE (arg);
13519           else
13520             type = arg;
13521
13522           if (same_type_p (parm, type))
13523             continue;
13524           if (strict != DEDUCE_EXACT
13525               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13526                                   flags))
13527             continue;
13528
13529           return 1;
13530         }
13531
13532       if (!TYPE_P (arg))
13533         {
13534           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13535           if (type_unknown_p (arg))
13536             {
13537               /* [temp.deduct.type] 
13538
13539                  A template-argument can be deduced from a pointer to
13540                  function or pointer to member function argument if
13541                  the set of overloaded functions does not contain
13542                  function templates and at most one of a set of
13543                  overloaded functions provides a unique match.  */
13544               if (resolve_overloaded_unification
13545                   (tparms, targs, parm, arg, strict, sub_strict))
13546                 continue;
13547
13548               return 1;
13549             }
13550           arg_expr = arg;
13551           arg = unlowered_expr_type (arg);
13552           if (arg == error_mark_node)
13553             return 1;
13554         }
13555
13556       {
13557         int arg_strict = sub_strict;
13558
13559         if (!subr)
13560           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13561                                                           arg_expr);
13562
13563         if (arg == init_list_type_node && arg_expr)
13564           arg = arg_expr;
13565         if (unify (tparms, targs, parm, arg, arg_strict))
13566           return 1;
13567       }
13568     }
13569
13570
13571   if (parms 
13572       && parms != void_list_node
13573       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13574     {
13575       /* Unify the remaining arguments with the pack expansion type.  */
13576       tree argvec;
13577       tree parmvec = make_tree_vec (1);
13578
13579       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13580       argvec = make_tree_vec (nargs - ia);
13581       for (i = 0; ia < nargs; ++ia, ++i)
13582         TREE_VEC_ELT (argvec, i) = args[ia];
13583
13584       /* Copy the parameter into parmvec.  */
13585       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13586       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13587                                 /*call_args_p=*/true, /*subr=*/subr))
13588         return 1;
13589
13590       /* Advance to the end of the list of parameters.  */
13591       parms = TREE_CHAIN (parms);
13592     }
13593
13594   /* Fail if we've reached the end of the parm list, and more args
13595      are present, and the parm list isn't variadic.  */
13596   if (ia < nargs && parms == void_list_node)
13597     return 1;
13598   /* Fail if parms are left and they don't have default values.  */
13599   if (parms && parms != void_list_node
13600       && TREE_PURPOSE (parms) == NULL_TREE)
13601     return 1;
13602
13603   if (!subr)
13604     for (i = 0; i < ntparms; i++)
13605       if (!TREE_VEC_ELT (targs, i))
13606         {
13607           tree tparm;
13608
13609           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13610             continue;
13611
13612           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13613
13614           /* If this is an undeduced nontype parameter that depends on
13615              a type parameter, try another pass; its type may have been
13616              deduced from a later argument than the one from which
13617              this parameter can be deduced.  */
13618           if (TREE_CODE (tparm) == PARM_DECL
13619               && uses_template_parms (TREE_TYPE (tparm))
13620               && !saw_undeduced++)
13621             goto again;
13622
13623           /* Core issue #226 (C++0x) [temp.deduct]:
13624
13625                If a template argument has not been deduced, its
13626                default template argument, if any, is used. 
13627
13628              When we are in C++98 mode, TREE_PURPOSE will either
13629              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13630              to explicitly check cxx_dialect here.  */
13631           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13632             {
13633               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13634               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13635               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13636               arg = convert_template_argument (parm, arg, targs, tf_none,
13637                                                i, NULL_TREE);
13638               if (arg == error_mark_node)
13639                 return 1;
13640               else
13641                 {
13642                   TREE_VEC_ELT (targs, i) = arg;
13643                   /* The position of the first default template argument,
13644                      is also the number of non-defaulted arguments in TARGS.
13645                      Record that.  */
13646                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13647                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13648                   continue;
13649                 }
13650             }
13651
13652           /* If the type parameter is a parameter pack, then it will
13653              be deduced to an empty parameter pack.  */
13654           if (template_parameter_pack_p (tparm))
13655             {
13656               tree arg;
13657
13658               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13659                 {
13660                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13661                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13662                   TREE_CONSTANT (arg) = 1;
13663                 }
13664               else
13665                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13666
13667               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13668
13669               TREE_VEC_ELT (targs, i) = arg;
13670               continue;
13671             }
13672
13673           return 2;
13674         }
13675 #ifdef ENABLE_CHECKING
13676   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13677     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13678 #endif
13679
13680   return 0;
13681 }
13682
13683 /* Subroutine of type_unification_real.  Args are like the variables
13684    at the call site.  ARG is an overloaded function (or template-id);
13685    we try deducing template args from each of the overloads, and if
13686    only one succeeds, we go with that.  Modifies TARGS and returns
13687    true on success.  */
13688
13689 static bool
13690 resolve_overloaded_unification (tree tparms,
13691                                 tree targs,
13692                                 tree parm,
13693                                 tree arg,
13694                                 unification_kind_t strict,
13695                                 int sub_strict)
13696 {
13697   tree tempargs = copy_node (targs);
13698   int good = 0;
13699   tree goodfn = NULL_TREE;
13700   bool addr_p;
13701
13702   if (TREE_CODE (arg) == ADDR_EXPR)
13703     {
13704       arg = TREE_OPERAND (arg, 0);
13705       addr_p = true;
13706     }
13707   else
13708     addr_p = false;
13709
13710   if (TREE_CODE (arg) == COMPONENT_REF)
13711     /* Handle `&x' where `x' is some static or non-static member
13712        function name.  */
13713     arg = TREE_OPERAND (arg, 1);
13714
13715   if (TREE_CODE (arg) == OFFSET_REF)
13716     arg = TREE_OPERAND (arg, 1);
13717
13718   /* Strip baselink information.  */
13719   if (BASELINK_P (arg))
13720     arg = BASELINK_FUNCTIONS (arg);
13721
13722   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13723     {
13724       /* If we got some explicit template args, we need to plug them into
13725          the affected templates before we try to unify, in case the
13726          explicit args will completely resolve the templates in question.  */
13727
13728       tree expl_subargs = TREE_OPERAND (arg, 1);
13729       arg = TREE_OPERAND (arg, 0);
13730
13731       for (; arg; arg = OVL_NEXT (arg))
13732         {
13733           tree fn = OVL_CURRENT (arg);
13734           tree subargs, elem;
13735
13736           if (TREE_CODE (fn) != TEMPLATE_DECL)
13737             continue;
13738
13739           ++processing_template_decl;
13740           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13741                                   expl_subargs, /*check_ret=*/false);
13742           if (subargs)
13743             {
13744               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13745               if (try_one_overload (tparms, targs, tempargs, parm,
13746                                     elem, strict, sub_strict, addr_p)
13747                   && (!goodfn || !decls_match (goodfn, elem)))
13748                 {
13749                   goodfn = elem;
13750                   ++good;
13751                 }
13752             }
13753           --processing_template_decl;
13754         }
13755     }
13756   else if (TREE_CODE (arg) != OVERLOAD
13757            && TREE_CODE (arg) != FUNCTION_DECL)
13758     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13759        -- but the deduction does not succeed because the expression is
13760        not just the function on its own.  */
13761     return false;
13762   else
13763     for (; arg; arg = OVL_NEXT (arg))
13764       if (try_one_overload (tparms, targs, tempargs, parm,
13765                             TREE_TYPE (OVL_CURRENT (arg)),
13766                             strict, sub_strict, addr_p)
13767           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13768         {
13769           goodfn = OVL_CURRENT (arg);
13770           ++good;
13771         }
13772
13773   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13774      to function or pointer to member function argument if the set of
13775      overloaded functions does not contain function templates and at most
13776      one of a set of overloaded functions provides a unique match.
13777
13778      So if we found multiple possibilities, we return success but don't
13779      deduce anything.  */
13780
13781   if (good == 1)
13782     {
13783       int i = TREE_VEC_LENGTH (targs);
13784       for (; i--; )
13785         if (TREE_VEC_ELT (tempargs, i))
13786           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13787     }
13788   if (good)
13789     return true;
13790
13791   return false;
13792 }
13793
13794 /* Core DR 115: In contexts where deduction is done and fails, or in
13795    contexts where deduction is not done, if a template argument list is
13796    specified and it, along with any default template arguments, identifies
13797    a single function template specialization, then the template-id is an
13798    lvalue for the function template specialization.  */
13799
13800 tree
13801 resolve_nondeduced_context (tree orig_expr)
13802 {
13803   tree expr, offset, baselink;
13804   bool addr;
13805
13806   if (!type_unknown_p (orig_expr))
13807     return orig_expr;
13808
13809   expr = orig_expr;
13810   addr = false;
13811   offset = NULL_TREE;
13812   baselink = NULL_TREE;
13813
13814   if (TREE_CODE (expr) == ADDR_EXPR)
13815     {
13816       expr = TREE_OPERAND (expr, 0);
13817       addr = true;
13818     }
13819   if (TREE_CODE (expr) == OFFSET_REF)
13820     {
13821       offset = expr;
13822       expr = TREE_OPERAND (expr, 1);
13823     }
13824   if (TREE_CODE (expr) == BASELINK)
13825     {
13826       baselink = expr;
13827       expr = BASELINK_FUNCTIONS (expr);
13828     }
13829
13830   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13831     {
13832       int good = 0;
13833       tree goodfn = NULL_TREE;
13834
13835       /* If we got some explicit template args, we need to plug them into
13836          the affected templates before we try to unify, in case the
13837          explicit args will completely resolve the templates in question.  */
13838
13839       tree expl_subargs = TREE_OPERAND (expr, 1);
13840       tree arg = TREE_OPERAND (expr, 0);
13841       tree badfn = NULL_TREE;
13842       tree badargs = NULL_TREE;
13843
13844       for (; arg; arg = OVL_NEXT (arg))
13845         {
13846           tree fn = OVL_CURRENT (arg);
13847           tree subargs, elem;
13848
13849           if (TREE_CODE (fn) != TEMPLATE_DECL)
13850             continue;
13851
13852           ++processing_template_decl;
13853           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13854                                   expl_subargs, /*check_ret=*/false);
13855           if (subargs && !any_dependent_template_arguments_p (subargs))
13856             {
13857               elem = instantiate_template (fn, subargs, tf_none);
13858               if (elem == error_mark_node)
13859                 {
13860                   badfn = fn;
13861                   badargs = subargs;
13862                 }
13863               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13864                 {
13865                   goodfn = elem;
13866                   ++good;
13867                 }
13868             }
13869           --processing_template_decl;
13870         }
13871       if (good == 1)
13872         {
13873           expr = goodfn;
13874           if (baselink)
13875             expr = build_baselink (BASELINK_BINFO (baselink),
13876                                    BASELINK_ACCESS_BINFO (baselink),
13877                                    expr, BASELINK_OPTYPE (baselink));
13878           if (offset)
13879             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13880                            TREE_OPERAND (offset, 0), expr);
13881           if (addr)
13882             expr = build_address (expr);
13883           return expr;
13884         }
13885       else if (good == 0 && badargs)
13886         /* There were no good options and at least one bad one, so let the
13887            user know what the problem is.  */
13888         instantiate_template (badfn, badargs, tf_warning_or_error);
13889     }
13890   return orig_expr;
13891 }
13892
13893 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13894    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13895    different overloads deduce different arguments for a given parm.
13896    ADDR_P is true if the expression for which deduction is being
13897    performed was of the form "& fn" rather than simply "fn".
13898
13899    Returns 1 on success.  */
13900
13901 static int
13902 try_one_overload (tree tparms,
13903                   tree orig_targs,
13904                   tree targs,
13905                   tree parm,
13906                   tree arg,
13907                   unification_kind_t strict,
13908                   int sub_strict,
13909                   bool addr_p)
13910 {
13911   int nargs;
13912   tree tempargs;
13913   int i;
13914
13915   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13916      to function or pointer to member function argument if the set of
13917      overloaded functions does not contain function templates and at most
13918      one of a set of overloaded functions provides a unique match.
13919
13920      So if this is a template, just return success.  */
13921
13922   if (uses_template_parms (arg))
13923     return 1;
13924
13925   if (TREE_CODE (arg) == METHOD_TYPE)
13926     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13927   else if (addr_p)
13928     arg = build_pointer_type (arg);
13929
13930   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13931
13932   /* We don't copy orig_targs for this because if we have already deduced
13933      some template args from previous args, unify would complain when we
13934      try to deduce a template parameter for the same argument, even though
13935      there isn't really a conflict.  */
13936   nargs = TREE_VEC_LENGTH (targs);
13937   tempargs = make_tree_vec (nargs);
13938
13939   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13940     return 0;
13941
13942   /* First make sure we didn't deduce anything that conflicts with
13943      explicitly specified args.  */
13944   for (i = nargs; i--; )
13945     {
13946       tree elt = TREE_VEC_ELT (tempargs, i);
13947       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13948
13949       if (!elt)
13950         /*NOP*/;
13951       else if (uses_template_parms (elt))
13952         /* Since we're unifying against ourselves, we will fill in
13953            template args used in the function parm list with our own
13954            template parms.  Discard them.  */
13955         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13956       else if (oldelt && !template_args_equal (oldelt, elt))
13957         return 0;
13958     }
13959
13960   for (i = nargs; i--; )
13961     {
13962       tree elt = TREE_VEC_ELT (tempargs, i);
13963
13964       if (elt)
13965         TREE_VEC_ELT (targs, i) = elt;
13966     }
13967
13968   return 1;
13969 }
13970
13971 /* PARM is a template class (perhaps with unbound template
13972    parameters).  ARG is a fully instantiated type.  If ARG can be
13973    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13974    TARGS are as for unify.  */
13975
13976 static tree
13977 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13978 {
13979   tree copy_of_targs;
13980
13981   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13982       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13983           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13984     return NULL_TREE;
13985
13986   /* We need to make a new template argument vector for the call to
13987      unify.  If we used TARGS, we'd clutter it up with the result of
13988      the attempted unification, even if this class didn't work out.
13989      We also don't want to commit ourselves to all the unifications
13990      we've already done, since unification is supposed to be done on
13991      an argument-by-argument basis.  In other words, consider the
13992      following pathological case:
13993
13994        template <int I, int J, int K>
13995        struct S {};
13996
13997        template <int I, int J>
13998        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13999
14000        template <int I, int J, int K>
14001        void f(S<I, J, K>, S<I, I, I>);
14002
14003        void g() {
14004          S<0, 0, 0> s0;
14005          S<0, 1, 2> s2;
14006
14007          f(s0, s2);
14008        }
14009
14010      Now, by the time we consider the unification involving `s2', we
14011      already know that we must have `f<0, 0, 0>'.  But, even though
14012      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14013      because there are two ways to unify base classes of S<0, 1, 2>
14014      with S<I, I, I>.  If we kept the already deduced knowledge, we
14015      would reject the possibility I=1.  */
14016   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14017
14018   /* If unification failed, we're done.  */
14019   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14020              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14021     return NULL_TREE;
14022
14023   return arg;
14024 }
14025
14026 /* Given a template type PARM and a class type ARG, find the unique
14027    base type in ARG that is an instance of PARM.  We do not examine
14028    ARG itself; only its base-classes.  If there is not exactly one
14029    appropriate base class, return NULL_TREE.  PARM may be the type of
14030    a partial specialization, as well as a plain template type.  Used
14031    by unify.  */
14032
14033 static tree
14034 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14035 {
14036   tree rval = NULL_TREE;
14037   tree binfo;
14038
14039   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14040
14041   binfo = TYPE_BINFO (complete_type (arg));
14042   if (!binfo)
14043     /* The type could not be completed.  */
14044     return NULL_TREE;
14045
14046   /* Walk in inheritance graph order.  The search order is not
14047      important, and this avoids multiple walks of virtual bases.  */
14048   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14049     {
14050       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14051
14052       if (r)
14053         {
14054           /* If there is more than one satisfactory baseclass, then:
14055
14056                [temp.deduct.call]
14057
14058               If they yield more than one possible deduced A, the type
14059               deduction fails.
14060
14061              applies.  */
14062           if (rval && !same_type_p (r, rval))
14063             return NULL_TREE;
14064
14065           rval = r;
14066         }
14067     }
14068
14069   return rval;
14070 }
14071
14072 /* Returns the level of DECL, which declares a template parameter.  */
14073
14074 static int
14075 template_decl_level (tree decl)
14076 {
14077   switch (TREE_CODE (decl))
14078     {
14079     case TYPE_DECL:
14080     case TEMPLATE_DECL:
14081       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14082
14083     case PARM_DECL:
14084       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14085
14086     default:
14087       gcc_unreachable ();
14088     }
14089   return 0;
14090 }
14091
14092 /* Decide whether ARG can be unified with PARM, considering only the
14093    cv-qualifiers of each type, given STRICT as documented for unify.
14094    Returns nonzero iff the unification is OK on that basis.  */
14095
14096 static int
14097 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14098 {
14099   int arg_quals = cp_type_quals (arg);
14100   int parm_quals = cp_type_quals (parm);
14101
14102   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14103       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14104     {
14105       /*  Although a CVR qualifier is ignored when being applied to a
14106           substituted template parameter ([8.3.2]/1 for example), that
14107           does not apply during deduction [14.8.2.4]/1, (even though
14108           that is not explicitly mentioned, [14.8.2.4]/9 indicates
14109           this).  Except when we're allowing additional CV qualifiers
14110           at the outer level [14.8.2.1]/3,1st bullet.  */
14111       if ((TREE_CODE (arg) == REFERENCE_TYPE
14112            || TREE_CODE (arg) == FUNCTION_TYPE
14113            || TREE_CODE (arg) == METHOD_TYPE)
14114           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14115         return 0;
14116
14117       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14118           && (parm_quals & TYPE_QUAL_RESTRICT))
14119         return 0;
14120     }
14121
14122   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14123       && (arg_quals & parm_quals) != parm_quals)
14124     return 0;
14125
14126   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14127       && (parm_quals & arg_quals) != arg_quals)
14128     return 0;
14129
14130   return 1;
14131 }
14132
14133 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14134 void 
14135 template_parm_level_and_index (tree parm, int* level, int* index)
14136 {
14137   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14138       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14139       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14140     {
14141       *index = TEMPLATE_TYPE_IDX (parm);
14142       *level = TEMPLATE_TYPE_LEVEL (parm);
14143     }
14144   else
14145     {
14146       *index = TEMPLATE_PARM_IDX (parm);
14147       *level = TEMPLATE_PARM_LEVEL (parm);
14148     }
14149 }
14150
14151 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14152    expansion at the end of PACKED_PARMS. Returns 0 if the type
14153    deduction succeeds, 1 otherwise. STRICT is the same as in
14154    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14155    call argument list. We'll need to adjust the arguments to make them
14156    types. SUBR tells us if this is from a recursive call to
14157    type_unification_real.  */
14158 int
14159 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14160                       tree packed_args, int strict, bool call_args_p,
14161                       bool subr)
14162 {
14163   tree parm 
14164     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14165   tree pattern = PACK_EXPANSION_PATTERN (parm);
14166   tree pack, packs = NULL_TREE;
14167   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14168   int len = TREE_VEC_LENGTH (packed_args);
14169
14170   /* Determine the parameter packs we will be deducing from the
14171      pattern, and record their current deductions.  */
14172   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14173        pack; pack = TREE_CHAIN (pack))
14174     {
14175       tree parm_pack = TREE_VALUE (pack);
14176       int idx, level;
14177
14178       /* Determine the index and level of this parameter pack.  */
14179       template_parm_level_and_index (parm_pack, &level, &idx);
14180
14181       /* Keep track of the parameter packs and their corresponding
14182          argument packs.  */
14183       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14184       TREE_TYPE (packs) = make_tree_vec (len - start);
14185     }
14186   
14187   /* Loop through all of the arguments that have not yet been
14188      unified and unify each with the pattern.  */
14189   for (i = start; i < len; i++)
14190     {
14191       tree parm = pattern;
14192
14193       /* For each parameter pack, clear out the deduced value so that
14194          we can deduce it again.  */
14195       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14196         {
14197           int idx, level;
14198           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14199
14200           TMPL_ARG (targs, level, idx) = NULL_TREE;
14201         }
14202
14203       /* Unify the pattern with the current argument.  */
14204       {
14205         tree arg = TREE_VEC_ELT (packed_args, i);
14206         tree arg_expr = NULL_TREE;
14207         int arg_strict = strict;
14208         bool skip_arg_p = false;
14209
14210         if (call_args_p)
14211           {
14212             int sub_strict;
14213
14214             /* This mirrors what we do in type_unification_real.  */
14215             switch (strict)
14216               {
14217               case DEDUCE_CALL:
14218                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14219                               | UNIFY_ALLOW_MORE_CV_QUAL
14220                               | UNIFY_ALLOW_DERIVED);
14221                 break;
14222                 
14223               case DEDUCE_CONV:
14224                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14225                 break;
14226                 
14227               case DEDUCE_EXACT:
14228                 sub_strict = UNIFY_ALLOW_NONE;
14229                 break;
14230                 
14231               default:
14232                 gcc_unreachable ();
14233               }
14234
14235             if (!TYPE_P (arg))
14236               {
14237                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14238                 if (type_unknown_p (arg))
14239                   {
14240                     /* [temp.deduct.type] A template-argument can be
14241                        deduced from a pointer to function or pointer
14242                        to member function argument if the set of
14243                        overloaded functions does not contain function
14244                        templates and at most one of a set of
14245                        overloaded functions provides a unique
14246                        match.  */
14247
14248                     if (resolve_overloaded_unification
14249                         (tparms, targs, parm, arg,
14250                          (unification_kind_t) strict,
14251                          sub_strict)
14252                         != 0)
14253                       return 1;
14254                     skip_arg_p = true;
14255                   }
14256
14257                 if (!skip_arg_p)
14258                   {
14259                     arg_expr = arg;
14260                     arg = unlowered_expr_type (arg);
14261                     if (arg == error_mark_node)
14262                       return 1;
14263                   }
14264               }
14265       
14266             arg_strict = sub_strict;
14267
14268             if (!subr)
14269               arg_strict |= 
14270                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14271                                                   &parm, &arg, arg_expr);
14272           }
14273
14274         if (!skip_arg_p)
14275           {
14276             /* For deduction from an init-list we need the actual list.  */
14277             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14278               arg = arg_expr;
14279             if (unify (tparms, targs, parm, arg, arg_strict))
14280               return 1;
14281           }
14282       }
14283
14284       /* For each parameter pack, collect the deduced value.  */
14285       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14286         {
14287           int idx, level;
14288           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14289
14290           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14291             TMPL_ARG (targs, level, idx);
14292         }
14293     }
14294
14295   /* Verify that the results of unification with the parameter packs
14296      produce results consistent with what we've seen before, and make
14297      the deduced argument packs available.  */
14298   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14299     {
14300       tree old_pack = TREE_VALUE (pack);
14301       tree new_args = TREE_TYPE (pack);
14302       int i, len = TREE_VEC_LENGTH (new_args);
14303       int idx, level;
14304       bool nondeduced_p = false;
14305
14306       /* By default keep the original deduced argument pack.
14307          If necessary, more specific code is going to update the
14308          resulting deduced argument later down in this function.  */
14309       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14310       TMPL_ARG (targs, level, idx) = old_pack;
14311
14312       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14313          actually deduce anything.  */
14314       for (i = 0; i < len && !nondeduced_p; ++i)
14315         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14316           nondeduced_p = true;
14317       if (nondeduced_p)
14318         continue;
14319
14320       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14321         {
14322           /* Prepend the explicit arguments onto NEW_ARGS.  */
14323           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14324           tree old_args = new_args;
14325           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14326           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14327
14328           /* Copy the explicit arguments.  */
14329           new_args = make_tree_vec (len);
14330           for (i = 0; i < explicit_len; i++)
14331             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14332
14333           /* Copy the deduced arguments.  */
14334           for (; i < len; i++)
14335             TREE_VEC_ELT (new_args, i) =
14336               TREE_VEC_ELT (old_args, i - explicit_len);
14337         }
14338
14339       if (!old_pack)
14340         {
14341           tree result;
14342           /* Build the deduced *_ARGUMENT_PACK.  */
14343           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14344             {
14345               result = make_node (NONTYPE_ARGUMENT_PACK);
14346               TREE_TYPE (result) = 
14347                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14348               TREE_CONSTANT (result) = 1;
14349             }
14350           else
14351             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14352
14353           SET_ARGUMENT_PACK_ARGS (result, new_args);
14354
14355           /* Note the deduced argument packs for this parameter
14356              pack.  */
14357           TMPL_ARG (targs, level, idx) = result;
14358         }
14359       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14360                && (ARGUMENT_PACK_ARGS (old_pack) 
14361                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14362         {
14363           /* We only had the explicitly-provided arguments before, but
14364              now we have a complete set of arguments.  */
14365           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14366
14367           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14368           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14369           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14370         }
14371       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14372                                     new_args))
14373         /* Inconsistent unification of this parameter pack.  */
14374         return 1;
14375     }
14376
14377   return 0;
14378 }
14379
14380 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14381    set of template parameters to a template.  TARGS is the bindings
14382    for those template parameters, as determined thus far; TARGS may
14383    include template arguments for outer levels of template parameters
14384    as well.  PARM is a parameter to a template function, or a
14385    subcomponent of that parameter; ARG is the corresponding argument.
14386    This function attempts to match PARM with ARG in a manner
14387    consistent with the existing assignments in TARGS.  If more values
14388    are deduced, then TARGS is updated.
14389
14390    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14391    parameter STRICT is a bitwise or of the following flags:
14392
14393      UNIFY_ALLOW_NONE:
14394        Require an exact match between PARM and ARG.
14395      UNIFY_ALLOW_MORE_CV_QUAL:
14396        Allow the deduced ARG to be more cv-qualified (by qualification
14397        conversion) than ARG.
14398      UNIFY_ALLOW_LESS_CV_QUAL:
14399        Allow the deduced ARG to be less cv-qualified than ARG.
14400      UNIFY_ALLOW_DERIVED:
14401        Allow the deduced ARG to be a template base class of ARG,
14402        or a pointer to a template base class of the type pointed to by
14403        ARG.
14404      UNIFY_ALLOW_INTEGER:
14405        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14406        case for more information.
14407      UNIFY_ALLOW_OUTER_LEVEL:
14408        This is the outermost level of a deduction. Used to determine validity
14409        of qualification conversions. A valid qualification conversion must
14410        have const qualified pointers leading up to the inner type which
14411        requires additional CV quals, except at the outer level, where const
14412        is not required [conv.qual]. It would be normal to set this flag in
14413        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14414      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14415        This is the outermost level of a deduction, and PARM can be more CV
14416        qualified at this point.
14417      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14418        This is the outermost level of a deduction, and PARM can be less CV
14419        qualified at this point.  */
14420
14421 static int
14422 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14423 {
14424   int idx;
14425   tree targ;
14426   tree tparm;
14427   int strict_in = strict;
14428
14429   /* I don't think this will do the right thing with respect to types.
14430      But the only case I've seen it in so far has been array bounds, where
14431      signedness is the only information lost, and I think that will be
14432      okay.  */
14433   while (TREE_CODE (parm) == NOP_EXPR)
14434     parm = TREE_OPERAND (parm, 0);
14435
14436   if (arg == error_mark_node)
14437     return 1;
14438   if (arg == unknown_type_node
14439       || arg == init_list_type_node)
14440     /* We can't deduce anything from this, but we might get all the
14441        template args from other function args.  */
14442     return 0;
14443
14444   /* If PARM uses template parameters, then we can't bail out here,
14445      even if ARG == PARM, since we won't record unifications for the
14446      template parameters.  We might need them if we're trying to
14447      figure out which of two things is more specialized.  */
14448   if (arg == parm && !uses_template_parms (parm))
14449     return 0;
14450
14451   /* Handle init lists early, so the rest of the function can assume
14452      we're dealing with a type. */
14453   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14454     {
14455       tree elt, elttype;
14456       unsigned i;
14457       tree orig_parm = parm;
14458
14459       /* Replace T with std::initializer_list<T> for deduction.  */
14460       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14461           && flag_deduce_init_list)
14462         parm = listify (parm);
14463
14464       if (!is_std_init_list (parm))
14465         /* We can only deduce from an initializer list argument if the
14466            parameter is std::initializer_list; otherwise this is a
14467            non-deduced context. */
14468         return 0;
14469
14470       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14471
14472       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14473         {
14474           int elt_strict = strict;
14475
14476           if (elt == error_mark_node)
14477             return 1;
14478
14479           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14480             {
14481               tree type = TREE_TYPE (elt);
14482               /* It should only be possible to get here for a call.  */
14483               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14484               elt_strict |= maybe_adjust_types_for_deduction
14485                 (DEDUCE_CALL, &elttype, &type, elt);
14486               elt = type;
14487             }
14488
14489           if (unify (tparms, targs, elttype, elt, elt_strict))
14490             return 1;
14491         }
14492
14493       /* If the std::initializer_list<T> deduction worked, replace the
14494          deduced A with std::initializer_list<A>.  */
14495       if (orig_parm != parm)
14496         {
14497           idx = TEMPLATE_TYPE_IDX (orig_parm);
14498           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14499           targ = listify (targ);
14500           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14501         }
14502       return 0;
14503     }
14504
14505   /* Immediately reject some pairs that won't unify because of
14506      cv-qualification mismatches.  */
14507   if (TREE_CODE (arg) == TREE_CODE (parm)
14508       && TYPE_P (arg)
14509       /* It is the elements of the array which hold the cv quals of an array
14510          type, and the elements might be template type parms. We'll check
14511          when we recurse.  */
14512       && TREE_CODE (arg) != ARRAY_TYPE
14513       /* We check the cv-qualifiers when unifying with template type
14514          parameters below.  We want to allow ARG `const T' to unify with
14515          PARM `T' for example, when computing which of two templates
14516          is more specialized, for example.  */
14517       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14518       && !check_cv_quals_for_unify (strict_in, arg, parm))
14519     return 1;
14520
14521   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14522       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14523     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14524   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14525   strict &= ~UNIFY_ALLOW_DERIVED;
14526   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14527   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14528
14529   switch (TREE_CODE (parm))
14530     {
14531     case TYPENAME_TYPE:
14532     case SCOPE_REF:
14533     case UNBOUND_CLASS_TEMPLATE:
14534       /* In a type which contains a nested-name-specifier, template
14535          argument values cannot be deduced for template parameters used
14536          within the nested-name-specifier.  */
14537       return 0;
14538
14539     case TEMPLATE_TYPE_PARM:
14540     case TEMPLATE_TEMPLATE_PARM:
14541     case BOUND_TEMPLATE_TEMPLATE_PARM:
14542       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14543       if (tparm == error_mark_node)
14544         return 1;
14545
14546       if (TEMPLATE_TYPE_LEVEL (parm)
14547           != template_decl_level (tparm))
14548         /* The PARM is not one we're trying to unify.  Just check
14549            to see if it matches ARG.  */
14550         return (TREE_CODE (arg) == TREE_CODE (parm)
14551                 && same_type_p (parm, arg)) ? 0 : 1;
14552       idx = TEMPLATE_TYPE_IDX (parm);
14553       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14554       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14555
14556       /* Check for mixed types and values.  */
14557       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14558            && TREE_CODE (tparm) != TYPE_DECL)
14559           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14560               && TREE_CODE (tparm) != TEMPLATE_DECL))
14561         return 1;
14562
14563       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14564         {
14565           /* ARG must be constructed from a template class or a template
14566              template parameter.  */
14567           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14568               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14569             return 1;
14570
14571           {
14572             tree parmvec = TYPE_TI_ARGS (parm);
14573             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14574             tree parm_parms 
14575               = DECL_INNERMOST_TEMPLATE_PARMS
14576                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14577             int i, len;
14578             int parm_variadic_p = 0;
14579
14580             /* The resolution to DR150 makes clear that default
14581                arguments for an N-argument may not be used to bind T
14582                to a template template parameter with fewer than N
14583                parameters.  It is not safe to permit the binding of
14584                default arguments as an extension, as that may change
14585                the meaning of a conforming program.  Consider:
14586
14587                   struct Dense { static const unsigned int dim = 1; };
14588
14589                   template <template <typename> class View,
14590                             typename Block>
14591                   void operator+(float, View<Block> const&);
14592
14593                   template <typename Block,
14594                             unsigned int Dim = Block::dim>
14595                   struct Lvalue_proxy { operator float() const; };
14596
14597                   void
14598                   test_1d (void) {
14599                     Lvalue_proxy<Dense> p;
14600                     float b;
14601                     b + p;
14602                   }
14603
14604               Here, if Lvalue_proxy is permitted to bind to View, then
14605               the global operator+ will be used; if they are not, the
14606               Lvalue_proxy will be converted to float.  */
14607             if (coerce_template_parms (parm_parms,
14608                                        argvec,
14609                                        TYPE_TI_TEMPLATE (parm),
14610                                        tf_none,
14611                                        /*require_all_args=*/true,
14612                                        /*use_default_args=*/false)
14613                 == error_mark_node)
14614               return 1;
14615
14616             /* Deduce arguments T, i from TT<T> or TT<i>.
14617                We check each element of PARMVEC and ARGVEC individually
14618                rather than the whole TREE_VEC since they can have
14619                different number of elements.  */
14620
14621             parmvec = expand_template_argument_pack (parmvec);
14622             argvec = expand_template_argument_pack (argvec);
14623
14624             len = TREE_VEC_LENGTH (parmvec);
14625
14626             /* Check if the parameters end in a pack, making them
14627                variadic.  */
14628             if (len > 0
14629                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14630               parm_variadic_p = 1;
14631             
14632             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14633               return 1;
14634
14635              for (i = 0; i < len - parm_variadic_p; ++i)
14636               {
14637                 if (unify (tparms, targs,
14638                            TREE_VEC_ELT (parmvec, i),
14639                            TREE_VEC_ELT (argvec, i),
14640                            UNIFY_ALLOW_NONE))
14641                   return 1;
14642               }
14643
14644             if (parm_variadic_p
14645                 && unify_pack_expansion (tparms, targs,
14646                                          parmvec, argvec,
14647                                          UNIFY_ALLOW_NONE,
14648                                          /*call_args_p=*/false,
14649                                          /*subr=*/false))
14650               return 1;
14651           }
14652           arg = TYPE_TI_TEMPLATE (arg);
14653
14654           /* Fall through to deduce template name.  */
14655         }
14656
14657       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14658           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14659         {
14660           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14661
14662           /* Simple cases: Value already set, does match or doesn't.  */
14663           if (targ != NULL_TREE && template_args_equal (targ, arg))
14664             return 0;
14665           else if (targ)
14666             return 1;
14667         }
14668       else
14669         {
14670           /* If PARM is `const T' and ARG is only `int', we don't have
14671              a match unless we are allowing additional qualification.
14672              If ARG is `const int' and PARM is just `T' that's OK;
14673              that binds `const int' to `T'.  */
14674           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14675                                          arg, parm))
14676             return 1;
14677
14678           /* Consider the case where ARG is `const volatile int' and
14679              PARM is `const T'.  Then, T should be `volatile int'.  */
14680           arg = cp_build_qualified_type_real
14681             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14682           if (arg == error_mark_node)
14683             return 1;
14684
14685           /* Simple cases: Value already set, does match or doesn't.  */
14686           if (targ != NULL_TREE && same_type_p (targ, arg))
14687             return 0;
14688           else if (targ)
14689             return 1;
14690
14691           /* Make sure that ARG is not a variable-sized array.  (Note
14692              that were talking about variable-sized arrays (like
14693              `int[n]'), rather than arrays of unknown size (like
14694              `int[]').)  We'll get very confused by such a type since
14695              the bound of the array will not be computable in an
14696              instantiation.  Besides, such types are not allowed in
14697              ISO C++, so we can do as we please here.  */
14698           if (variably_modified_type_p (arg, NULL_TREE))
14699             return 1;
14700
14701           /* Strip typedefs as in convert_template_argument.  */
14702           arg = strip_typedefs (arg);
14703         }
14704
14705       /* If ARG is a parameter pack or an expansion, we cannot unify
14706          against it unless PARM is also a parameter pack.  */
14707       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14708           && !template_parameter_pack_p (parm))
14709         return 1;
14710
14711       /* If the argument deduction results is a METHOD_TYPE,
14712          then there is a problem.
14713          METHOD_TYPE doesn't map to any real C++ type the result of
14714          the deduction can not be of that type.  */
14715       if (TREE_CODE (arg) == METHOD_TYPE)
14716         return 1;
14717
14718       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14719       return 0;
14720
14721     case TEMPLATE_PARM_INDEX:
14722       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14723       if (tparm == error_mark_node)
14724         return 1;
14725
14726       if (TEMPLATE_PARM_LEVEL (parm)
14727           != template_decl_level (tparm))
14728         /* The PARM is not one we're trying to unify.  Just check
14729            to see if it matches ARG.  */
14730         return !(TREE_CODE (arg) == TREE_CODE (parm)
14731                  && cp_tree_equal (parm, arg));
14732
14733       idx = TEMPLATE_PARM_IDX (parm);
14734       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14735
14736       if (targ)
14737         return !cp_tree_equal (targ, arg);
14738
14739       /* [temp.deduct.type] If, in the declaration of a function template
14740          with a non-type template-parameter, the non-type
14741          template-parameter is used in an expression in the function
14742          parameter-list and, if the corresponding template-argument is
14743          deduced, the template-argument type shall match the type of the
14744          template-parameter exactly, except that a template-argument
14745          deduced from an array bound may be of any integral type.
14746          The non-type parameter might use already deduced type parameters.  */
14747       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14748       if (!TREE_TYPE (arg))
14749         /* Template-parameter dependent expression.  Just accept it for now.
14750            It will later be processed in convert_template_argument.  */
14751         ;
14752       else if (same_type_p (TREE_TYPE (arg), tparm))
14753         /* OK */;
14754       else if ((strict & UNIFY_ALLOW_INTEGER)
14755                && (TREE_CODE (tparm) == INTEGER_TYPE
14756                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14757         /* Convert the ARG to the type of PARM; the deduced non-type
14758            template argument must exactly match the types of the
14759            corresponding parameter.  */
14760         arg = fold (build_nop (tparm, arg));
14761       else if (uses_template_parms (tparm))
14762         /* We haven't deduced the type of this parameter yet.  Try again
14763            later.  */
14764         return 0;
14765       else
14766         return 1;
14767
14768       /* If ARG is a parameter pack or an expansion, we cannot unify
14769          against it unless PARM is also a parameter pack.  */
14770       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14771           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14772         return 1;
14773
14774       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14775       return 0;
14776
14777     case PTRMEM_CST:
14778      {
14779         /* A pointer-to-member constant can be unified only with
14780          another constant.  */
14781       if (TREE_CODE (arg) != PTRMEM_CST)
14782         return 1;
14783
14784       /* Just unify the class member. It would be useless (and possibly
14785          wrong, depending on the strict flags) to unify also
14786          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14787          arg refer to the same variable, even if through different
14788          classes. For instance:
14789
14790          struct A { int x; };
14791          struct B : A { };
14792
14793          Unification of &A::x and &B::x must succeed.  */
14794       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14795                     PTRMEM_CST_MEMBER (arg), strict);
14796      }
14797
14798     case POINTER_TYPE:
14799       {
14800         if (TREE_CODE (arg) != POINTER_TYPE)
14801           return 1;
14802
14803         /* [temp.deduct.call]
14804
14805            A can be another pointer or pointer to member type that can
14806            be converted to the deduced A via a qualification
14807            conversion (_conv.qual_).
14808
14809            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14810            This will allow for additional cv-qualification of the
14811            pointed-to types if appropriate.  */
14812
14813         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14814           /* The derived-to-base conversion only persists through one
14815              level of pointers.  */
14816           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14817
14818         return unify (tparms, targs, TREE_TYPE (parm),
14819                       TREE_TYPE (arg), strict);
14820       }
14821
14822     case REFERENCE_TYPE:
14823       if (TREE_CODE (arg) != REFERENCE_TYPE)
14824         return 1;
14825       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14826                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14827
14828     case ARRAY_TYPE:
14829       if (TREE_CODE (arg) != ARRAY_TYPE)
14830         return 1;
14831       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14832           != (TYPE_DOMAIN (arg) == NULL_TREE))
14833         return 1;
14834       if (TYPE_DOMAIN (parm) != NULL_TREE)
14835         {
14836           tree parm_max;
14837           tree arg_max;
14838           bool parm_cst;
14839           bool arg_cst;
14840
14841           /* Our representation of array types uses "N - 1" as the
14842              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14843              not an integer constant.  We cannot unify arbitrarily
14844              complex expressions, so we eliminate the MINUS_EXPRs
14845              here.  */
14846           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14847           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14848           if (!parm_cst)
14849             {
14850               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14851               parm_max = TREE_OPERAND (parm_max, 0);
14852             }
14853           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14854           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14855           if (!arg_cst)
14856             {
14857               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14858                  trying to unify the type of a variable with the type
14859                  of a template parameter.  For example:
14860
14861                    template <unsigned int N>
14862                    void f (char (&) [N]);
14863                    int g(); 
14864                    void h(int i) {
14865                      char a[g(i)];
14866                      f(a); 
14867                    }
14868
14869                 Here, the type of the ARG will be "int [g(i)]", and
14870                 may be a SAVE_EXPR, etc.  */
14871               if (TREE_CODE (arg_max) != MINUS_EXPR)
14872                 return 1;
14873               arg_max = TREE_OPERAND (arg_max, 0);
14874             }
14875
14876           /* If only one of the bounds used a MINUS_EXPR, compensate
14877              by adding one to the other bound.  */
14878           if (parm_cst && !arg_cst)
14879             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14880                                     integer_type_node,
14881                                     parm_max,
14882                                     integer_one_node);
14883           else if (arg_cst && !parm_cst)
14884             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14885                                    integer_type_node,
14886                                    arg_max,
14887                                    integer_one_node);
14888
14889           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14890             return 1;
14891         }
14892       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14893                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14894
14895     case REAL_TYPE:
14896     case COMPLEX_TYPE:
14897     case VECTOR_TYPE:
14898     case INTEGER_TYPE:
14899     case BOOLEAN_TYPE:
14900     case ENUMERAL_TYPE:
14901     case VOID_TYPE:
14902       if (TREE_CODE (arg) != TREE_CODE (parm))
14903         return 1;
14904
14905       /* We have already checked cv-qualification at the top of the
14906          function.  */
14907       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14908         return 1;
14909
14910       /* As far as unification is concerned, this wins.  Later checks
14911          will invalidate it if necessary.  */
14912       return 0;
14913
14914       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14915       /* Type INTEGER_CST can come from ordinary constant template args.  */
14916     case INTEGER_CST:
14917       while (TREE_CODE (arg) == NOP_EXPR)
14918         arg = TREE_OPERAND (arg, 0);
14919
14920       if (TREE_CODE (arg) != INTEGER_CST)
14921         return 1;
14922       return !tree_int_cst_equal (parm, arg);
14923
14924     case TREE_VEC:
14925       {
14926         int i;
14927         if (TREE_CODE (arg) != TREE_VEC)
14928           return 1;
14929         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14930           return 1;
14931         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14932           if (unify (tparms, targs,
14933                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14934                      UNIFY_ALLOW_NONE))
14935             return 1;
14936         return 0;
14937       }
14938
14939     case RECORD_TYPE:
14940     case UNION_TYPE:
14941       if (TREE_CODE (arg) != TREE_CODE (parm))
14942         return 1;
14943
14944       if (TYPE_PTRMEMFUNC_P (parm))
14945         {
14946           if (!TYPE_PTRMEMFUNC_P (arg))
14947             return 1;
14948
14949           return unify (tparms, targs,
14950                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14951                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14952                         strict);
14953         }
14954
14955       if (CLASSTYPE_TEMPLATE_INFO (parm))
14956         {
14957           tree t = NULL_TREE;
14958
14959           if (strict_in & UNIFY_ALLOW_DERIVED)
14960             {
14961               /* First, we try to unify the PARM and ARG directly.  */
14962               t = try_class_unification (tparms, targs,
14963                                          parm, arg);
14964
14965               if (!t)
14966                 {
14967                   /* Fallback to the special case allowed in
14968                      [temp.deduct.call]:
14969
14970                        If P is a class, and P has the form
14971                        template-id, then A can be a derived class of
14972                        the deduced A.  Likewise, if P is a pointer to
14973                        a class of the form template-id, A can be a
14974                        pointer to a derived class pointed to by the
14975                        deduced A.  */
14976                   t = get_template_base (tparms, targs, parm, arg);
14977
14978                   if (!t)
14979                     return 1;
14980                 }
14981             }
14982           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14983                    && (CLASSTYPE_TI_TEMPLATE (parm)
14984                        == CLASSTYPE_TI_TEMPLATE (arg)))
14985             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14986                Then, we should unify `int' and `U'.  */
14987             t = arg;
14988           else
14989             /* There's no chance of unification succeeding.  */
14990             return 1;
14991
14992           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14993                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14994         }
14995       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14996         return 1;
14997       return 0;
14998
14999     case METHOD_TYPE:
15000     case FUNCTION_TYPE:
15001       {
15002         unsigned int nargs;
15003         tree *args;
15004         tree a;
15005         unsigned int i;
15006
15007         if (TREE_CODE (arg) != TREE_CODE (parm))
15008           return 1;
15009
15010         /* CV qualifications for methods can never be deduced, they must
15011            match exactly.  We need to check them explicitly here,
15012            because type_unification_real treats them as any other
15013            cv-qualified parameter.  */
15014         if (TREE_CODE (parm) == METHOD_TYPE
15015             && (!check_cv_quals_for_unify
15016                 (UNIFY_ALLOW_NONE,
15017                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15018                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15019           return 1;
15020
15021         if (unify (tparms, targs, TREE_TYPE (parm),
15022                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15023           return 1;
15024
15025         nargs = list_length (TYPE_ARG_TYPES (arg));
15026         args = XALLOCAVEC (tree, nargs);
15027         for (a = TYPE_ARG_TYPES (arg), i = 0;
15028              a != NULL_TREE && a != void_list_node;
15029              a = TREE_CHAIN (a), ++i)
15030           args[i] = TREE_VALUE (a);
15031         nargs = i;
15032
15033         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15034                                       args, nargs, 1, DEDUCE_EXACT,
15035                                       LOOKUP_NORMAL);
15036       }
15037
15038     case OFFSET_TYPE:
15039       /* Unify a pointer to member with a pointer to member function, which
15040          deduces the type of the member as a function type. */
15041       if (TYPE_PTRMEMFUNC_P (arg))
15042         {
15043           tree method_type;
15044           tree fntype;
15045           cp_cv_quals cv_quals;
15046
15047           /* Check top-level cv qualifiers */
15048           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15049             return 1;
15050
15051           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15052                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15053             return 1;
15054
15055           /* Determine the type of the function we are unifying against. */
15056           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15057           fntype =
15058             build_function_type (TREE_TYPE (method_type),
15059                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15060
15061           /* Extract the cv-qualifiers of the member function from the
15062              implicit object parameter and place them on the function
15063              type to be restored later. */
15064           cv_quals =
15065             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15066           fntype = build_qualified_type (fntype, cv_quals);
15067           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15068         }
15069
15070       if (TREE_CODE (arg) != OFFSET_TYPE)
15071         return 1;
15072       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15073                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15074         return 1;
15075       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15076                     strict);
15077
15078     case CONST_DECL:
15079       if (DECL_TEMPLATE_PARM_P (parm))
15080         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15081       if (arg != integral_constant_value (parm))
15082         return 1;
15083       return 0;
15084
15085     case FIELD_DECL:
15086     case TEMPLATE_DECL:
15087       /* Matched cases are handled by the ARG == PARM test above.  */
15088       return 1;
15089
15090     case VAR_DECL:
15091       /* A non-type template parameter that is a variable should be a
15092          an integral constant, in which case, it whould have been
15093          folded into its (constant) value. So we should not be getting
15094          a variable here.  */
15095       gcc_unreachable ();
15096
15097     case TYPE_ARGUMENT_PACK:
15098     case NONTYPE_ARGUMENT_PACK:
15099       {
15100         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15101         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15102         int i, len = TREE_VEC_LENGTH (packed_parms);
15103         int argslen = TREE_VEC_LENGTH (packed_args);
15104         int parm_variadic_p = 0;
15105
15106         for (i = 0; i < len; ++i)
15107           {
15108             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15109               {
15110                 if (i == len - 1)
15111                   /* We can unify against something with a trailing
15112                      parameter pack.  */
15113                   parm_variadic_p = 1;
15114                 else
15115                   /* Since there is something following the pack
15116                      expansion, we cannot unify this template argument
15117                      list.  */
15118                   return 0;
15119               }
15120           }
15121           
15122
15123         /* If we don't have enough arguments to satisfy the parameters
15124            (not counting the pack expression at the end), or we have
15125            too many arguments for a parameter list that doesn't end in
15126            a pack expression, we can't unify.  */
15127         if (argslen < (len - parm_variadic_p)
15128             || (argslen > len && !parm_variadic_p))
15129           return 1;
15130
15131         /* Unify all of the parameters that precede the (optional)
15132            pack expression.  */
15133         for (i = 0; i < len - parm_variadic_p; ++i)
15134           {
15135             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15136                        TREE_VEC_ELT (packed_args, i), strict))
15137               return 1;
15138           }
15139
15140         if (parm_variadic_p)
15141           return unify_pack_expansion (tparms, targs, 
15142                                        packed_parms, packed_args,
15143                                        strict, /*call_args_p=*/false,
15144                                        /*subr=*/false);
15145         return 0;
15146       }
15147
15148       break;
15149
15150     case TYPEOF_TYPE:
15151     case DECLTYPE_TYPE:
15152       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15153          nodes.  */
15154       return 0;
15155
15156     case ERROR_MARK:
15157       /* Unification fails if we hit an error node.  */
15158       return 1;
15159
15160     default:
15161       gcc_assert (EXPR_P (parm));
15162
15163       /* We must be looking at an expression.  This can happen with
15164          something like:
15165
15166            template <int I>
15167            void foo(S<I>, S<I + 2>);
15168
15169          This is a "nondeduced context":
15170
15171            [deduct.type]
15172
15173            The nondeduced contexts are:
15174
15175            --A type that is a template-id in which one or more of
15176              the template-arguments is an expression that references
15177              a template-parameter.
15178
15179          In these cases, we assume deduction succeeded, but don't
15180          actually infer any unifications.  */
15181
15182       if (!uses_template_parms (parm)
15183           && !template_args_equal (parm, arg))
15184         return 1;
15185       else
15186         return 0;
15187     }
15188 }
15189 \f
15190 /* Note that DECL can be defined in this translation unit, if
15191    required.  */
15192
15193 static void
15194 mark_definable (tree decl)
15195 {
15196   tree clone;
15197   DECL_NOT_REALLY_EXTERN (decl) = 1;
15198   FOR_EACH_CLONE (clone, decl)
15199     DECL_NOT_REALLY_EXTERN (clone) = 1;
15200 }
15201
15202 /* Called if RESULT is explicitly instantiated, or is a member of an
15203    explicitly instantiated class.  */
15204
15205 void
15206 mark_decl_instantiated (tree result, int extern_p)
15207 {
15208   SET_DECL_EXPLICIT_INSTANTIATION (result);
15209
15210   /* If this entity has already been written out, it's too late to
15211      make any modifications.  */
15212   if (TREE_ASM_WRITTEN (result))
15213     return;
15214
15215   if (TREE_CODE (result) != FUNCTION_DECL)
15216     /* The TREE_PUBLIC flag for function declarations will have been
15217        set correctly by tsubst.  */
15218     TREE_PUBLIC (result) = 1;
15219
15220   /* This might have been set by an earlier implicit instantiation.  */
15221   DECL_COMDAT (result) = 0;
15222
15223   if (extern_p)
15224     DECL_NOT_REALLY_EXTERN (result) = 0;
15225   else
15226     {
15227       mark_definable (result);
15228       /* Always make artificials weak.  */
15229       if (DECL_ARTIFICIAL (result) && flag_weak)
15230         comdat_linkage (result);
15231       /* For WIN32 we also want to put explicit instantiations in
15232          linkonce sections.  */
15233       else if (TREE_PUBLIC (result))
15234         maybe_make_one_only (result);
15235     }
15236
15237   /* If EXTERN_P, then this function will not be emitted -- unless
15238      followed by an explicit instantiation, at which point its linkage
15239      will be adjusted.  If !EXTERN_P, then this function will be
15240      emitted here.  In neither circumstance do we want
15241      import_export_decl to adjust the linkage.  */
15242   DECL_INTERFACE_KNOWN (result) = 1;
15243 }
15244
15245 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15246    important template arguments.  If any are missing, we check whether
15247    they're important by using error_mark_node for substituting into any
15248    args that were used for partial ordering (the ones between ARGS and END)
15249    and seeing if it bubbles up.  */
15250
15251 static bool
15252 check_undeduced_parms (tree targs, tree args, tree end)
15253 {
15254   bool found = false;
15255   int i;
15256   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15257     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15258       {
15259         found = true;
15260         TREE_VEC_ELT (targs, i) = error_mark_node;
15261       }
15262   if (found)
15263     {
15264       for (; args != end; args = TREE_CHAIN (args))
15265         {
15266           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15267           if (substed == error_mark_node)
15268             return true;
15269         }
15270     }
15271   return false;
15272 }
15273
15274 /* Given two function templates PAT1 and PAT2, return:
15275
15276    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15277    -1 if PAT2 is more specialized than PAT1.
15278    0 if neither is more specialized.
15279
15280    LEN indicates the number of parameters we should consider
15281    (defaulted parameters should not be considered).
15282
15283    The 1998 std underspecified function template partial ordering, and
15284    DR214 addresses the issue.  We take pairs of arguments, one from
15285    each of the templates, and deduce them against each other.  One of
15286    the templates will be more specialized if all the *other*
15287    template's arguments deduce against its arguments and at least one
15288    of its arguments *does* *not* deduce against the other template's
15289    corresponding argument.  Deduction is done as for class templates.
15290    The arguments used in deduction have reference and top level cv
15291    qualifiers removed.  Iff both arguments were originally reference
15292    types *and* deduction succeeds in both directions, the template
15293    with the more cv-qualified argument wins for that pairing (if
15294    neither is more cv-qualified, they both are equal).  Unlike regular
15295    deduction, after all the arguments have been deduced in this way,
15296    we do *not* verify the deduced template argument values can be
15297    substituted into non-deduced contexts.
15298
15299    The logic can be a bit confusing here, because we look at deduce1 and
15300    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15301    can find template arguments for pat1 to make arg1 look like arg2, that
15302    means that arg2 is at least as specialized as arg1.  */
15303
15304 int
15305 more_specialized_fn (tree pat1, tree pat2, int len)
15306 {
15307   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15308   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15309   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15310   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15311   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15312   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15313   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15314   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15315   tree origs1, origs2;
15316   bool lose1 = false;
15317   bool lose2 = false;
15318
15319   /* Remove the this parameter from non-static member functions.  If
15320      one is a non-static member function and the other is not a static
15321      member function, remove the first parameter from that function
15322      also.  This situation occurs for operator functions where we
15323      locate both a member function (with this pointer) and non-member
15324      operator (with explicit first operand).  */
15325   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15326     {
15327       len--; /* LEN is the number of significant arguments for DECL1 */
15328       args1 = TREE_CHAIN (args1);
15329       if (!DECL_STATIC_FUNCTION_P (decl2))
15330         args2 = TREE_CHAIN (args2);
15331     }
15332   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15333     {
15334       args2 = TREE_CHAIN (args2);
15335       if (!DECL_STATIC_FUNCTION_P (decl1))
15336         {
15337           len--;
15338           args1 = TREE_CHAIN (args1);
15339         }
15340     }
15341
15342   /* If only one is a conversion operator, they are unordered.  */
15343   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15344     return 0;
15345
15346   /* Consider the return type for a conversion function */
15347   if (DECL_CONV_FN_P (decl1))
15348     {
15349       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15350       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15351       len++;
15352     }
15353
15354   processing_template_decl++;
15355
15356   origs1 = args1;
15357   origs2 = args2;
15358
15359   while (len--
15360          /* Stop when an ellipsis is seen.  */
15361          && args1 != NULL_TREE && args2 != NULL_TREE)
15362     {
15363       tree arg1 = TREE_VALUE (args1);
15364       tree arg2 = TREE_VALUE (args2);
15365       int deduce1, deduce2;
15366       int quals1 = -1;
15367       int quals2 = -1;
15368
15369       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15370           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15371         {
15372           /* When both arguments are pack expansions, we need only
15373              unify the patterns themselves.  */
15374           arg1 = PACK_EXPANSION_PATTERN (arg1);
15375           arg2 = PACK_EXPANSION_PATTERN (arg2);
15376
15377           /* This is the last comparison we need to do.  */
15378           len = 0;
15379         }
15380
15381       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15382         {
15383           arg1 = TREE_TYPE (arg1);
15384           quals1 = cp_type_quals (arg1);
15385         }
15386
15387       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15388         {
15389           arg2 = TREE_TYPE (arg2);
15390           quals2 = cp_type_quals (arg2);
15391         }
15392
15393       if ((quals1 < 0) != (quals2 < 0))
15394         {
15395           /* Only of the args is a reference, see if we should apply
15396              array/function pointer decay to it.  This is not part of
15397              DR214, but is, IMHO, consistent with the deduction rules
15398              for the function call itself, and with our earlier
15399              implementation of the underspecified partial ordering
15400              rules.  (nathan).  */
15401           if (quals1 >= 0)
15402             {
15403               switch (TREE_CODE (arg1))
15404                 {
15405                 case ARRAY_TYPE:
15406                   arg1 = TREE_TYPE (arg1);
15407                   /* FALLTHROUGH. */
15408                 case FUNCTION_TYPE:
15409                   arg1 = build_pointer_type (arg1);
15410                   break;
15411
15412                 default:
15413                   break;
15414                 }
15415             }
15416           else
15417             {
15418               switch (TREE_CODE (arg2))
15419                 {
15420                 case ARRAY_TYPE:
15421                   arg2 = TREE_TYPE (arg2);
15422                   /* FALLTHROUGH. */
15423                 case FUNCTION_TYPE:
15424                   arg2 = build_pointer_type (arg2);
15425                   break;
15426
15427                 default:
15428                   break;
15429                 }
15430             }
15431         }
15432
15433       arg1 = TYPE_MAIN_VARIANT (arg1);
15434       arg2 = TYPE_MAIN_VARIANT (arg2);
15435
15436       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15437         {
15438           int i, len2 = list_length (args2);
15439           tree parmvec = make_tree_vec (1);
15440           tree argvec = make_tree_vec (len2);
15441           tree ta = args2;
15442
15443           /* Setup the parameter vector, which contains only ARG1.  */
15444           TREE_VEC_ELT (parmvec, 0) = arg1;
15445
15446           /* Setup the argument vector, which contains the remaining
15447              arguments.  */
15448           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15449             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15450
15451           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15452                                            argvec, UNIFY_ALLOW_NONE, 
15453                                            /*call_args_p=*/false, 
15454                                            /*subr=*/0);
15455
15456           /* We cannot deduce in the other direction, because ARG1 is
15457              a pack expansion but ARG2 is not.  */
15458           deduce2 = 0;
15459         }
15460       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15461         {
15462           int i, len1 = list_length (args1);
15463           tree parmvec = make_tree_vec (1);
15464           tree argvec = make_tree_vec (len1);
15465           tree ta = args1;
15466
15467           /* Setup the parameter vector, which contains only ARG1.  */
15468           TREE_VEC_ELT (parmvec, 0) = arg2;
15469
15470           /* Setup the argument vector, which contains the remaining
15471              arguments.  */
15472           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15473             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15474
15475           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15476                                            argvec, UNIFY_ALLOW_NONE, 
15477                                            /*call_args_p=*/false, 
15478                                            /*subr=*/0);
15479
15480           /* We cannot deduce in the other direction, because ARG2 is
15481              a pack expansion but ARG1 is not.*/
15482           deduce1 = 0;
15483         }
15484
15485       else
15486         {
15487           /* The normal case, where neither argument is a pack
15488              expansion.  */
15489           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15490           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15491         }
15492
15493       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15494          arg2, then arg2 is not as specialized as arg1.  */
15495       if (!deduce1)
15496         lose2 = true;
15497       if (!deduce2)
15498         lose1 = true;
15499
15500       /* "If, for a given type, deduction succeeds in both directions
15501          (i.e., the types are identical after the transformations above)
15502          and if the type from the argument template is more cv-qualified
15503          than the type from the parameter template (as described above)
15504          that type is considered to be more specialized than the other. If
15505          neither type is more cv-qualified than the other then neither type
15506          is more specialized than the other."  */
15507
15508       if (deduce1 && deduce2
15509           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15510         {
15511           if ((quals1 & quals2) == quals2)
15512             lose2 = true;
15513           if ((quals1 & quals2) == quals1)
15514             lose1 = true;
15515         }
15516
15517       if (lose1 && lose2)
15518         /* We've failed to deduce something in either direction.
15519            These must be unordered.  */
15520         break;
15521
15522       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15523           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15524         /* We have already processed all of the arguments in our
15525            handing of the pack expansion type.  */
15526         len = 0;
15527
15528       args1 = TREE_CHAIN (args1);
15529       args2 = TREE_CHAIN (args2);
15530     }
15531
15532   /* "In most cases, all template parameters must have values in order for
15533      deduction to succeed, but for partial ordering purposes a template
15534      parameter may remain without a value provided it is not used in the
15535      types being used for partial ordering."
15536
15537      Thus, if we are missing any of the targs1 we need to substitute into
15538      origs1, then pat2 is not as specialized as pat1.  This can happen when
15539      there is a nondeduced context.  */
15540   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15541     lose2 = true;
15542   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15543     lose1 = true;
15544
15545   processing_template_decl--;
15546
15547   /* All things being equal, if the next argument is a pack expansion
15548      for one function but not for the other, prefer the
15549      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15550   if (lose1 == lose2
15551       && args1 && TREE_VALUE (args1)
15552       && args2 && TREE_VALUE (args2))
15553     {
15554       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15555       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15556     }
15557
15558   if (lose1 == lose2)
15559     return 0;
15560   else if (!lose1)
15561     return 1;
15562   else
15563     return -1;
15564 }
15565
15566 /* Determine which of two partial specializations is more specialized.
15567
15568    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15569    to the first partial specialization.  The TREE_VALUE is the
15570    innermost set of template parameters for the partial
15571    specialization.  PAT2 is similar, but for the second template.
15572
15573    Return 1 if the first partial specialization is more specialized;
15574    -1 if the second is more specialized; 0 if neither is more
15575    specialized.
15576
15577    See [temp.class.order] for information about determining which of
15578    two templates is more specialized.  */
15579
15580 static int
15581 more_specialized_class (tree pat1, tree pat2)
15582 {
15583   tree targs;
15584   tree tmpl1, tmpl2;
15585   int winner = 0;
15586   bool any_deductions = false;
15587
15588   tmpl1 = TREE_TYPE (pat1);
15589   tmpl2 = TREE_TYPE (pat2);
15590
15591   /* Just like what happens for functions, if we are ordering between
15592      different class template specializations, we may encounter dependent
15593      types in the arguments, and we need our dependency check functions
15594      to behave correctly.  */
15595   ++processing_template_decl;
15596   targs = get_class_bindings (TREE_VALUE (pat1),
15597                               CLASSTYPE_TI_ARGS (tmpl1),
15598                               CLASSTYPE_TI_ARGS (tmpl2));
15599   if (targs)
15600     {
15601       --winner;
15602       any_deductions = true;
15603     }
15604
15605   targs = get_class_bindings (TREE_VALUE (pat2),
15606                               CLASSTYPE_TI_ARGS (tmpl2),
15607                               CLASSTYPE_TI_ARGS (tmpl1));
15608   if (targs)
15609     {
15610       ++winner;
15611       any_deductions = true;
15612     }
15613   --processing_template_decl;
15614
15615   /* In the case of a tie where at least one of the class templates
15616      has a parameter pack at the end, the template with the most
15617      non-packed parameters wins.  */
15618   if (winner == 0
15619       && any_deductions
15620       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15621           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15622     {
15623       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15624       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15625       int len1 = TREE_VEC_LENGTH (args1);
15626       int len2 = TREE_VEC_LENGTH (args2);
15627
15628       /* We don't count the pack expansion at the end.  */
15629       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15630         --len1;
15631       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15632         --len2;
15633
15634       if (len1 > len2)
15635         return 1;
15636       else if (len1 < len2)
15637         return -1;
15638     }
15639
15640   return winner;
15641 }
15642
15643 /* Return the template arguments that will produce the function signature
15644    DECL from the function template FN, with the explicit template
15645    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15646    also match.  Return NULL_TREE if no satisfactory arguments could be
15647    found.  */
15648
15649 static tree
15650 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15651 {
15652   int ntparms = DECL_NTPARMS (fn);
15653   tree targs = make_tree_vec (ntparms);
15654   tree decl_type;
15655   tree decl_arg_types;
15656   tree *args;
15657   unsigned int nargs, ix;
15658   tree arg;
15659
15660   /* Substitute the explicit template arguments into the type of DECL.
15661      The call to fn_type_unification will handle substitution into the
15662      FN.  */
15663   decl_type = TREE_TYPE (decl);
15664   if (explicit_args && uses_template_parms (decl_type))
15665     {
15666       tree tmpl;
15667       tree converted_args;
15668
15669       if (DECL_TEMPLATE_INFO (decl))
15670         tmpl = DECL_TI_TEMPLATE (decl);
15671       else
15672         /* We can get here for some invalid specializations.  */
15673         return NULL_TREE;
15674
15675       converted_args
15676         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15677                                  explicit_args, NULL_TREE,
15678                                  tf_none,
15679                                  /*require_all_args=*/false,
15680                                  /*use_default_args=*/false);
15681       if (converted_args == error_mark_node)
15682         return NULL_TREE;
15683
15684       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15685       if (decl_type == error_mark_node)
15686         return NULL_TREE;
15687     }
15688
15689   /* Never do unification on the 'this' parameter.  */
15690   decl_arg_types = skip_artificial_parms_for (decl, 
15691                                               TYPE_ARG_TYPES (decl_type));
15692
15693   nargs = list_length (decl_arg_types);
15694   args = XALLOCAVEC (tree, nargs);
15695   for (arg = decl_arg_types, ix = 0;
15696        arg != NULL_TREE && arg != void_list_node;
15697        arg = TREE_CHAIN (arg), ++ix)
15698     args[ix] = TREE_VALUE (arg);
15699
15700   if (fn_type_unification (fn, explicit_args, targs,
15701                            args, ix,
15702                            (check_rettype || DECL_CONV_FN_P (fn)
15703                             ? TREE_TYPE (decl_type) : NULL_TREE),
15704                            DEDUCE_EXACT, LOOKUP_NORMAL))
15705     return NULL_TREE;
15706
15707   return targs;
15708 }
15709
15710 /* Return the innermost template arguments that, when applied to a
15711    template specialization whose innermost template parameters are
15712    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15713    ARGS.
15714
15715    For example, suppose we have:
15716
15717      template <class T, class U> struct S {};
15718      template <class T> struct S<T*, int> {};
15719
15720    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15721    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15722    int}.  The resulting vector will be {double}, indicating that `T'
15723    is bound to `double'.  */
15724
15725 static tree
15726 get_class_bindings (tree tparms, tree spec_args, tree args)
15727 {
15728   int i, ntparms = TREE_VEC_LENGTH (tparms);
15729   tree deduced_args;
15730   tree innermost_deduced_args;
15731
15732   innermost_deduced_args = make_tree_vec (ntparms);
15733   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15734     {
15735       deduced_args = copy_node (args);
15736       SET_TMPL_ARGS_LEVEL (deduced_args,
15737                            TMPL_ARGS_DEPTH (deduced_args),
15738                            innermost_deduced_args);
15739     }
15740   else
15741     deduced_args = innermost_deduced_args;
15742
15743   if (unify (tparms, deduced_args,
15744              INNERMOST_TEMPLATE_ARGS (spec_args),
15745              INNERMOST_TEMPLATE_ARGS (args),
15746              UNIFY_ALLOW_NONE))
15747     return NULL_TREE;
15748
15749   for (i =  0; i < ntparms; ++i)
15750     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15751       return NULL_TREE;
15752
15753   /* Verify that nondeduced template arguments agree with the type
15754      obtained from argument deduction.
15755
15756      For example:
15757
15758        struct A { typedef int X; };
15759        template <class T, class U> struct C {};
15760        template <class T> struct C<T, typename T::X> {};
15761
15762      Then with the instantiation `C<A, int>', we can deduce that
15763      `T' is `A' but unify () does not check whether `typename T::X'
15764      is `int'.  */
15765   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15766   if (spec_args == error_mark_node
15767       /* We only need to check the innermost arguments; the other
15768          arguments will always agree.  */
15769       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15770                               INNERMOST_TEMPLATE_ARGS (args)))
15771     return NULL_TREE;
15772
15773   /* Now that we have bindings for all of the template arguments,
15774      ensure that the arguments deduced for the template template
15775      parameters have compatible template parameter lists.  See the use
15776      of template_template_parm_bindings_ok_p in fn_type_unification
15777      for more information.  */
15778   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15779     return NULL_TREE;
15780
15781   return deduced_args;
15782 }
15783
15784 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15785    Return the TREE_LIST node with the most specialized template, if
15786    any.  If there is no most specialized template, the error_mark_node
15787    is returned.
15788
15789    Note that this function does not look at, or modify, the
15790    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15791    returned is one of the elements of INSTANTIATIONS, callers may
15792    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15793    and retrieve it from the value returned.  */
15794
15795 tree
15796 most_specialized_instantiation (tree templates)
15797 {
15798   tree fn, champ;
15799
15800   ++processing_template_decl;
15801
15802   champ = templates;
15803   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15804     {
15805       int fate = 0;
15806
15807       if (get_bindings (TREE_VALUE (champ),
15808                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15809                         NULL_TREE, /*check_ret=*/false))
15810         fate--;
15811
15812       if (get_bindings (TREE_VALUE (fn),
15813                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15814                         NULL_TREE, /*check_ret=*/false))
15815         fate++;
15816
15817       if (fate == -1)
15818         champ = fn;
15819       else if (!fate)
15820         {
15821           /* Equally specialized, move to next function.  If there
15822              is no next function, nothing's most specialized.  */
15823           fn = TREE_CHAIN (fn);
15824           champ = fn;
15825           if (!fn)
15826             break;
15827         }
15828     }
15829
15830   if (champ)
15831     /* Now verify that champ is better than everything earlier in the
15832        instantiation list.  */
15833     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15834       if (get_bindings (TREE_VALUE (champ),
15835                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15836                         NULL_TREE, /*check_ret=*/false)
15837           || !get_bindings (TREE_VALUE (fn),
15838                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15839                             NULL_TREE, /*check_ret=*/false))
15840         {
15841           champ = NULL_TREE;
15842           break;
15843         }
15844
15845   processing_template_decl--;
15846
15847   if (!champ)
15848     return error_mark_node;
15849
15850   return champ;
15851 }
15852
15853 /* If DECL is a specialization of some template, return the most
15854    general such template.  Otherwise, returns NULL_TREE.
15855
15856    For example, given:
15857
15858      template <class T> struct S { template <class U> void f(U); };
15859
15860    if TMPL is `template <class U> void S<int>::f(U)' this will return
15861    the full template.  This function will not trace past partial
15862    specializations, however.  For example, given in addition:
15863
15864      template <class T> struct S<T*> { template <class U> void f(U); };
15865
15866    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15867    `template <class T> template <class U> S<T*>::f(U)'.  */
15868
15869 tree
15870 most_general_template (tree decl)
15871 {
15872   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15873      an immediate specialization.  */
15874   if (TREE_CODE (decl) == FUNCTION_DECL)
15875     {
15876       if (DECL_TEMPLATE_INFO (decl)) {
15877         decl = DECL_TI_TEMPLATE (decl);
15878
15879         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15880            template friend.  */
15881         if (TREE_CODE (decl) != TEMPLATE_DECL)
15882           return NULL_TREE;
15883       } else
15884         return NULL_TREE;
15885     }
15886
15887   /* Look for more and more general templates.  */
15888   while (DECL_TEMPLATE_INFO (decl))
15889     {
15890       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15891          (See cp-tree.h for details.)  */
15892       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15893         break;
15894
15895       if (CLASS_TYPE_P (TREE_TYPE (decl))
15896           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15897         break;
15898
15899       /* Stop if we run into an explicitly specialized class template.  */
15900       if (!DECL_NAMESPACE_SCOPE_P (decl)
15901           && DECL_CONTEXT (decl)
15902           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15903         break;
15904
15905       decl = DECL_TI_TEMPLATE (decl);
15906     }
15907
15908   return decl;
15909 }
15910
15911 /* Return the most specialized of the class template partial
15912    specializations of TMPL which can produce TYPE, a specialization of
15913    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15914    a _TYPE node corresponding to the partial specialization, while the
15915    TREE_PURPOSE is the set of template arguments that must be
15916    substituted into the TREE_TYPE in order to generate TYPE.
15917
15918    If the choice of partial specialization is ambiguous, a diagnostic
15919    is issued, and the error_mark_node is returned.  If there are no
15920    partial specializations of TMPL matching TYPE, then NULL_TREE is
15921    returned.  */
15922
15923 static tree
15924 most_specialized_class (tree type, tree tmpl)
15925 {
15926   tree list = NULL_TREE;
15927   tree t;
15928   tree champ;
15929   int fate;
15930   bool ambiguous_p;
15931   tree args;
15932   tree outer_args = NULL_TREE;
15933
15934   tmpl = most_general_template (tmpl);
15935   args = CLASSTYPE_TI_ARGS (type);
15936
15937   /* For determining which partial specialization to use, only the
15938      innermost args are interesting.  */
15939   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15940     {
15941       outer_args = strip_innermost_template_args (args, 1);
15942       args = INNERMOST_TEMPLATE_ARGS (args);
15943     }
15944
15945   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15946     {
15947       tree partial_spec_args;
15948       tree spec_args;
15949       tree parms = TREE_VALUE (t);
15950
15951       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15952
15953       ++processing_template_decl;
15954
15955       if (outer_args)
15956         {
15957           int i;
15958
15959           /* Discard the outer levels of args, and then substitute in the
15960              template args from the enclosing class.  */
15961           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15962           partial_spec_args = tsubst_template_args
15963             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15964
15965           /* PARMS already refers to just the innermost parms, but the
15966              template parms in partial_spec_args had their levels lowered
15967              by tsubst, so we need to do the same for the parm list.  We
15968              can't just tsubst the TREE_VEC itself, as tsubst wants to
15969              treat a TREE_VEC as an argument vector.  */
15970           parms = copy_node (parms);
15971           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15972             TREE_VEC_ELT (parms, i) =
15973               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15974
15975         }
15976
15977       partial_spec_args =
15978           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15979                                  add_to_template_args (outer_args,
15980                                                        partial_spec_args),
15981                                  tmpl, tf_none,
15982                                  /*require_all_args=*/true,
15983                                  /*use_default_args=*/true);
15984
15985       if (partial_spec_args == error_mark_node)
15986         return error_mark_node;
15987
15988       spec_args = get_class_bindings (parms,
15989                                       partial_spec_args,
15990                                       args);
15991       if (spec_args)
15992         {
15993           if (outer_args)
15994             spec_args = add_to_template_args (outer_args, spec_args);
15995           list = tree_cons (spec_args, TREE_VALUE (t), list);
15996           TREE_TYPE (list) = TREE_TYPE (t);
15997         }
15998     }
15999
16000   if (! list)
16001     return NULL_TREE;
16002
16003   ambiguous_p = false;
16004   t = list;
16005   champ = t;
16006   t = TREE_CHAIN (t);
16007   for (; t; t = TREE_CHAIN (t))
16008     {
16009       fate = more_specialized_class (champ, t);
16010       if (fate == 1)
16011         ;
16012       else
16013         {
16014           if (fate == 0)
16015             {
16016               t = TREE_CHAIN (t);
16017               if (! t)
16018                 {
16019                   ambiguous_p = true;
16020                   break;
16021                 }
16022             }
16023           champ = t;
16024         }
16025     }
16026
16027   if (!ambiguous_p)
16028     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16029       {
16030         fate = more_specialized_class (champ, t);
16031         if (fate != 1)
16032           {
16033             ambiguous_p = true;
16034             break;
16035           }
16036       }
16037
16038   if (ambiguous_p)
16039     {
16040       const char *str;
16041       char *spaces = NULL;
16042       error ("ambiguous class template instantiation for %q#T", type);
16043       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16044       for (t = list; t; t = TREE_CHAIN (t))
16045         {
16046           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16047           spaces = spaces ? spaces : get_spaces (str);
16048         }
16049       free (spaces);
16050       return error_mark_node;
16051     }
16052
16053   return champ;
16054 }
16055
16056 /* Explicitly instantiate DECL.  */
16057
16058 void
16059 do_decl_instantiation (tree decl, tree storage)
16060 {
16061   tree result = NULL_TREE;
16062   int extern_p = 0;
16063
16064   if (!decl || decl == error_mark_node)
16065     /* An error occurred, for which grokdeclarator has already issued
16066        an appropriate message.  */
16067     return;
16068   else if (! DECL_LANG_SPECIFIC (decl))
16069     {
16070       error ("explicit instantiation of non-template %q#D", decl);
16071       return;
16072     }
16073   else if (TREE_CODE (decl) == VAR_DECL)
16074     {
16075       /* There is an asymmetry here in the way VAR_DECLs and
16076          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16077          the latter, the DECL we get back will be marked as a
16078          template instantiation, and the appropriate
16079          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16080          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16081          should handle VAR_DECLs as it currently handles
16082          FUNCTION_DECLs.  */
16083       if (!DECL_CLASS_SCOPE_P (decl))
16084         {
16085           error ("%qD is not a static data member of a class template", decl);
16086           return;
16087         }
16088       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16089       if (!result || TREE_CODE (result) != VAR_DECL)
16090         {
16091           error ("no matching template for %qD found", decl);
16092           return;
16093         }
16094       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16095         {
16096           error ("type %qT for explicit instantiation %qD does not match "
16097                  "declared type %qT", TREE_TYPE (result), decl,
16098                  TREE_TYPE (decl));
16099           return;
16100         }
16101     }
16102   else if (TREE_CODE (decl) != FUNCTION_DECL)
16103     {
16104       error ("explicit instantiation of %q#D", decl);
16105       return;
16106     }
16107   else
16108     result = decl;
16109
16110   /* Check for various error cases.  Note that if the explicit
16111      instantiation is valid the RESULT will currently be marked as an
16112      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16113      until we get here.  */
16114
16115   if (DECL_TEMPLATE_SPECIALIZATION (result))
16116     {
16117       /* DR 259 [temp.spec].
16118
16119          Both an explicit instantiation and a declaration of an explicit
16120          specialization shall not appear in a program unless the explicit
16121          instantiation follows a declaration of the explicit specialization.
16122
16123          For a given set of template parameters, if an explicit
16124          instantiation of a template appears after a declaration of an
16125          explicit specialization for that template, the explicit
16126          instantiation has no effect.  */
16127       return;
16128     }
16129   else if (DECL_EXPLICIT_INSTANTIATION (result))
16130     {
16131       /* [temp.spec]
16132
16133          No program shall explicitly instantiate any template more
16134          than once.
16135
16136          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16137          the first instantiation was `extern' and the second is not,
16138          and EXTERN_P for the opposite case.  */
16139       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16140         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16141       /* If an "extern" explicit instantiation follows an ordinary
16142          explicit instantiation, the template is instantiated.  */
16143       if (extern_p)
16144         return;
16145     }
16146   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16147     {
16148       error ("no matching template for %qD found", result);
16149       return;
16150     }
16151   else if (!DECL_TEMPLATE_INFO (result))
16152     {
16153       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16154       return;
16155     }
16156
16157   if (storage == NULL_TREE)
16158     ;
16159   else if (storage == ridpointers[(int) RID_EXTERN])
16160     {
16161       if (!in_system_header && (cxx_dialect == cxx98))
16162         pedwarn (input_location, OPT_pedantic, 
16163                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16164                  "instantiations");
16165       extern_p = 1;
16166     }
16167   else
16168     error ("storage class %qD applied to template instantiation", storage);
16169
16170   check_explicit_instantiation_namespace (result);
16171   mark_decl_instantiated (result, extern_p);
16172   if (! extern_p)
16173     instantiate_decl (result, /*defer_ok=*/1,
16174                       /*expl_inst_class_mem_p=*/false);
16175 }
16176
16177 static void
16178 mark_class_instantiated (tree t, int extern_p)
16179 {
16180   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16181   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16182   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16183   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16184   if (! extern_p)
16185     {
16186       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16187       rest_of_type_compilation (t, 1);
16188     }
16189 }
16190
16191 /* Called from do_type_instantiation through binding_table_foreach to
16192    do recursive instantiation for the type bound in ENTRY.  */
16193 static void
16194 bt_instantiate_type_proc (binding_entry entry, void *data)
16195 {
16196   tree storage = *(tree *) data;
16197
16198   if (MAYBE_CLASS_TYPE_P (entry->type)
16199       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16200     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16201 }
16202
16203 /* Called from do_type_instantiation to instantiate a member
16204    (a member function or a static member variable) of an
16205    explicitly instantiated class template.  */
16206 static void
16207 instantiate_class_member (tree decl, int extern_p)
16208 {
16209   mark_decl_instantiated (decl, extern_p);
16210   if (! extern_p)
16211     instantiate_decl (decl, /*defer_ok=*/1,
16212                       /*expl_inst_class_mem_p=*/true);
16213 }
16214
16215 /* Perform an explicit instantiation of template class T.  STORAGE, if
16216    non-null, is the RID for extern, inline or static.  COMPLAIN is
16217    nonzero if this is called from the parser, zero if called recursively,
16218    since the standard is unclear (as detailed below).  */
16219
16220 void
16221 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16222 {
16223   int extern_p = 0;
16224   int nomem_p = 0;
16225   int static_p = 0;
16226   int previous_instantiation_extern_p = 0;
16227
16228   if (TREE_CODE (t) == TYPE_DECL)
16229     t = TREE_TYPE (t);
16230
16231   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16232     {
16233       error ("explicit instantiation of non-template type %qT", t);
16234       return;
16235     }
16236
16237   complete_type (t);
16238
16239   if (!COMPLETE_TYPE_P (t))
16240     {
16241       if (complain & tf_error)
16242         error ("explicit instantiation of %q#T before definition of template",
16243                t);
16244       return;
16245     }
16246
16247   if (storage != NULL_TREE)
16248     {
16249       if (!in_system_header)
16250         {
16251           if (storage == ridpointers[(int) RID_EXTERN])
16252             {
16253               if (cxx_dialect == cxx98)
16254                 pedwarn (input_location, OPT_pedantic, 
16255                          "ISO C++ 1998 forbids the use of %<extern%> on "
16256                          "explicit instantiations");
16257             }
16258           else
16259             pedwarn (input_location, OPT_pedantic, 
16260                      "ISO C++ forbids the use of %qE"
16261                      " on explicit instantiations", storage);
16262         }
16263
16264       if (storage == ridpointers[(int) RID_INLINE])
16265         nomem_p = 1;
16266       else if (storage == ridpointers[(int) RID_EXTERN])
16267         extern_p = 1;
16268       else if (storage == ridpointers[(int) RID_STATIC])
16269         static_p = 1;
16270       else
16271         {
16272           error ("storage class %qD applied to template instantiation",
16273                  storage);
16274           extern_p = 0;
16275         }
16276     }
16277
16278   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16279     {
16280       /* DR 259 [temp.spec].
16281
16282          Both an explicit instantiation and a declaration of an explicit
16283          specialization shall not appear in a program unless the explicit
16284          instantiation follows a declaration of the explicit specialization.
16285
16286          For a given set of template parameters, if an explicit
16287          instantiation of a template appears after a declaration of an
16288          explicit specialization for that template, the explicit
16289          instantiation has no effect.  */
16290       return;
16291     }
16292   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16293     {
16294       /* [temp.spec]
16295
16296          No program shall explicitly instantiate any template more
16297          than once.
16298
16299          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16300          instantiation was `extern'.  If EXTERN_P then the second is.
16301          These cases are OK.  */
16302       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16303
16304       if (!previous_instantiation_extern_p && !extern_p
16305           && (complain & tf_error))
16306         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16307
16308       /* If we've already instantiated the template, just return now.  */
16309       if (!CLASSTYPE_INTERFACE_ONLY (t))
16310         return;
16311     }
16312
16313   check_explicit_instantiation_namespace (TYPE_NAME (t));
16314   mark_class_instantiated (t, extern_p);
16315
16316   if (nomem_p)
16317     return;
16318
16319   {
16320     tree tmp;
16321
16322     /* In contrast to implicit instantiation, where only the
16323        declarations, and not the definitions, of members are
16324        instantiated, we have here:
16325
16326          [temp.explicit]
16327
16328          The explicit instantiation of a class template specialization
16329          implies the instantiation of all of its members not
16330          previously explicitly specialized in the translation unit
16331          containing the explicit instantiation.
16332
16333        Of course, we can't instantiate member template classes, since
16334        we don't have any arguments for them.  Note that the standard
16335        is unclear on whether the instantiation of the members are
16336        *explicit* instantiations or not.  However, the most natural
16337        interpretation is that it should be an explicit instantiation.  */
16338
16339     if (! static_p)
16340       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16341         if (TREE_CODE (tmp) == FUNCTION_DECL
16342             && DECL_TEMPLATE_INSTANTIATION (tmp))
16343           instantiate_class_member (tmp, extern_p);
16344
16345     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16346       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16347         instantiate_class_member (tmp, extern_p);
16348
16349     if (CLASSTYPE_NESTED_UTDS (t))
16350       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16351                              bt_instantiate_type_proc, &storage);
16352   }
16353 }
16354
16355 /* Given a function DECL, which is a specialization of TMPL, modify
16356    DECL to be a re-instantiation of TMPL with the same template
16357    arguments.  TMPL should be the template into which tsubst'ing
16358    should occur for DECL, not the most general template.
16359
16360    One reason for doing this is a scenario like this:
16361
16362      template <class T>
16363      void f(const T&, int i);
16364
16365      void g() { f(3, 7); }
16366
16367      template <class T>
16368      void f(const T& t, const int i) { }
16369
16370    Note that when the template is first instantiated, with
16371    instantiate_template, the resulting DECL will have no name for the
16372    first parameter, and the wrong type for the second.  So, when we go
16373    to instantiate the DECL, we regenerate it.  */
16374
16375 static void
16376 regenerate_decl_from_template (tree decl, tree tmpl)
16377 {
16378   /* The arguments used to instantiate DECL, from the most general
16379      template.  */
16380   tree args;
16381   tree code_pattern;
16382
16383   args = DECL_TI_ARGS (decl);
16384   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16385
16386   /* Make sure that we can see identifiers, and compute access
16387      correctly.  */
16388   push_access_scope (decl);
16389
16390   if (TREE_CODE (decl) == FUNCTION_DECL)
16391     {
16392       tree decl_parm;
16393       tree pattern_parm;
16394       tree specs;
16395       int args_depth;
16396       int parms_depth;
16397
16398       args_depth = TMPL_ARGS_DEPTH (args);
16399       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16400       if (args_depth > parms_depth)
16401         args = get_innermost_template_args (args, parms_depth);
16402
16403       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16404                                               args, tf_error, NULL_TREE);
16405       if (specs)
16406         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16407                                                     specs);
16408
16409       /* Merge parameter declarations.  */
16410       decl_parm = skip_artificial_parms_for (decl,
16411                                              DECL_ARGUMENTS (decl));
16412       pattern_parm
16413         = skip_artificial_parms_for (code_pattern,
16414                                      DECL_ARGUMENTS (code_pattern));
16415       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16416         {
16417           tree parm_type;
16418           tree attributes;
16419           
16420           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16421             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16422           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16423                               NULL_TREE);
16424           parm_type = type_decays_to (parm_type);
16425           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16426             TREE_TYPE (decl_parm) = parm_type;
16427           attributes = DECL_ATTRIBUTES (pattern_parm);
16428           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16429             {
16430               DECL_ATTRIBUTES (decl_parm) = attributes;
16431               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16432             }
16433           decl_parm = TREE_CHAIN (decl_parm);
16434           pattern_parm = TREE_CHAIN (pattern_parm);
16435         }
16436       /* Merge any parameters that match with the function parameter
16437          pack.  */
16438       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16439         {
16440           int i, len;
16441           tree expanded_types;
16442           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16443              the parameters in this function parameter pack.  */
16444           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16445                                                  args, tf_error, NULL_TREE);
16446           len = TREE_VEC_LENGTH (expanded_types);
16447           for (i = 0; i < len; i++)
16448             {
16449               tree parm_type;
16450               tree attributes;
16451           
16452               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16453                 /* Rename the parameter to include the index.  */
16454                 DECL_NAME (decl_parm) = 
16455                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16456               parm_type = TREE_VEC_ELT (expanded_types, i);
16457               parm_type = type_decays_to (parm_type);
16458               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16459                 TREE_TYPE (decl_parm) = parm_type;
16460               attributes = DECL_ATTRIBUTES (pattern_parm);
16461               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16462                 {
16463                   DECL_ATTRIBUTES (decl_parm) = attributes;
16464                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16465                 }
16466               decl_parm = TREE_CHAIN (decl_parm);
16467             }
16468         }
16469       /* Merge additional specifiers from the CODE_PATTERN.  */
16470       if (DECL_DECLARED_INLINE_P (code_pattern)
16471           && !DECL_DECLARED_INLINE_P (decl))
16472         DECL_DECLARED_INLINE_P (decl) = 1;
16473     }
16474   else if (TREE_CODE (decl) == VAR_DECL)
16475     {
16476       DECL_INITIAL (decl) =
16477         tsubst_expr (DECL_INITIAL (code_pattern), args,
16478                      tf_error, DECL_TI_TEMPLATE (decl),
16479                      /*integral_constant_expression_p=*/false);
16480       if (VAR_HAD_UNKNOWN_BOUND (decl))
16481         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16482                                    tf_error, DECL_TI_TEMPLATE (decl));
16483     }
16484   else
16485     gcc_unreachable ();
16486
16487   pop_access_scope (decl);
16488 }
16489
16490 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16491    substituted to get DECL.  */
16492
16493 tree
16494 template_for_substitution (tree decl)
16495 {
16496   tree tmpl = DECL_TI_TEMPLATE (decl);
16497
16498   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16499      for the instantiation.  This is not always the most general
16500      template.  Consider, for example:
16501
16502         template <class T>
16503         struct S { template <class U> void f();
16504                    template <> void f<int>(); };
16505
16506      and an instantiation of S<double>::f<int>.  We want TD to be the
16507      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16508   while (/* An instantiation cannot have a definition, so we need a
16509             more general template.  */
16510          DECL_TEMPLATE_INSTANTIATION (tmpl)
16511            /* We must also deal with friend templates.  Given:
16512
16513                 template <class T> struct S {
16514                   template <class U> friend void f() {};
16515                 };
16516
16517               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16518               so far as the language is concerned, but that's still
16519               where we get the pattern for the instantiation from.  On
16520               other hand, if the definition comes outside the class, say:
16521
16522                 template <class T> struct S {
16523                   template <class U> friend void f();
16524                 };
16525                 template <class U> friend void f() {}
16526
16527               we don't need to look any further.  That's what the check for
16528               DECL_INITIAL is for.  */
16529           || (TREE_CODE (decl) == FUNCTION_DECL
16530               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16531               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16532     {
16533       /* The present template, TD, should not be a definition.  If it
16534          were a definition, we should be using it!  Note that we
16535          cannot restructure the loop to just keep going until we find
16536          a template with a definition, since that might go too far if
16537          a specialization was declared, but not defined.  */
16538       gcc_assert (TREE_CODE (decl) != VAR_DECL
16539                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16540
16541       /* Fetch the more general template.  */
16542       tmpl = DECL_TI_TEMPLATE (tmpl);
16543     }
16544
16545   return tmpl;
16546 }
16547
16548 /* Returns true if we need to instantiate this template instance even if we
16549    know we aren't going to emit it..  */
16550
16551 bool
16552 always_instantiate_p (tree decl)
16553 {
16554   /* We always instantiate inline functions so that we can inline them.  An
16555      explicit instantiation declaration prohibits implicit instantiation of
16556      non-inline functions.  With high levels of optimization, we would
16557      normally inline non-inline functions -- but we're not allowed to do
16558      that for "extern template" functions.  Therefore, we check
16559      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16560   return ((TREE_CODE (decl) == FUNCTION_DECL
16561            && DECL_DECLARED_INLINE_P (decl))
16562           /* And we need to instantiate static data members so that
16563              their initializers are available in integral constant
16564              expressions.  */
16565           || (TREE_CODE (decl) == VAR_DECL
16566               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16567 }
16568
16569 /* Produce the definition of D, a _DECL generated from a template.  If
16570    DEFER_OK is nonzero, then we don't have to actually do the
16571    instantiation now; we just have to do it sometime.  Normally it is
16572    an error if this is an explicit instantiation but D is undefined.
16573    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16574    explicitly instantiated class template.  */
16575
16576 tree
16577 instantiate_decl (tree d, int defer_ok,
16578                   bool expl_inst_class_mem_p)
16579 {
16580   tree tmpl = DECL_TI_TEMPLATE (d);
16581   tree gen_args;
16582   tree args;
16583   tree td;
16584   tree code_pattern;
16585   tree spec;
16586   tree gen_tmpl;
16587   bool pattern_defined;
16588   int need_push;
16589   location_t saved_loc = input_location;
16590   bool external_p;
16591
16592   /* This function should only be used to instantiate templates for
16593      functions and static member variables.  */
16594   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16595               || TREE_CODE (d) == VAR_DECL);
16596
16597   /* Variables are never deferred; if instantiation is required, they
16598      are instantiated right away.  That allows for better code in the
16599      case that an expression refers to the value of the variable --
16600      if the variable has a constant value the referring expression can
16601      take advantage of that fact.  */
16602   if (TREE_CODE (d) == VAR_DECL)
16603     defer_ok = 0;
16604
16605   /* Don't instantiate cloned functions.  Instead, instantiate the
16606      functions they cloned.  */
16607   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16608     d = DECL_CLONED_FUNCTION (d);
16609
16610   if (DECL_TEMPLATE_INSTANTIATED (d)
16611       || DECL_TEMPLATE_SPECIALIZATION (d))
16612     /* D has already been instantiated or explicitly specialized, so
16613        there's nothing for us to do here.
16614
16615        It might seem reasonable to check whether or not D is an explicit
16616        instantiation, and, if so, stop here.  But when an explicit
16617        instantiation is deferred until the end of the compilation,
16618        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16619        the instantiation.  */
16620     return d;
16621
16622   /* Check to see whether we know that this template will be
16623      instantiated in some other file, as with "extern template"
16624      extension.  */
16625   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16626
16627   /* In general, we do not instantiate such templates.  */
16628   if (external_p && !always_instantiate_p (d))
16629     return d;
16630
16631   gen_tmpl = most_general_template (tmpl);
16632   gen_args = DECL_TI_ARGS (d);
16633
16634   if (tmpl != gen_tmpl)
16635     /* We should already have the extra args.  */
16636     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16637                 == TMPL_ARGS_DEPTH (gen_args));
16638   /* And what's in the hash table should match D.  */
16639   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16640               || spec == NULL_TREE);
16641
16642   /* This needs to happen before any tsubsting.  */
16643   if (! push_tinst_level (d))
16644     return d;
16645
16646   timevar_push (TV_PARSE);
16647
16648   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16649      for the instantiation.  */
16650   td = template_for_substitution (d);
16651   code_pattern = DECL_TEMPLATE_RESULT (td);
16652
16653   /* We should never be trying to instantiate a member of a class
16654      template or partial specialization.  */
16655   gcc_assert (d != code_pattern);
16656
16657   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16658       || DECL_TEMPLATE_SPECIALIZATION (td))
16659     /* In the case of a friend template whose definition is provided
16660        outside the class, we may have too many arguments.  Drop the
16661        ones we don't need.  The same is true for specializations.  */
16662     args = get_innermost_template_args
16663       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16664   else
16665     args = gen_args;
16666
16667   if (TREE_CODE (d) == FUNCTION_DECL)
16668     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16669   else
16670     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16671
16672   /* We may be in the middle of deferred access check.  Disable it now.  */
16673   push_deferring_access_checks (dk_no_deferred);
16674
16675   /* Unless an explicit instantiation directive has already determined
16676      the linkage of D, remember that a definition is available for
16677      this entity.  */
16678   if (pattern_defined
16679       && !DECL_INTERFACE_KNOWN (d)
16680       && !DECL_NOT_REALLY_EXTERN (d))
16681     mark_definable (d);
16682
16683   input_location = DECL_SOURCE_LOCATION (d);
16684
16685   /* If D is a member of an explicitly instantiated class template,
16686      and no definition is available, treat it like an implicit
16687      instantiation.  */
16688   if (!pattern_defined && expl_inst_class_mem_p
16689       && DECL_EXPLICIT_INSTANTIATION (d))
16690     {
16691       DECL_NOT_REALLY_EXTERN (d) = 0;
16692       DECL_INTERFACE_KNOWN (d) = 0;
16693       SET_DECL_IMPLICIT_INSTANTIATION (d);
16694     }
16695
16696   /* Recheck the substitutions to obtain any warning messages
16697      about ignoring cv qualifiers.  Don't do this for artificial decls,
16698      as it breaks the context-sensitive substitution for lambda op(). */
16699   if (!defer_ok && !DECL_ARTIFICIAL (d))
16700     {
16701       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16702       tree type = TREE_TYPE (gen);
16703
16704       /* Make sure that we can see identifiers, and compute access
16705          correctly.  D is already the target FUNCTION_DECL with the
16706          right context.  */
16707       push_access_scope (d);
16708
16709       if (TREE_CODE (gen) == FUNCTION_DECL)
16710         {
16711           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16712           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16713                                           d);
16714           /* Don't simply tsubst the function type, as that will give
16715              duplicate warnings about poor parameter qualifications.
16716              The function arguments are the same as the decl_arguments
16717              without the top level cv qualifiers.  */
16718           type = TREE_TYPE (type);
16719         }
16720       tsubst (type, gen_args, tf_warning_or_error, d);
16721
16722       pop_access_scope (d);
16723     }
16724
16725   /* Defer all other templates, unless we have been explicitly
16726      forbidden from doing so.  */
16727   if (/* If there is no definition, we cannot instantiate the
16728          template.  */
16729       ! pattern_defined
16730       /* If it's OK to postpone instantiation, do so.  */
16731       || defer_ok
16732       /* If this is a static data member that will be defined
16733          elsewhere, we don't want to instantiate the entire data
16734          member, but we do want to instantiate the initializer so that
16735          we can substitute that elsewhere.  */
16736       || (external_p && TREE_CODE (d) == VAR_DECL))
16737     {
16738       /* The definition of the static data member is now required so
16739          we must substitute the initializer.  */
16740       if (TREE_CODE (d) == VAR_DECL
16741           && !DECL_INITIAL (d)
16742           && DECL_INITIAL (code_pattern))
16743         {
16744           tree ns;
16745           tree init;
16746
16747           ns = decl_namespace_context (d);
16748           push_nested_namespace (ns);
16749           push_nested_class (DECL_CONTEXT (d));
16750           init = tsubst_expr (DECL_INITIAL (code_pattern),
16751                               args,
16752                               tf_warning_or_error, NULL_TREE,
16753                               /*integral_constant_expression_p=*/false);
16754           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16755                           /*asmspec_tree=*/NULL_TREE,
16756                           LOOKUP_ONLYCONVERTING);
16757           pop_nested_class ();
16758           pop_nested_namespace (ns);
16759         }
16760
16761       /* We restore the source position here because it's used by
16762          add_pending_template.  */
16763       input_location = saved_loc;
16764
16765       if (at_eof && !pattern_defined
16766           && DECL_EXPLICIT_INSTANTIATION (d)
16767           && DECL_NOT_REALLY_EXTERN (d))
16768         /* [temp.explicit]
16769
16770            The definition of a non-exported function template, a
16771            non-exported member function template, or a non-exported
16772            member function or static data member of a class template
16773            shall be present in every translation unit in which it is
16774            explicitly instantiated.  */
16775         permerror (input_location,  "explicit instantiation of %qD "
16776                    "but no definition available", d);
16777
16778       /* ??? Historically, we have instantiated inline functions, even
16779          when marked as "extern template".  */
16780       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16781         add_pending_template (d);
16782       goto out;
16783     }
16784   /* Tell the repository that D is available in this translation unit
16785      -- and see if it is supposed to be instantiated here.  */
16786   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16787     {
16788       /* In a PCH file, despite the fact that the repository hasn't
16789          requested instantiation in the PCH it is still possible that
16790          an instantiation will be required in a file that includes the
16791          PCH.  */
16792       if (pch_file)
16793         add_pending_template (d);
16794       /* Instantiate inline functions so that the inliner can do its
16795          job, even though we'll not be emitting a copy of this
16796          function.  */
16797       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16798         goto out;
16799     }
16800
16801   need_push = !cfun || !global_bindings_p ();
16802   if (need_push)
16803     push_to_top_level ();
16804
16805   /* Mark D as instantiated so that recursive calls to
16806      instantiate_decl do not try to instantiate it again.  */
16807   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16808
16809   /* Regenerate the declaration in case the template has been modified
16810      by a subsequent redeclaration.  */
16811   regenerate_decl_from_template (d, td);
16812
16813   /* We already set the file and line above.  Reset them now in case
16814      they changed as a result of calling regenerate_decl_from_template.  */
16815   input_location = DECL_SOURCE_LOCATION (d);
16816
16817   if (TREE_CODE (d) == VAR_DECL)
16818     {
16819       tree init;
16820
16821       /* Clear out DECL_RTL; whatever was there before may not be right
16822          since we've reset the type of the declaration.  */
16823       SET_DECL_RTL (d, NULL_RTX);
16824       DECL_IN_AGGR_P (d) = 0;
16825
16826       /* The initializer is placed in DECL_INITIAL by
16827          regenerate_decl_from_template.  Pull it out so that
16828          cp_finish_decl can process it.  */
16829       init = DECL_INITIAL (d);
16830       DECL_INITIAL (d) = NULL_TREE;
16831       DECL_INITIALIZED_P (d) = 0;
16832
16833       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16834          initializer.  That function will defer actual emission until
16835          we have a chance to determine linkage.  */
16836       DECL_EXTERNAL (d) = 0;
16837
16838       /* Enter the scope of D so that access-checking works correctly.  */
16839       push_nested_class (DECL_CONTEXT (d));
16840       cp_finish_decl (d, init, false, NULL_TREE, 0);
16841       pop_nested_class ();
16842     }
16843   else if (TREE_CODE (d) == FUNCTION_DECL)
16844     {
16845       htab_t saved_local_specializations;
16846       tree subst_decl;
16847       tree tmpl_parm;
16848       tree spec_parm;
16849
16850       /* Save away the current list, in case we are instantiating one
16851          template from within the body of another.  */
16852       saved_local_specializations = local_specializations;
16853
16854       /* Set up the list of local specializations.  */
16855       local_specializations = htab_create (37,
16856                                            hash_local_specialization,
16857                                            eq_local_specializations,
16858                                            NULL);
16859
16860       /* Set up context.  */
16861       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16862
16863       /* Create substitution entries for the parameters.  */
16864       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16865       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16866       spec_parm = DECL_ARGUMENTS (d);
16867       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16868         {
16869           register_local_specialization (spec_parm, tmpl_parm);
16870           spec_parm = skip_artificial_parms_for (d, spec_parm);
16871           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16872         }
16873       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16874         {
16875           register_local_specialization (spec_parm, tmpl_parm);
16876           tmpl_parm = TREE_CHAIN (tmpl_parm);
16877           spec_parm = TREE_CHAIN (spec_parm);
16878         }
16879       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16880         {
16881           /* Register the (value) argument pack as a specialization of
16882              TMPL_PARM, then move on.  */
16883           tree argpack = make_fnparm_pack (spec_parm);
16884           register_local_specialization (argpack, tmpl_parm);
16885           tmpl_parm = TREE_CHAIN (tmpl_parm);
16886           spec_parm = NULL_TREE;
16887         }
16888       gcc_assert (!spec_parm);
16889
16890       /* Substitute into the body of the function.  */
16891       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16892                    tf_warning_or_error, tmpl,
16893                    /*integral_constant_expression_p=*/false);
16894
16895       /* Set the current input_location to the end of the function
16896          so that finish_function knows where we are.  */
16897       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16898
16899       /* We don't need the local specializations any more.  */
16900       htab_delete (local_specializations);
16901       local_specializations = saved_local_specializations;
16902
16903       /* Finish the function.  */
16904       d = finish_function (0);
16905       expand_or_defer_fn (d);
16906     }
16907
16908   /* We're not deferring instantiation any more.  */
16909   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16910
16911   if (need_push)
16912     pop_from_top_level ();
16913
16914 out:
16915   input_location = saved_loc;
16916   pop_deferring_access_checks ();
16917   pop_tinst_level ();
16918
16919   timevar_pop (TV_PARSE);
16920
16921   return d;
16922 }
16923
16924 /* Run through the list of templates that we wish we could
16925    instantiate, and instantiate any we can.  RETRIES is the
16926    number of times we retry pending template instantiation.  */
16927
16928 void
16929 instantiate_pending_templates (int retries)
16930 {
16931   int reconsider;
16932   location_t saved_loc = input_location;
16933
16934   /* Instantiating templates may trigger vtable generation.  This in turn
16935      may require further template instantiations.  We place a limit here
16936      to avoid infinite loop.  */
16937   if (pending_templates && retries >= max_tinst_depth)
16938     {
16939       tree decl = pending_templates->tinst->decl;
16940
16941       error ("template instantiation depth exceeds maximum of %d"
16942              " instantiating %q+D, possibly from virtual table generation"
16943              " (use -ftemplate-depth= to increase the maximum)",
16944              max_tinst_depth, decl);
16945       if (TREE_CODE (decl) == FUNCTION_DECL)
16946         /* Pretend that we defined it.  */
16947         DECL_INITIAL (decl) = error_mark_node;
16948       return;
16949     }
16950
16951   do
16952     {
16953       struct pending_template **t = &pending_templates;
16954       struct pending_template *last = NULL;
16955       reconsider = 0;
16956       while (*t)
16957         {
16958           tree instantiation = reopen_tinst_level ((*t)->tinst);
16959           bool complete = false;
16960
16961           if (TYPE_P (instantiation))
16962             {
16963               tree fn;
16964
16965               if (!COMPLETE_TYPE_P (instantiation))
16966                 {
16967                   instantiate_class_template (instantiation);
16968                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16969                     for (fn = TYPE_METHODS (instantiation);
16970                          fn;
16971                          fn = TREE_CHAIN (fn))
16972                       if (! DECL_ARTIFICIAL (fn))
16973                         instantiate_decl (fn,
16974                                           /*defer_ok=*/0,
16975                                           /*expl_inst_class_mem_p=*/false);
16976                   if (COMPLETE_TYPE_P (instantiation))
16977                     reconsider = 1;
16978                 }
16979
16980               complete = COMPLETE_TYPE_P (instantiation);
16981             }
16982           else
16983             {
16984               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16985                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16986                 {
16987                   instantiation
16988                     = instantiate_decl (instantiation,
16989                                         /*defer_ok=*/0,
16990                                         /*expl_inst_class_mem_p=*/false);
16991                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16992                     reconsider = 1;
16993                 }
16994
16995               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16996                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16997             }
16998
16999           if (complete)
17000             /* If INSTANTIATION has been instantiated, then we don't
17001                need to consider it again in the future.  */
17002             *t = (*t)->next;
17003           else
17004             {
17005               last = *t;
17006               t = &(*t)->next;
17007             }
17008           tinst_depth = 0;
17009           current_tinst_level = NULL;
17010         }
17011       last_pending_template = last;
17012     }
17013   while (reconsider);
17014
17015   input_location = saved_loc;
17016 }
17017
17018 /* Substitute ARGVEC into T, which is a list of initializers for
17019    either base class or a non-static data member.  The TREE_PURPOSEs
17020    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17021    instantiate_decl.  */
17022
17023 static tree
17024 tsubst_initializer_list (tree t, tree argvec)
17025 {
17026   tree inits = NULL_TREE;
17027
17028   for (; t; t = TREE_CHAIN (t))
17029     {
17030       tree decl;
17031       tree init;
17032       tree expanded_bases = NULL_TREE;
17033       tree expanded_arguments = NULL_TREE;
17034       int i, len = 1;
17035
17036       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17037         {
17038           tree expr;
17039           tree arg;
17040
17041           /* Expand the base class expansion type into separate base
17042              classes.  */
17043           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17044                                                  tf_warning_or_error,
17045                                                  NULL_TREE);
17046           if (expanded_bases == error_mark_node)
17047             continue;
17048           
17049           /* We'll be building separate TREE_LISTs of arguments for
17050              each base.  */
17051           len = TREE_VEC_LENGTH (expanded_bases);
17052           expanded_arguments = make_tree_vec (len);
17053           for (i = 0; i < len; i++)
17054             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17055
17056           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17057              expand each argument in the TREE_VALUE of t.  */
17058           expr = make_node (EXPR_PACK_EXPANSION);
17059           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17060             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17061
17062           if (TREE_VALUE (t) == void_type_node)
17063             /* VOID_TYPE_NODE is used to indicate
17064                value-initialization.  */
17065             {
17066               for (i = 0; i < len; i++)
17067                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17068             }
17069           else
17070             {
17071               /* Substitute parameter packs into each argument in the
17072                  TREE_LIST.  */
17073               in_base_initializer = 1;
17074               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17075                 {
17076                   tree expanded_exprs;
17077
17078                   /* Expand the argument.  */
17079                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17080                   expanded_exprs 
17081                     = tsubst_pack_expansion (expr, argvec,
17082                                              tf_warning_or_error,
17083                                              NULL_TREE);
17084                   if (expanded_exprs == error_mark_node)
17085                     continue;
17086
17087                   /* Prepend each of the expanded expressions to the
17088                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17089                   for (i = 0; i < len; i++)
17090                     {
17091                       TREE_VEC_ELT (expanded_arguments, i) = 
17092                         tree_cons (NULL_TREE, 
17093                                    TREE_VEC_ELT (expanded_exprs, i),
17094                                    TREE_VEC_ELT (expanded_arguments, i));
17095                     }
17096                 }
17097               in_base_initializer = 0;
17098
17099               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17100                  since we built them backwards.  */
17101               for (i = 0; i < len; i++)
17102                 {
17103                   TREE_VEC_ELT (expanded_arguments, i) = 
17104                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17105                 }
17106             }
17107         }
17108
17109       for (i = 0; i < len; ++i)
17110         {
17111           if (expanded_bases)
17112             {
17113               decl = TREE_VEC_ELT (expanded_bases, i);
17114               decl = expand_member_init (decl);
17115               init = TREE_VEC_ELT (expanded_arguments, i);
17116             }
17117           else
17118             {
17119               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17120                                   tf_warning_or_error, NULL_TREE);
17121
17122               decl = expand_member_init (decl);
17123               if (decl && !DECL_P (decl))
17124                 in_base_initializer = 1;
17125
17126               init = tsubst_expr (TREE_VALUE (t), argvec, 
17127                                   tf_warning_or_error, NULL_TREE,
17128                                   /*integral_constant_expression_p=*/false);
17129               in_base_initializer = 0;
17130             }
17131
17132           if (decl)
17133             {
17134               init = build_tree_list (decl, init);
17135               TREE_CHAIN (init) = inits;
17136               inits = init;
17137             }
17138         }
17139     }
17140   return inits;
17141 }
17142
17143 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17144
17145 static void
17146 set_current_access_from_decl (tree decl)
17147 {
17148   if (TREE_PRIVATE (decl))
17149     current_access_specifier = access_private_node;
17150   else if (TREE_PROTECTED (decl))
17151     current_access_specifier = access_protected_node;
17152   else
17153     current_access_specifier = access_public_node;
17154 }
17155
17156 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17157    is the instantiation (which should have been created with
17158    start_enum) and ARGS are the template arguments to use.  */
17159
17160 static void
17161 tsubst_enum (tree tag, tree newtag, tree args)
17162 {
17163   tree e;
17164
17165   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17166     {
17167       tree value;
17168       tree decl;
17169
17170       decl = TREE_VALUE (e);
17171       /* Note that in a template enum, the TREE_VALUE is the
17172          CONST_DECL, not the corresponding INTEGER_CST.  */
17173       value = tsubst_expr (DECL_INITIAL (decl),
17174                            args, tf_warning_or_error, NULL_TREE,
17175                            /*integral_constant_expression_p=*/true);
17176
17177       /* Give this enumeration constant the correct access.  */
17178       set_current_access_from_decl (decl);
17179
17180       /* Actually build the enumerator itself.  */
17181       build_enumerator (DECL_NAME (decl), value, newtag);
17182     }
17183
17184   finish_enum (newtag);
17185   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17186     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17187 }
17188
17189 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17190    its type -- but without substituting the innermost set of template
17191    arguments.  So, innermost set of template parameters will appear in
17192    the type.  */
17193
17194 tree
17195 get_mostly_instantiated_function_type (tree decl)
17196 {
17197   tree fn_type;
17198   tree tmpl;
17199   tree targs;
17200   tree tparms;
17201   int parm_depth;
17202
17203   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17204   targs = DECL_TI_ARGS (decl);
17205   tparms = DECL_TEMPLATE_PARMS (tmpl);
17206   parm_depth = TMPL_PARMS_DEPTH (tparms);
17207
17208   /* There should be as many levels of arguments as there are levels
17209      of parameters.  */
17210   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17211
17212   fn_type = TREE_TYPE (tmpl);
17213
17214   if (parm_depth == 1)
17215     /* No substitution is necessary.  */
17216     ;
17217   else
17218     {
17219       int i, save_access_control;
17220       tree partial_args;
17221
17222       /* Replace the innermost level of the TARGS with NULL_TREEs to
17223          let tsubst know not to substitute for those parameters.  */
17224       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17225       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17226         SET_TMPL_ARGS_LEVEL (partial_args, i,
17227                              TMPL_ARGS_LEVEL (targs, i));
17228       SET_TMPL_ARGS_LEVEL (partial_args,
17229                            TMPL_ARGS_DEPTH (targs),
17230                            make_tree_vec (DECL_NTPARMS (tmpl)));
17231
17232       /* Disable access control as this function is used only during
17233          name-mangling.  */
17234       save_access_control = flag_access_control;
17235       flag_access_control = 0;
17236
17237       ++processing_template_decl;
17238       /* Now, do the (partial) substitution to figure out the
17239          appropriate function type.  */
17240       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17241       --processing_template_decl;
17242
17243       /* Substitute into the template parameters to obtain the real
17244          innermost set of parameters.  This step is important if the
17245          innermost set of template parameters contains value
17246          parameters whose types depend on outer template parameters.  */
17247       TREE_VEC_LENGTH (partial_args)--;
17248       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17249
17250       flag_access_control = save_access_control;
17251     }
17252
17253   return fn_type;
17254 }
17255
17256 /* Return truthvalue if we're processing a template different from
17257    the last one involved in diagnostics.  */
17258 int
17259 problematic_instantiation_changed (void)
17260 {
17261   return last_template_error_tick != tinst_level_tick;
17262 }
17263
17264 /* Remember current template involved in diagnostics.  */
17265 void
17266 record_last_problematic_instantiation (void)
17267 {
17268   last_template_error_tick = tinst_level_tick;
17269 }
17270
17271 struct tinst_level *
17272 current_instantiation (void)
17273 {
17274   return current_tinst_level;
17275 }
17276
17277 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17278    type. Return zero for ok, nonzero for disallowed. Issue error and
17279    warning messages under control of COMPLAIN.  */
17280
17281 static int
17282 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17283 {
17284   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17285     return 0;
17286   else if (POINTER_TYPE_P (type))
17287     return 0;
17288   else if (TYPE_PTR_TO_MEMBER_P (type))
17289     return 0;
17290   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17291     return 0;
17292   else if (TREE_CODE (type) == TYPENAME_TYPE)
17293     return 0;
17294
17295   if (complain & tf_error)
17296     error ("%q#T is not a valid type for a template constant parameter", type);
17297   return 1;
17298 }
17299
17300 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17301    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17302
17303 static bool
17304 dependent_type_p_r (tree type)
17305 {
17306   tree scope;
17307
17308   /* [temp.dep.type]
17309
17310      A type is dependent if it is:
17311
17312      -- a template parameter. Template template parameters are types
17313         for us (since TYPE_P holds true for them) so we handle
17314         them here.  */
17315   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17316       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17317     return true;
17318   /* -- a qualified-id with a nested-name-specifier which contains a
17319         class-name that names a dependent type or whose unqualified-id
17320         names a dependent type.  */
17321   if (TREE_CODE (type) == TYPENAME_TYPE)
17322     return true;
17323   /* -- a cv-qualified type where the cv-unqualified type is
17324         dependent.  */
17325   type = TYPE_MAIN_VARIANT (type);
17326   /* -- a compound type constructed from any dependent type.  */
17327   if (TYPE_PTR_TO_MEMBER_P (type))
17328     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17329             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17330                                            (type)));
17331   else if (TREE_CODE (type) == POINTER_TYPE
17332            || TREE_CODE (type) == REFERENCE_TYPE)
17333     return dependent_type_p (TREE_TYPE (type));
17334   else if (TREE_CODE (type) == FUNCTION_TYPE
17335            || TREE_CODE (type) == METHOD_TYPE)
17336     {
17337       tree arg_type;
17338
17339       if (dependent_type_p (TREE_TYPE (type)))
17340         return true;
17341       for (arg_type = TYPE_ARG_TYPES (type);
17342            arg_type;
17343            arg_type = TREE_CHAIN (arg_type))
17344         if (dependent_type_p (TREE_VALUE (arg_type)))
17345           return true;
17346       return false;
17347     }
17348   /* -- an array type constructed from any dependent type or whose
17349         size is specified by a constant expression that is
17350         value-dependent.  */
17351   if (TREE_CODE (type) == ARRAY_TYPE)
17352     {
17353       if (TYPE_DOMAIN (type)
17354           && dependent_type_p (TYPE_DOMAIN (type)))
17355         return true;
17356       return dependent_type_p (TREE_TYPE (type));
17357     }
17358   else if (TREE_CODE (type) == INTEGER_TYPE
17359            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17360     {
17361       /* If this is the TYPE_DOMAIN of an array type, consider it
17362          dependent.  We already checked for value-dependence in
17363          compute_array_index_type.  */
17364       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17365     }
17366
17367   /* -- a template-id in which either the template name is a template
17368      parameter ...  */
17369   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17370     return true;
17371   /* ... or any of the template arguments is a dependent type or
17372         an expression that is type-dependent or value-dependent.  */
17373   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17374            && (any_dependent_template_arguments_p
17375                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17376     return true;
17377
17378   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17379      argument of the `typeof' expression is not type-dependent, then
17380      it should already been have resolved.  */
17381   if (TREE_CODE (type) == TYPEOF_TYPE
17382       || TREE_CODE (type) == DECLTYPE_TYPE)
17383     return true;
17384
17385   /* A template argument pack is dependent if any of its packed
17386      arguments are.  */
17387   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17388     {
17389       tree args = ARGUMENT_PACK_ARGS (type);
17390       int i, len = TREE_VEC_LENGTH (args);
17391       for (i = 0; i < len; ++i)
17392         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17393           return true;
17394     }
17395
17396   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17397      be template parameters.  */
17398   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17399     return true;
17400
17401   /* The standard does not specifically mention types that are local
17402      to template functions or local classes, but they should be
17403      considered dependent too.  For example:
17404
17405        template <int I> void f() {
17406          enum E { a = I };
17407          S<sizeof (E)> s;
17408        }
17409
17410      The size of `E' cannot be known until the value of `I' has been
17411      determined.  Therefore, `E' must be considered dependent.  */
17412   scope = TYPE_CONTEXT (type);
17413   if (scope && TYPE_P (scope))
17414     return dependent_type_p (scope);
17415   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17416     return type_dependent_expression_p (scope);
17417
17418   /* Other types are non-dependent.  */
17419   return false;
17420 }
17421
17422 /* Returns TRUE if TYPE is dependent, in the sense of
17423    [temp.dep.type].  */
17424
17425 bool
17426 dependent_type_p (tree type)
17427 {
17428   /* If there are no template parameters in scope, then there can't be
17429      any dependent types.  */
17430   if (!processing_template_decl)
17431     {
17432       /* If we are not processing a template, then nobody should be
17433          providing us with a dependent type.  */
17434       gcc_assert (type);
17435       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17436       return false;
17437     }
17438
17439   /* If the type is NULL, we have not computed a type for the entity
17440      in question; in that case, the type is dependent.  */
17441   if (!type)
17442     return true;
17443
17444   /* Erroneous types can be considered non-dependent.  */
17445   if (type == error_mark_node)
17446     return false;
17447
17448   /* If we have not already computed the appropriate value for TYPE,
17449      do so now.  */
17450   if (!TYPE_DEPENDENT_P_VALID (type))
17451     {
17452       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17453       TYPE_DEPENDENT_P_VALID (type) = 1;
17454     }
17455
17456   return TYPE_DEPENDENT_P (type);
17457 }
17458
17459 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17460    lookup.  In other words, a dependent type that is not the current
17461    instantiation.  */
17462
17463 bool
17464 dependent_scope_p (tree scope)
17465 {
17466   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17467           && !currently_open_class (scope));
17468 }
17469
17470 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17471
17472 static bool
17473 dependent_scope_ref_p (tree expression, bool criterion (tree))
17474 {
17475   tree scope;
17476   tree name;
17477
17478   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17479
17480   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17481     return true;
17482
17483   scope = TREE_OPERAND (expression, 0);
17484   name = TREE_OPERAND (expression, 1);
17485
17486   /* [temp.dep.expr]
17487
17488      An id-expression is type-dependent if it contains a
17489      nested-name-specifier that contains a class-name that names a
17490      dependent type.  */
17491   /* The suggested resolution to Core Issue 224 implies that if the
17492      qualifying type is the current class, then we must peek
17493      inside it.  */
17494   if (DECL_P (name)
17495       && currently_open_class (scope)
17496       && !criterion (name))
17497     return false;
17498   if (dependent_type_p (scope))
17499     return true;
17500
17501   return false;
17502 }
17503
17504 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17505    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17506    expression.  */
17507
17508 bool
17509 value_dependent_expression_p (tree expression)
17510 {
17511   if (!processing_template_decl)
17512     return false;
17513
17514   /* A name declared with a dependent type.  */
17515   if (DECL_P (expression) && type_dependent_expression_p (expression))
17516     return true;
17517
17518   switch (TREE_CODE (expression))
17519     {
17520     case IDENTIFIER_NODE:
17521       /* A name that has not been looked up -- must be dependent.  */
17522       return true;
17523
17524     case TEMPLATE_PARM_INDEX:
17525       /* A non-type template parm.  */
17526       return true;
17527
17528     case CONST_DECL:
17529       /* A non-type template parm.  */
17530       if (DECL_TEMPLATE_PARM_P (expression))
17531         return true;
17532       return value_dependent_expression_p (DECL_INITIAL (expression));
17533
17534     case VAR_DECL:
17535        /* A constant with integral or enumeration type and is initialized
17536           with an expression that is value-dependent.  */
17537       if (DECL_INITIAL (expression)
17538           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17539           && value_dependent_expression_p (DECL_INITIAL (expression)))
17540         return true;
17541       return false;
17542
17543     case DYNAMIC_CAST_EXPR:
17544     case STATIC_CAST_EXPR:
17545     case CONST_CAST_EXPR:
17546     case REINTERPRET_CAST_EXPR:
17547     case CAST_EXPR:
17548       /* These expressions are value-dependent if the type to which
17549          the cast occurs is dependent or the expression being casted
17550          is value-dependent.  */
17551       {
17552         tree type = TREE_TYPE (expression);
17553
17554         if (dependent_type_p (type))
17555           return true;
17556
17557         /* A functional cast has a list of operands.  */
17558         expression = TREE_OPERAND (expression, 0);
17559         if (!expression)
17560           {
17561             /* If there are no operands, it must be an expression such
17562                as "int()". This should not happen for aggregate types
17563                because it would form non-constant expressions.  */
17564             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17565
17566             return false;
17567           }
17568
17569         if (TREE_CODE (expression) == TREE_LIST)
17570           return any_value_dependent_elements_p (expression);
17571
17572         return value_dependent_expression_p (expression);
17573       }
17574
17575     case SIZEOF_EXPR:
17576     case ALIGNOF_EXPR:
17577       /* A `sizeof' expression is value-dependent if the operand is
17578          type-dependent or is a pack expansion.  */
17579       expression = TREE_OPERAND (expression, 0);
17580       if (PACK_EXPANSION_P (expression))
17581         return true;
17582       else if (TYPE_P (expression))
17583         return dependent_type_p (expression);
17584       return type_dependent_expression_p (expression);
17585
17586     case SCOPE_REF:
17587       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17588
17589     case COMPONENT_REF:
17590       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17591               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17592
17593     case CALL_EXPR:
17594       /* A CALL_EXPR may appear in a constant expression if it is a
17595          call to a builtin function, e.g., __builtin_constant_p.  All
17596          such calls are value-dependent.  */
17597       return true;
17598
17599     case NONTYPE_ARGUMENT_PACK:
17600       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17601          is value-dependent.  */
17602       {
17603         tree values = ARGUMENT_PACK_ARGS (expression);
17604         int i, len = TREE_VEC_LENGTH (values);
17605         
17606         for (i = 0; i < len; ++i)
17607           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17608             return true;
17609         
17610         return false;
17611       }
17612
17613     case TRAIT_EXPR:
17614       {
17615         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17616         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17617                 || (type2 ? dependent_type_p (type2) : false));
17618       }
17619
17620     case MODOP_EXPR:
17621       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17622               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17623
17624     default:
17625       /* A constant expression is value-dependent if any subexpression is
17626          value-dependent.  */
17627       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17628         {
17629         case tcc_reference:
17630         case tcc_unary:
17631           return (value_dependent_expression_p
17632                   (TREE_OPERAND (expression, 0)));
17633
17634         case tcc_comparison:
17635         case tcc_binary:
17636           return ((value_dependent_expression_p
17637                    (TREE_OPERAND (expression, 0)))
17638                   || (value_dependent_expression_p
17639                       (TREE_OPERAND (expression, 1))));
17640
17641         case tcc_expression:
17642         case tcc_vl_exp:
17643           {
17644             int i;
17645             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17646               /* In some cases, some of the operands may be missing.
17647                  (For example, in the case of PREDECREMENT_EXPR, the
17648                  amount to increment by may be missing.)  That doesn't
17649                  make the expression dependent.  */
17650               if (TREE_OPERAND (expression, i)
17651                   && (value_dependent_expression_p
17652                       (TREE_OPERAND (expression, i))))
17653                 return true;
17654             return false;
17655           }
17656
17657         default:
17658           break;
17659         }
17660     }
17661
17662   /* The expression is not value-dependent.  */
17663   return false;
17664 }
17665
17666 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17667    [temp.dep.expr].  */
17668
17669 bool
17670 type_dependent_expression_p (tree expression)
17671 {
17672   if (!processing_template_decl)
17673     return false;
17674
17675   if (expression == error_mark_node)
17676     return false;
17677
17678   /* An unresolved name is always dependent.  */
17679   if (TREE_CODE (expression) == IDENTIFIER_NODE
17680       || TREE_CODE (expression) == USING_DECL)
17681     return true;
17682
17683   /* Some expression forms are never type-dependent.  */
17684   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17685       || TREE_CODE (expression) == SIZEOF_EXPR
17686       || TREE_CODE (expression) == ALIGNOF_EXPR
17687       || TREE_CODE (expression) == TRAIT_EXPR
17688       || TREE_CODE (expression) == TYPEID_EXPR
17689       || TREE_CODE (expression) == DELETE_EXPR
17690       || TREE_CODE (expression) == VEC_DELETE_EXPR
17691       || TREE_CODE (expression) == THROW_EXPR)
17692     return false;
17693
17694   /* The types of these expressions depends only on the type to which
17695      the cast occurs.  */
17696   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17697       || TREE_CODE (expression) == STATIC_CAST_EXPR
17698       || TREE_CODE (expression) == CONST_CAST_EXPR
17699       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17700       || TREE_CODE (expression) == CAST_EXPR)
17701     return dependent_type_p (TREE_TYPE (expression));
17702
17703   /* The types of these expressions depends only on the type created
17704      by the expression.  */
17705   if (TREE_CODE (expression) == NEW_EXPR
17706       || TREE_CODE (expression) == VEC_NEW_EXPR)
17707     {
17708       /* For NEW_EXPR tree nodes created inside a template, either
17709          the object type itself or a TREE_LIST may appear as the
17710          operand 1.  */
17711       tree type = TREE_OPERAND (expression, 1);
17712       if (TREE_CODE (type) == TREE_LIST)
17713         /* This is an array type.  We need to check array dimensions
17714            as well.  */
17715         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17716                || value_dependent_expression_p
17717                     (TREE_OPERAND (TREE_VALUE (type), 1));
17718       else
17719         return dependent_type_p (type);
17720     }
17721
17722   if (TREE_CODE (expression) == SCOPE_REF
17723       && dependent_scope_ref_p (expression,
17724                                 type_dependent_expression_p))
17725     return true;
17726
17727   if (TREE_CODE (expression) == FUNCTION_DECL
17728       && DECL_LANG_SPECIFIC (expression)
17729       && DECL_TEMPLATE_INFO (expression)
17730       && (any_dependent_template_arguments_p
17731           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17732     return true;
17733
17734   if (TREE_CODE (expression) == TEMPLATE_DECL
17735       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17736     return false;
17737
17738   if (TREE_CODE (expression) == STMT_EXPR)
17739     expression = stmt_expr_value_expr (expression);
17740
17741   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17742     {
17743       tree elt;
17744       unsigned i;
17745
17746       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17747         {
17748           if (type_dependent_expression_p (elt))
17749             return true;
17750         }
17751       return false;
17752     }
17753
17754   /* A static data member of the current instantiation with incomplete
17755      array type is type-dependent, as the definition and specializations
17756      can have different bounds.  */
17757   if (TREE_CODE (expression) == VAR_DECL
17758       && DECL_CLASS_SCOPE_P (expression)
17759       && dependent_type_p (DECL_CONTEXT (expression))
17760       && VAR_HAD_UNKNOWN_BOUND (expression))
17761     return true;
17762
17763   if (TREE_TYPE (expression) == unknown_type_node)
17764     {
17765       if (TREE_CODE (expression) == ADDR_EXPR)
17766         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17767       if (TREE_CODE (expression) == COMPONENT_REF
17768           || TREE_CODE (expression) == OFFSET_REF)
17769         {
17770           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17771             return true;
17772           expression = TREE_OPERAND (expression, 1);
17773           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17774             return false;
17775         }
17776       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17777       if (TREE_CODE (expression) == SCOPE_REF)
17778         return false;
17779
17780       if (TREE_CODE (expression) == BASELINK)
17781         expression = BASELINK_FUNCTIONS (expression);
17782
17783       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17784         {
17785           if (any_dependent_template_arguments_p
17786               (TREE_OPERAND (expression, 1)))
17787             return true;
17788           expression = TREE_OPERAND (expression, 0);
17789         }
17790       gcc_assert (TREE_CODE (expression) == OVERLOAD
17791                   || TREE_CODE (expression) == FUNCTION_DECL);
17792
17793       while (expression)
17794         {
17795           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17796             return true;
17797           expression = OVL_NEXT (expression);
17798         }
17799       return false;
17800     }
17801
17802   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17803
17804   return (dependent_type_p (TREE_TYPE (expression)));
17805 }
17806
17807 /* Like type_dependent_expression_p, but it also works while not processing
17808    a template definition, i.e. during substitution or mangling.  */
17809
17810 bool
17811 type_dependent_expression_p_push (tree expr)
17812 {
17813   bool b;
17814   ++processing_template_decl;
17815   b = type_dependent_expression_p (expr);
17816   --processing_template_decl;
17817   return b;
17818 }
17819
17820 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17821
17822 bool
17823 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17824 {
17825   unsigned int i;
17826   tree arg;
17827
17828   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17829     {
17830       if (type_dependent_expression_p (arg))
17831         return true;
17832     }
17833   return false;
17834 }
17835
17836 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17837    expressions) contains any value-dependent expressions.  */
17838
17839 bool
17840 any_value_dependent_elements_p (const_tree list)
17841 {
17842   for (; list; list = TREE_CHAIN (list))
17843     if (value_dependent_expression_p (TREE_VALUE (list)))
17844       return true;
17845
17846   return false;
17847 }
17848
17849 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17850
17851 bool
17852 dependent_template_arg_p (tree arg)
17853 {
17854   if (!processing_template_decl)
17855     return false;
17856
17857   if (TREE_CODE (arg) == TEMPLATE_DECL
17858       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17859     return dependent_template_p (arg);
17860   else if (ARGUMENT_PACK_P (arg))
17861     {
17862       tree args = ARGUMENT_PACK_ARGS (arg);
17863       int i, len = TREE_VEC_LENGTH (args);
17864       for (i = 0; i < len; ++i)
17865         {
17866           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17867             return true;
17868         }
17869
17870       return false;
17871     }
17872   else if (TYPE_P (arg))
17873     return dependent_type_p (arg);
17874   else
17875     return (type_dependent_expression_p (arg)
17876             || value_dependent_expression_p (arg));
17877 }
17878
17879 /* Returns true if ARGS (a collection of template arguments) contains
17880    any types that require structural equality testing.  */
17881
17882 bool
17883 any_template_arguments_need_structural_equality_p (tree args)
17884 {
17885   int i;
17886   int j;
17887
17888   if (!args)
17889     return false;
17890   if (args == error_mark_node)
17891     return true;
17892
17893   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17894     {
17895       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17896       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17897         {
17898           tree arg = TREE_VEC_ELT (level, j);
17899           tree packed_args = NULL_TREE;
17900           int k, len = 1;
17901
17902           if (ARGUMENT_PACK_P (arg))
17903             {
17904               /* Look inside the argument pack.  */
17905               packed_args = ARGUMENT_PACK_ARGS (arg);
17906               len = TREE_VEC_LENGTH (packed_args);
17907             }
17908
17909           for (k = 0; k < len; ++k)
17910             {
17911               if (packed_args)
17912                 arg = TREE_VEC_ELT (packed_args, k);
17913
17914               if (error_operand_p (arg))
17915                 return true;
17916               else if (TREE_CODE (arg) == TEMPLATE_DECL
17917                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17918                 continue;
17919               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17920                 return true;
17921               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17922                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17923                 return true;
17924             }
17925         }
17926     }
17927
17928   return false;
17929 }
17930
17931 /* Returns true if ARGS (a collection of template arguments) contains
17932    any dependent arguments.  */
17933
17934 bool
17935 any_dependent_template_arguments_p (const_tree args)
17936 {
17937   int i;
17938   int j;
17939
17940   if (!args)
17941     return false;
17942   if (args == error_mark_node)
17943     return true;
17944
17945   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17946     {
17947       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17948       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17949         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17950           return true;
17951     }
17952
17953   return false;
17954 }
17955
17956 /* Returns TRUE if the template TMPL is dependent.  */
17957
17958 bool
17959 dependent_template_p (tree tmpl)
17960 {
17961   if (TREE_CODE (tmpl) == OVERLOAD)
17962     {
17963       while (tmpl)
17964         {
17965           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17966             return true;
17967           tmpl = OVL_CHAIN (tmpl);
17968         }
17969       return false;
17970     }
17971
17972   /* Template template parameters are dependent.  */
17973   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17974       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17975     return true;
17976   /* So are names that have not been looked up.  */
17977   if (TREE_CODE (tmpl) == SCOPE_REF
17978       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17979     return true;
17980   /* So are member templates of dependent classes.  */
17981   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17982     return dependent_type_p (DECL_CONTEXT (tmpl));
17983   return false;
17984 }
17985
17986 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17987
17988 bool
17989 dependent_template_id_p (tree tmpl, tree args)
17990 {
17991   return (dependent_template_p (tmpl)
17992           || any_dependent_template_arguments_p (args));
17993 }
17994
17995 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17996    is dependent.  */
17997
17998 bool
17999 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18000 {
18001   int i;
18002
18003   if (!processing_template_decl)
18004     return false;
18005
18006   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18007     {
18008       tree decl = TREE_VEC_ELT (declv, i);
18009       tree init = TREE_VEC_ELT (initv, i);
18010       tree cond = TREE_VEC_ELT (condv, i);
18011       tree incr = TREE_VEC_ELT (incrv, i);
18012
18013       if (type_dependent_expression_p (decl))
18014         return true;
18015
18016       if (init && type_dependent_expression_p (init))
18017         return true;
18018
18019       if (type_dependent_expression_p (cond))
18020         return true;
18021
18022       if (COMPARISON_CLASS_P (cond)
18023           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18024               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18025         return true;
18026
18027       if (TREE_CODE (incr) == MODOP_EXPR)
18028         {
18029           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18030               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18031             return true;
18032         }
18033       else if (type_dependent_expression_p (incr))
18034         return true;
18035       else if (TREE_CODE (incr) == MODIFY_EXPR)
18036         {
18037           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18038             return true;
18039           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18040             {
18041               tree t = TREE_OPERAND (incr, 1);
18042               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18043                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18044                 return true;
18045             }
18046         }
18047     }
18048
18049   return false;
18050 }
18051
18052 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18053    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18054    no such TYPE can be found.  Note that this function peers inside
18055    uninstantiated templates and therefore should be used only in
18056    extremely limited situations.  ONLY_CURRENT_P restricts this
18057    peering to the currently open classes hierarchy (which is required
18058    when comparing types).  */
18059
18060 tree
18061 resolve_typename_type (tree type, bool only_current_p)
18062 {
18063   tree scope;
18064   tree name;
18065   tree decl;
18066   int quals;
18067   tree pushed_scope;
18068   tree result;
18069
18070   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18071
18072   scope = TYPE_CONTEXT (type);
18073   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18074      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18075      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18076      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18077      identifier  of the TYPENAME_TYPE anymore.
18078      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18079      TYPENAME_TYPE instead, we avoid messing up with a possible
18080      typedef variant case.  */
18081   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18082
18083   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18084      it first before we can figure out what NAME refers to.  */
18085   if (TREE_CODE (scope) == TYPENAME_TYPE)
18086     scope = resolve_typename_type (scope, only_current_p);
18087   /* If we don't know what SCOPE refers to, then we cannot resolve the
18088      TYPENAME_TYPE.  */
18089   if (TREE_CODE (scope) == TYPENAME_TYPE)
18090     return type;
18091   /* If the SCOPE is a template type parameter, we have no way of
18092      resolving the name.  */
18093   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18094     return type;
18095   /* If the SCOPE is not the current instantiation, there's no reason
18096      to look inside it.  */
18097   if (only_current_p && !currently_open_class (scope))
18098     return type;
18099   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18100   if (typedef_variant_p (type))
18101     return type;
18102   /* If SCOPE isn't the template itself, it will not have a valid
18103      TYPE_FIELDS list.  */
18104   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18105     /* scope is either the template itself or a compatible instantiation
18106        like X<T>, so look up the name in the original template.  */
18107     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18108   else
18109     /* scope is a partial instantiation, so we can't do the lookup or we
18110        will lose the template arguments.  */
18111     return type;
18112   /* Enter the SCOPE so that name lookup will be resolved as if we
18113      were in the class definition.  In particular, SCOPE will no
18114      longer be considered a dependent type.  */
18115   pushed_scope = push_scope (scope);
18116   /* Look up the declaration.  */
18117   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18118
18119   result = NULL_TREE;
18120   
18121   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18122      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18123   if (!decl)
18124     /*nop*/;
18125   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18126            && TREE_CODE (decl) == TYPE_DECL)
18127     {
18128       result = TREE_TYPE (decl);
18129       if (result == error_mark_node)
18130         result = NULL_TREE;
18131     }
18132   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18133            && DECL_CLASS_TEMPLATE_P (decl))
18134     {
18135       tree tmpl;
18136       tree args;
18137       /* Obtain the template and the arguments.  */
18138       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18139       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18140       /* Instantiate the template.  */
18141       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18142                                       /*entering_scope=*/0,
18143                                       tf_error | tf_user);
18144       if (result == error_mark_node)
18145         result = NULL_TREE;
18146     }
18147   
18148   /* Leave the SCOPE.  */
18149   if (pushed_scope)
18150     pop_scope (pushed_scope);
18151
18152   /* If we failed to resolve it, return the original typename.  */
18153   if (!result)
18154     return type;
18155   
18156   /* If lookup found a typename type, resolve that too.  */
18157   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18158     {
18159       /* Ill-formed programs can cause infinite recursion here, so we
18160          must catch that.  */
18161       TYPENAME_IS_RESOLVING_P (type) = 1;
18162       result = resolve_typename_type (result, only_current_p);
18163       TYPENAME_IS_RESOLVING_P (type) = 0;
18164     }
18165   
18166   /* Qualify the resulting type.  */
18167   quals = cp_type_quals (type);
18168   if (quals)
18169     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18170
18171   return result;
18172 }
18173
18174 /* EXPR is an expression which is not type-dependent.  Return a proxy
18175    for EXPR that can be used to compute the types of larger
18176    expressions containing EXPR.  */
18177
18178 tree
18179 build_non_dependent_expr (tree expr)
18180 {
18181   tree inner_expr;
18182
18183   /* Preserve null pointer constants so that the type of things like
18184      "p == 0" where "p" is a pointer can be determined.  */
18185   if (null_ptr_cst_p (expr))
18186     return expr;
18187   /* Preserve OVERLOADs; the functions must be available to resolve
18188      types.  */
18189   inner_expr = expr;
18190   if (TREE_CODE (inner_expr) == STMT_EXPR)
18191     inner_expr = stmt_expr_value_expr (inner_expr);
18192   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18193     inner_expr = TREE_OPERAND (inner_expr, 0);
18194   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18195     inner_expr = TREE_OPERAND (inner_expr, 1);
18196   if (is_overloaded_fn (inner_expr)
18197       || TREE_CODE (inner_expr) == OFFSET_REF)
18198     return expr;
18199   /* There is no need to return a proxy for a variable.  */
18200   if (TREE_CODE (expr) == VAR_DECL)
18201     return expr;
18202   /* Preserve string constants; conversions from string constants to
18203      "char *" are allowed, even though normally a "const char *"
18204      cannot be used to initialize a "char *".  */
18205   if (TREE_CODE (expr) == STRING_CST)
18206     return expr;
18207   /* Preserve arithmetic constants, as an optimization -- there is no
18208      reason to create a new node.  */
18209   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18210     return expr;
18211   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18212      There is at least one place where we want to know that a
18213      particular expression is a throw-expression: when checking a ?:
18214      expression, there are special rules if the second or third
18215      argument is a throw-expression.  */
18216   if (TREE_CODE (expr) == THROW_EXPR)
18217     return expr;
18218
18219   if (TREE_CODE (expr) == COND_EXPR)
18220     return build3 (COND_EXPR,
18221                    TREE_TYPE (expr),
18222                    TREE_OPERAND (expr, 0),
18223                    (TREE_OPERAND (expr, 1)
18224                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18225                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18226                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18227   if (TREE_CODE (expr) == COMPOUND_EXPR
18228       && !COMPOUND_EXPR_OVERLOADED (expr))
18229     return build2 (COMPOUND_EXPR,
18230                    TREE_TYPE (expr),
18231                    TREE_OPERAND (expr, 0),
18232                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18233
18234   /* If the type is unknown, it can't really be non-dependent */
18235   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18236
18237   /* Otherwise, build a NON_DEPENDENT_EXPR.
18238
18239      REFERENCE_TYPEs are not stripped for expressions in templates
18240      because doing so would play havoc with mangling.  Consider, for
18241      example:
18242
18243        template <typename T> void f<T& g>() { g(); }
18244
18245      In the body of "f", the expression for "g" will have
18246      REFERENCE_TYPE, even though the standard says that it should
18247      not.  The reason is that we must preserve the syntactic form of
18248      the expression so that mangling (say) "f<g>" inside the body of
18249      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18250      stripped here.  */
18251   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18252 }
18253
18254 /* ARGS is a vector of expressions as arguments to a function call.
18255    Replace the arguments with equivalent non-dependent expressions.
18256    This modifies ARGS in place.  */
18257
18258 void
18259 make_args_non_dependent (VEC(tree,gc) *args)
18260 {
18261   unsigned int ix;
18262   tree arg;
18263
18264   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18265     {
18266       tree newarg = build_non_dependent_expr (arg);
18267       if (newarg != arg)
18268         VEC_replace (tree, args, ix, newarg);
18269     }
18270 }
18271
18272 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18273    with a level one deeper than the actual template parms.  */
18274
18275 tree
18276 make_auto (void)
18277 {
18278   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18279   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18280                                TYPE_DECL, get_identifier ("auto"), au);
18281   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18282   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18283     (0, processing_template_decl + 1, processing_template_decl + 1,
18284      TYPE_NAME (au), NULL_TREE);
18285   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18286   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18287   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18288
18289   return au;
18290 }
18291
18292 /* Given type ARG, return std::initializer_list<ARG>.  */
18293
18294 static tree
18295 listify (tree arg)
18296 {
18297   tree std_init_list = namespace_binding
18298     (get_identifier ("initializer_list"), std_node);
18299   tree argvec;
18300   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18301     {    
18302       error ("deducing from brace-enclosed initializer list requires "
18303              "#include <initializer_list>");
18304       return error_mark_node;
18305     }
18306   argvec = make_tree_vec (1);
18307   TREE_VEC_ELT (argvec, 0) = arg;
18308   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18309                                 NULL_TREE, 0, tf_warning_or_error);
18310 }
18311
18312 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18313
18314 static tree
18315 listify_autos (tree type, tree auto_node)
18316 {
18317   tree init_auto = listify (auto_node);
18318   tree argvec = make_tree_vec (1);
18319   TREE_VEC_ELT (argvec, 0) = init_auto;
18320   if (processing_template_decl)
18321     argvec = add_to_template_args (current_template_args (), argvec);
18322   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18323 }
18324
18325 /* walk_tree helper for do_auto_deduction.  */
18326
18327 static tree
18328 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18329                  void *type)
18330 {
18331   /* Is this a variable with the type we're looking for?  */
18332   if (DECL_P (*tp)
18333       && TREE_TYPE (*tp) == type)
18334     return *tp;
18335   else
18336     return NULL_TREE;
18337 }
18338
18339 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18340    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18341
18342 tree
18343 do_auto_deduction (tree type, tree init, tree auto_node)
18344 {
18345   tree parms, tparms, targs;
18346   tree args[1];
18347   tree decl;
18348   int val;
18349
18350   /* The name of the object being declared shall not appear in the
18351      initializer expression.  */
18352   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18353   if (decl)
18354     {
18355       error ("variable %q#D with %<auto%> type used in its own "
18356              "initializer", decl);
18357       return error_mark_node;
18358     }
18359
18360   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18361      with either a new invented type template parameter U or, if the
18362      initializer is a braced-init-list (8.5.4), with
18363      std::initializer_list<U>.  */
18364   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18365     type = listify_autos (type, auto_node);
18366
18367   parms = build_tree_list (NULL_TREE, type);
18368   args[0] = init;
18369   tparms = make_tree_vec (1);
18370   targs = make_tree_vec (1);
18371   TREE_VEC_ELT (tparms, 0)
18372     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18373   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18374                                DEDUCE_CALL, LOOKUP_NORMAL);
18375   if (val > 0)
18376     {
18377       error ("unable to deduce %qT from %qE", type, init);
18378       return error_mark_node;
18379     }
18380
18381   /* If the list of declarators contains more than one declarator, the type
18382      of each declared variable is determined as described above. If the
18383      type deduced for the template parameter U is not the same in each
18384      deduction, the program is ill-formed.  */
18385   if (TREE_TYPE (auto_node)
18386       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18387     {
18388       error ("inconsistent deduction for %qT: %qT and then %qT",
18389              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18390       return error_mark_node;
18391     }
18392   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18393
18394   if (processing_template_decl)
18395     targs = add_to_template_args (current_template_args (), targs);
18396   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18397 }
18398
18399 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18400    result.  */
18401
18402 tree
18403 splice_late_return_type (tree type, tree late_return_type)
18404 {
18405   tree argvec;
18406
18407   if (late_return_type == NULL_TREE)
18408     return type;
18409   argvec = make_tree_vec (1);
18410   TREE_VEC_ELT (argvec, 0) = late_return_type;
18411   if (processing_template_decl)
18412     argvec = add_to_template_args (current_template_args (), argvec);
18413   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18414 }
18415
18416 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18417
18418 bool
18419 is_auto (const_tree type)
18420 {
18421   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18422       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18423     return true;
18424   else
18425     return false;
18426 }
18427
18428 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18429    appear as a type-specifier for the declaration in question, we don't
18430    have to look through the whole type.  */
18431
18432 tree
18433 type_uses_auto (tree type)
18434 {
18435   enum tree_code code;
18436   if (is_auto (type))
18437     return type;
18438
18439   code = TREE_CODE (type);
18440
18441   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18442       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18443       || code == METHOD_TYPE || code == ARRAY_TYPE)
18444     return type_uses_auto (TREE_TYPE (type));
18445
18446   if (TYPE_PTRMEMFUNC_P (type))
18447     return type_uses_auto (TREE_TYPE (TREE_TYPE
18448                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18449
18450   return NULL_TREE;
18451 }
18452
18453 /* For a given template T, return the vector of typedefs referenced
18454    in T for which access check is needed at T instantiation time.
18455    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18456    Those typedefs were added to T by the function
18457    append_type_to_template_for_access_check.  */
18458
18459 VEC(qualified_typedef_usage_t,gc)*
18460 get_types_needing_access_check (tree t)
18461 {
18462   tree ti;
18463   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18464
18465   if (!t || t == error_mark_node)
18466     return NULL;
18467
18468   if (!(ti = get_template_info (t)))
18469     return NULL;
18470
18471   if (CLASS_TYPE_P (t)
18472       || TREE_CODE (t) == FUNCTION_DECL)
18473     {
18474       if (!TI_TEMPLATE (ti))
18475         return NULL;
18476
18477       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18478     }
18479
18480   return result;
18481 }
18482
18483 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18484    tied to T. That list of typedefs will be access checked at
18485    T instantiation time.
18486    T is either a FUNCTION_DECL or a RECORD_TYPE.
18487    TYPE_DECL is a TYPE_DECL node representing a typedef.
18488    SCOPE is the scope through which TYPE_DECL is accessed.
18489    LOCATION is the location of the usage point of TYPE_DECL.
18490
18491    This function is a subroutine of
18492    append_type_to_template_for_access_check.  */
18493
18494 static void
18495 append_type_to_template_for_access_check_1 (tree t,
18496                                             tree type_decl,
18497                                             tree scope,
18498                                             location_t location)
18499 {
18500   qualified_typedef_usage_t typedef_usage;
18501   tree ti;
18502
18503   if (!t || t == error_mark_node)
18504     return;
18505
18506   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18507                || CLASS_TYPE_P (t))
18508               && type_decl
18509               && TREE_CODE (type_decl) == TYPE_DECL
18510               && scope);
18511
18512   if (!(ti = get_template_info (t)))
18513     return;
18514
18515   gcc_assert (TI_TEMPLATE (ti));
18516
18517   typedef_usage.typedef_decl = type_decl;
18518   typedef_usage.context = scope;
18519   typedef_usage.locus = location;
18520
18521   VEC_safe_push (qualified_typedef_usage_t, gc,
18522                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18523                  &typedef_usage);
18524 }
18525
18526 /* Append TYPE_DECL to the template TEMPL.
18527    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18528    At TEMPL instanciation time, TYPE_DECL will be checked to see
18529    if it can be accessed through SCOPE.
18530    LOCATION is the location of the usage point of TYPE_DECL.
18531
18532    e.g. consider the following code snippet:
18533
18534      class C
18535      {
18536        typedef int myint;
18537      };
18538
18539      template<class U> struct S
18540      {
18541        C::myint mi; // <-- usage point of the typedef C::myint
18542      };
18543
18544      S<char> s;
18545
18546    At S<char> instantiation time, we need to check the access of C::myint
18547    In other words, we need to check the access of the myint typedef through
18548    the C scope. For that purpose, this function will add the myint typedef
18549    and the scope C through which its being accessed to a list of typedefs
18550    tied to the template S. That list will be walked at template instantiation
18551    time and access check performed on each typedefs it contains.
18552    Note that this particular code snippet should yield an error because
18553    myint is private to C.  */
18554
18555 void
18556 append_type_to_template_for_access_check (tree templ,
18557                                           tree type_decl,
18558                                           tree scope,
18559                                           location_t location)
18560 {
18561   qualified_typedef_usage_t *iter;
18562   int i;
18563
18564   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18565
18566   /* Make sure we don't append the type to the template twice.  */
18567   for (i = 0;
18568        VEC_iterate (qualified_typedef_usage_t,
18569                     get_types_needing_access_check (templ),
18570                     i, iter);
18571        ++i)
18572     if (iter->typedef_decl == type_decl && scope == iter->context)
18573       return;
18574
18575   append_type_to_template_for_access_check_1 (templ, type_decl,
18576                                               scope, location);
18577 }
18578
18579 /* Set up the hash tables for template instantiations.  */
18580
18581 void
18582 init_template_processing (void)
18583 {
18584   decl_specializations = htab_create_ggc (37,
18585                                           hash_specialization,
18586                                           eq_specializations,
18587                                           ggc_free);
18588   type_specializations = htab_create_ggc (37,
18589                                           hash_specialization,
18590                                           eq_specializations,
18591                                           ggc_free);
18592 }
18593
18594 /* Print stats about the template hash tables for -fstats.  */
18595
18596 void
18597 print_template_statistics (void)
18598 {
18599   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
18600            "%f collisions\n", (long) htab_size (decl_specializations),
18601            (long) htab_elements (decl_specializations),
18602            htab_collisions (decl_specializations));
18603   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
18604            "%f collisions\n", (long) htab_size (type_specializations),
18605            (long) htab_elements (type_specializations),
18606            htab_collisions (type_specializations));
18607 }
18608
18609 #include "gt-cp-pt.h"