OSDN Git Service

PR c++/50086
[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, 2011
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 "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 enum template_base_result {
113   tbr_incomplete_type,
114   tbr_ambiguous_baseclass,
115   tbr_success
116 };
117
118 static void push_access_scope (tree);
119 static void pop_access_scope (tree);
120 static void push_deduction_access_scope (tree);
121 static void pop_deduction_access_scope (tree);
122 static bool resolve_overloaded_unification (tree, tree, tree, tree,
123                                             unification_kind_t, int,
124                                             bool);
125 static int try_one_overload (tree, tree, tree, tree, tree,
126                              unification_kind_t, int, bool, bool);
127 static int unify (tree, tree, tree, tree, int, bool);
128 static void add_pending_template (tree);
129 static tree reopen_tinst_level (struct tinst_level *);
130 static tree tsubst_initializer_list (tree, tree);
131 static tree get_class_bindings (tree, tree, tree);
132 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
133                                    bool, bool);
134 static void tsubst_enum (tree, tree, tree);
135 static tree add_to_template_args (tree, tree);
136 static tree add_outermost_template_args (tree, tree);
137 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
138 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
139                                              tree);
140 static int type_unification_real (tree, tree, tree, const tree *,
141                                   unsigned int, int, unification_kind_t, int,
142                                   bool);
143 static void note_template_header (int);
144 static tree convert_nontype_argument_function (tree, tree);
145 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
146 static tree convert_template_argument (tree, tree, tree,
147                                        tsubst_flags_t, int, tree);
148 static int for_each_template_parm (tree, tree_fn_t, void*,
149                                    struct pointer_set_t*, bool);
150 static tree expand_template_argument_pack (tree);
151 static tree build_template_parm_index (int, int, int, int, tree, tree);
152 static bool inline_needs_template_parms (tree);
153 static void push_inline_template_parms_recursive (tree, int);
154 static tree retrieve_local_specialization (tree);
155 static void register_local_specialization (tree, tree);
156 static hashval_t hash_specialization (const void *p);
157 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
158 static int mark_template_parm (tree, void *);
159 static int template_parm_this_level_p (tree, void *);
160 static tree tsubst_friend_function (tree, tree);
161 static tree tsubst_friend_class (tree, tree);
162 static int can_complete_type_without_circularity (tree);
163 static tree get_bindings (tree, tree, tree, bool);
164 static int template_decl_level (tree);
165 static int check_cv_quals_for_unify (int, tree, tree);
166 static void template_parm_level_and_index (tree, int*, int*);
167 static int unify_pack_expansion (tree, tree, tree,
168                                  tree, int, bool, bool, bool);
169 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
171 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
172 static void regenerate_decl_from_template (tree, tree);
173 static tree most_specialized_class (tree, tree, tsubst_flags_t);
174 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
175 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
177 static bool check_specialization_scope (void);
178 static tree process_partial_specialization (tree);
179 static void set_current_access_from_decl (tree);
180 static enum template_base_result get_template_base (tree, tree, tree, tree,
181                                                     bool , tree *);
182 static tree try_class_unification (tree, tree, tree, tree, bool);
183 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
184                                            tree, tree);
185 static bool template_template_parm_bindings_ok_p (tree, tree);
186 static int template_args_equal (tree, tree);
187 static void tsubst_default_arguments (tree);
188 static tree for_each_template_parm_r (tree *, int *, void *);
189 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
190 static void copy_default_args_to_explicit_spec (tree);
191 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
192 static int eq_local_specializations (const void *, const void *);
193 static bool dependent_template_arg_p (tree);
194 static bool any_template_arguments_need_structural_equality_p (tree);
195 static bool dependent_type_p_r (tree);
196 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
197 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
198 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
199 static tree tsubst_decl (tree, tree, tsubst_flags_t);
200 static void perform_typedefs_access_check (tree tmpl, tree targs);
201 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
202                                                         location_t);
203 static tree listify (tree);
204 static tree listify_autos (tree, tree);
205 static tree template_parm_to_arg (tree t);
206 static tree current_template_args (void);
207 static tree fixup_template_type_parm_type (tree, int);
208 static tree fixup_template_parm_index (tree, tree, int);
209 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
210
211 /* Make the current scope suitable for access checking when we are
212    processing T.  T can be FUNCTION_DECL for instantiated function
213    template, or VAR_DECL for static member variable (need by
214    instantiate_decl).  */
215
216 static void
217 push_access_scope (tree t)
218 {
219   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
220               || TREE_CODE (t) == VAR_DECL);
221
222   if (DECL_FRIEND_CONTEXT (t))
223     push_nested_class (DECL_FRIEND_CONTEXT (t));
224   else if (DECL_CLASS_SCOPE_P (t))
225     push_nested_class (DECL_CONTEXT (t));
226   else
227     push_to_top_level ();
228
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       saved_access_scope = tree_cons
232         (NULL_TREE, current_function_decl, saved_access_scope);
233       current_function_decl = t;
234     }
235 }
236
237 /* Restore the scope set up by push_access_scope.  T is the node we
238    are processing.  */
239
240 static void
241 pop_access_scope (tree t)
242 {
243   if (TREE_CODE (t) == FUNCTION_DECL)
244     {
245       current_function_decl = TREE_VALUE (saved_access_scope);
246       saved_access_scope = TREE_CHAIN (saved_access_scope);
247     }
248
249   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
250     pop_nested_class ();
251   else
252     pop_from_top_level ();
253 }
254
255 /* Do any processing required when DECL (a member template
256    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
257    to DECL, unless it is a specialization, in which case the DECL
258    itself is returned.  */
259
260 tree
261 finish_member_template_decl (tree decl)
262 {
263   if (decl == error_mark_node)
264     return error_mark_node;
265
266   gcc_assert (DECL_P (decl));
267
268   if (TREE_CODE (decl) == TYPE_DECL)
269     {
270       tree type;
271
272       type = TREE_TYPE (decl);
273       if (type == error_mark_node)
274         return error_mark_node;
275       if (MAYBE_CLASS_TYPE_P (type)
276           && CLASSTYPE_TEMPLATE_INFO (type)
277           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
278         {
279           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
280           check_member_template (tmpl);
281           return tmpl;
282         }
283       return NULL_TREE;
284     }
285   else if (TREE_CODE (decl) == FIELD_DECL)
286     error ("data member %qD cannot be a member template", decl);
287   else if (DECL_TEMPLATE_INFO (decl))
288     {
289       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
290         {
291           check_member_template (DECL_TI_TEMPLATE (decl));
292           return DECL_TI_TEMPLATE (decl);
293         }
294       else
295         return decl;
296     }
297   else
298     error ("invalid member template declaration %qD", decl);
299
300   return error_mark_node;
301 }
302
303 /* Create a template info node.  */
304
305 tree
306 build_template_info (tree template_decl, tree template_args)
307 {
308   tree result = make_node (TEMPLATE_INFO);
309   TI_TEMPLATE (result) = template_decl;
310   TI_ARGS (result) = template_args;
311   return result;
312 }
313
314 /* Return the template info node corresponding to T, whatever T is.  */
315
316 tree
317 get_template_info (const_tree t)
318 {
319   tree tinfo = NULL_TREE;
320
321   if (!t || t == error_mark_node)
322     return NULL;
323
324   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
325     tinfo = DECL_TEMPLATE_INFO (t);
326
327   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
328     t = TREE_TYPE (t);
329
330   if (TAGGED_TYPE_P (t))
331     tinfo = TYPE_TEMPLATE_INFO (t);
332   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
333     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
334
335   return tinfo;
336 }
337
338 /* Returns the template nesting level of the indicated class TYPE.
339
340    For example, in:
341      template <class T>
342      struct A
343      {
344        template <class U>
345        struct B {};
346      };
347
348    A<T>::B<U> has depth two, while A<T> has depth one.
349    Both A<T>::B<int> and A<int>::B<U> have depth one, if
350    they are instantiations, not specializations.
351
352    This function is guaranteed to return 0 if passed NULL_TREE so
353    that, for example, `template_class_depth (current_class_type)' is
354    always safe.  */
355
356 int
357 template_class_depth (tree type)
358 {
359   int depth;
360
361   for (depth = 0;
362        type && TREE_CODE (type) != NAMESPACE_DECL;
363        type = (TREE_CODE (type) == FUNCTION_DECL)
364          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
365     {
366       tree tinfo = get_template_info (type);
367
368       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
369           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
370         ++depth;
371     }
372
373   return depth;
374 }
375
376 /* Subroutine of maybe_begin_member_template_processing.
377    Returns true if processing DECL needs us to push template parms.  */
378
379 static bool
380 inline_needs_template_parms (tree decl)
381 {
382   if (! DECL_TEMPLATE_INFO (decl))
383     return false;
384
385   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
386           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
387 }
388
389 /* Subroutine of maybe_begin_member_template_processing.
390    Push the template parms in PARMS, starting from LEVELS steps into the
391    chain, and ending at the beginning, since template parms are listed
392    innermost first.  */
393
394 static void
395 push_inline_template_parms_recursive (tree parmlist, int levels)
396 {
397   tree parms = TREE_VALUE (parmlist);
398   int i;
399
400   if (levels > 1)
401     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
402
403   ++processing_template_decl;
404   current_template_parms
405     = tree_cons (size_int (processing_template_decl),
406                  parms, current_template_parms);
407   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
408
409   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
410                NULL);
411   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
412     {
413       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
414
415       if (parm == error_mark_node)
416         continue;
417
418       gcc_assert (DECL_P (parm));
419
420       switch (TREE_CODE (parm))
421         {
422         case TYPE_DECL:
423         case TEMPLATE_DECL:
424           pushdecl (parm);
425           break;
426
427         case PARM_DECL:
428           {
429             /* Make a CONST_DECL as is done in process_template_parm.
430                It is ugly that we recreate this here; the original
431                version built in process_template_parm is no longer
432                available.  */
433             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
434                                     CONST_DECL, DECL_NAME (parm),
435                                     TREE_TYPE (parm));
436             DECL_ARTIFICIAL (decl) = 1;
437             TREE_CONSTANT (decl) = 1;
438             TREE_READONLY (decl) = 1;
439             DECL_INITIAL (decl) = DECL_INITIAL (parm);
440             SET_DECL_TEMPLATE_PARM_P (decl);
441             pushdecl (decl);
442           }
443           break;
444
445         default:
446           gcc_unreachable ();
447         }
448     }
449 }
450
451 /* Restore the template parameter context for a member template or
452    a friend template defined in a class definition.  */
453
454 void
455 maybe_begin_member_template_processing (tree decl)
456 {
457   tree parms;
458   int levels = 0;
459
460   if (inline_needs_template_parms (decl))
461     {
462       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
463       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
464
465       if (DECL_TEMPLATE_SPECIALIZATION (decl))
466         {
467           --levels;
468           parms = TREE_CHAIN (parms);
469         }
470
471       push_inline_template_parms_recursive (parms, levels);
472     }
473
474   /* Remember how many levels of template parameters we pushed so that
475      we can pop them later.  */
476   VEC_safe_push (int, heap, inline_parm_levels, levels);
477 }
478
479 /* Undo the effects of maybe_begin_member_template_processing.  */
480
481 void
482 maybe_end_member_template_processing (void)
483 {
484   int i;
485   int last;
486
487   if (VEC_length (int, inline_parm_levels) == 0)
488     return;
489
490   last = VEC_pop (int, inline_parm_levels);
491   for (i = 0; i < last; ++i)
492     {
493       --processing_template_decl;
494       current_template_parms = TREE_CHAIN (current_template_parms);
495       poplevel (0, 0, 0);
496     }
497 }
498
499 /* Return a new template argument vector which contains all of ARGS,
500    but has as its innermost set of arguments the EXTRA_ARGS.  */
501
502 static tree
503 add_to_template_args (tree args, tree extra_args)
504 {
505   tree new_args;
506   int extra_depth;
507   int i;
508   int j;
509
510   if (args == NULL_TREE || extra_args == error_mark_node)
511     return extra_args;
512
513   extra_depth = TMPL_ARGS_DEPTH (extra_args);
514   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
515
516   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
517     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
518
519   for (j = 1; j <= extra_depth; ++j, ++i)
520     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
521
522   return new_args;
523 }
524
525 /* Like add_to_template_args, but only the outermost ARGS are added to
526    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
527    (EXTRA_ARGS) levels are added.  This function is used to combine
528    the template arguments from a partial instantiation with the
529    template arguments used to attain the full instantiation from the
530    partial instantiation.  */
531
532 static tree
533 add_outermost_template_args (tree args, tree extra_args)
534 {
535   tree new_args;
536
537   /* If there are more levels of EXTRA_ARGS than there are ARGS,
538      something very fishy is going on.  */
539   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
540
541   /* If *all* the new arguments will be the EXTRA_ARGS, just return
542      them.  */
543   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
544     return extra_args;
545
546   /* For the moment, we make ARGS look like it contains fewer levels.  */
547   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
548
549   new_args = add_to_template_args (args, extra_args);
550
551   /* Now, we restore ARGS to its full dimensions.  */
552   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
553
554   return new_args;
555 }
556
557 /* Return the N levels of innermost template arguments from the ARGS.  */
558
559 tree
560 get_innermost_template_args (tree args, int n)
561 {
562   tree new_args;
563   int extra_levels;
564   int i;
565
566   gcc_assert (n >= 0);
567
568   /* If N is 1, just return the innermost set of template arguments.  */
569   if (n == 1)
570     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
571
572   /* If we're not removing anything, just return the arguments we were
573      given.  */
574   extra_levels = TMPL_ARGS_DEPTH (args) - n;
575   gcc_assert (extra_levels >= 0);
576   if (extra_levels == 0)
577     return args;
578
579   /* Make a new set of arguments, not containing the outer arguments.  */
580   new_args = make_tree_vec (n);
581   for (i = 1; i <= n; ++i)
582     SET_TMPL_ARGS_LEVEL (new_args, i,
583                          TMPL_ARGS_LEVEL (args, i + extra_levels));
584
585   return new_args;
586 }
587
588 /* The inverse of get_innermost_template_args: Return all but the innermost
589    EXTRA_LEVELS levels of template arguments from the ARGS.  */
590
591 static tree
592 strip_innermost_template_args (tree args, int extra_levels)
593 {
594   tree new_args;
595   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
596   int i;
597
598   gcc_assert (n >= 0);
599
600   /* If N is 1, just return the outermost set of template arguments.  */
601   if (n == 1)
602     return TMPL_ARGS_LEVEL (args, 1);
603
604   /* If we're not removing anything, just return the arguments we were
605      given.  */
606   gcc_assert (extra_levels >= 0);
607   if (extra_levels == 0)
608     return args;
609
610   /* Make a new set of arguments, not containing the inner arguments.  */
611   new_args = make_tree_vec (n);
612   for (i = 1; i <= n; ++i)
613     SET_TMPL_ARGS_LEVEL (new_args, i,
614                          TMPL_ARGS_LEVEL (args, i));
615
616   return new_args;
617 }
618
619 /* We've got a template header coming up; push to a new level for storing
620    the parms.  */
621
622 void
623 begin_template_parm_list (void)
624 {
625   /* We use a non-tag-transparent scope here, which causes pushtag to
626      put tags in this scope, rather than in the enclosing class or
627      namespace scope.  This is the right thing, since we want
628      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
629      global template class, push_template_decl handles putting the
630      TEMPLATE_DECL into top-level scope.  For a nested template class,
631      e.g.:
632
633        template <class T> struct S1 {
634          template <class T> struct S2 {};
635        };
636
637      pushtag contains special code to call pushdecl_with_scope on the
638      TEMPLATE_DECL for S2.  */
639   begin_scope (sk_template_parms, NULL);
640   ++processing_template_decl;
641   ++processing_template_parmlist;
642   note_template_header (0);
643 }
644
645 /* This routine is called when a specialization is declared.  If it is
646    invalid to declare a specialization here, an error is reported and
647    false is returned, otherwise this routine will return true.  */
648
649 static bool
650 check_specialization_scope (void)
651 {
652   tree scope = current_scope ();
653
654   /* [temp.expl.spec]
655
656      An explicit specialization shall be declared in the namespace of
657      which the template is a member, or, for member templates, in the
658      namespace of which the enclosing class or enclosing class
659      template is a member.  An explicit specialization of a member
660      function, member class or static data member of a class template
661      shall be declared in the namespace of which the class template
662      is a member.  */
663   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
664     {
665       error ("explicit specialization in non-namespace scope %qD", scope);
666       return false;
667     }
668
669   /* [temp.expl.spec]
670
671      In an explicit specialization declaration for a member of a class
672      template or a member template that appears in namespace scope,
673      the member template and some of its enclosing class templates may
674      remain unspecialized, except that the declaration shall not
675      explicitly specialize a class member template if its enclosing
676      class templates are not explicitly specialized as well.  */
677   if (current_template_parms)
678     {
679       error ("enclosing class templates are not explicitly specialized");
680       return false;
681     }
682
683   return true;
684 }
685
686 /* We've just seen template <>.  */
687
688 bool
689 begin_specialization (void)
690 {
691   begin_scope (sk_template_spec, NULL);
692   note_template_header (1);
693   return check_specialization_scope ();
694 }
695
696 /* Called at then end of processing a declaration preceded by
697    template<>.  */
698
699 void
700 end_specialization (void)
701 {
702   finish_scope ();
703   reset_specialization ();
704 }
705
706 /* Any template <>'s that we have seen thus far are not referring to a
707    function specialization.  */
708
709 void
710 reset_specialization (void)
711 {
712   processing_specialization = 0;
713   template_header_count = 0;
714 }
715
716 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
717    it was of the form template <>.  */
718
719 static void
720 note_template_header (int specialization)
721 {
722   processing_specialization = specialization;
723   template_header_count++;
724 }
725
726 /* We're beginning an explicit instantiation.  */
727
728 void
729 begin_explicit_instantiation (void)
730 {
731   gcc_assert (!processing_explicit_instantiation);
732   processing_explicit_instantiation = true;
733 }
734
735
736 void
737 end_explicit_instantiation (void)
738 {
739   gcc_assert (processing_explicit_instantiation);
740   processing_explicit_instantiation = false;
741 }
742
743 /* An explicit specialization or partial specialization TMPL is being
744    declared.  Check that the namespace in which the specialization is
745    occurring is permissible.  Returns false iff it is invalid to
746    specialize TMPL in the current namespace.  */
747
748 static bool
749 check_specialization_namespace (tree tmpl)
750 {
751   tree tpl_ns = decl_namespace_context (tmpl);
752
753   /* [tmpl.expl.spec]
754
755      An explicit specialization shall be declared in the namespace of
756      which the template is a member, or, for member templates, in the
757      namespace of which the enclosing class or enclosing class
758      template is a member.  An explicit specialization of a member
759      function, member class or static data member of a class template
760      shall be declared in the namespace of which the class template is
761      a member.  */
762   if (current_scope() != DECL_CONTEXT (tmpl)
763       && !at_namespace_scope_p ())
764     {
765       error ("specialization of %qD must appear at namespace scope", tmpl);
766       return false;
767     }
768   if (is_associated_namespace (current_namespace, tpl_ns))
769     /* Same or super-using namespace.  */
770     return true;
771   else
772     {
773       permerror (input_location, "specialization of %qD in different namespace", tmpl);
774       permerror (input_location, "  from definition of %q+#D", tmpl);
775       return false;
776     }
777 }
778
779 /* SPEC is an explicit instantiation.  Check that it is valid to
780    perform this explicit instantiation in the current namespace.  */
781
782 static void
783 check_explicit_instantiation_namespace (tree spec)
784 {
785   tree ns;
786
787   /* DR 275: An explicit instantiation shall appear in an enclosing
788      namespace of its template.  */
789   ns = decl_namespace_context (spec);
790   if (!is_ancestor (current_namespace, ns))
791     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
792                "(which does not enclose namespace %qD)",
793                spec, current_namespace, ns);
794 }
795
796 /* The TYPE is being declared.  If it is a template type, that means it
797    is a partial specialization.  Do appropriate error-checking.  */
798
799 tree
800 maybe_process_partial_specialization (tree type)
801 {
802   tree context;
803
804   if (type == error_mark_node)
805     return error_mark_node;
806
807   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
808     {
809       error ("name of class shadows template template parameter %qD",
810              TYPE_NAME (type));
811       return error_mark_node;
812     }
813
814   context = TYPE_CONTEXT (type);
815
816   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
817     {
818       /* This is for ordinary explicit specialization and partial
819          specialization of a template class such as:
820
821            template <> class C<int>;
822
823          or:
824
825            template <class T> class C<T*>;
826
827          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
828
829       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
830           && !COMPLETE_TYPE_P (type))
831         {
832           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
833           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
834           if (processing_template_decl)
835             {
836               if (push_template_decl (TYPE_MAIN_DECL (type))
837                   == error_mark_node)
838                 return error_mark_node;
839             }
840         }
841       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
842         error ("specialization of %qT after instantiation", type);
843     }
844   else if (CLASS_TYPE_P (type)
845            && !CLASSTYPE_USE_TEMPLATE (type)
846            && CLASSTYPE_TEMPLATE_INFO (type)
847            && context && CLASS_TYPE_P (context)
848            && CLASSTYPE_TEMPLATE_INFO (context))
849     {
850       /* This is for an explicit specialization of member class
851          template according to [temp.expl.spec/18]:
852
853            template <> template <class U> class C<int>::D;
854
855          The context `C<int>' must be an implicit instantiation.
856          Otherwise this is just a member class template declared
857          earlier like:
858
859            template <> class C<int> { template <class U> class D; };
860            template <> template <class U> class C<int>::D;
861
862          In the first case, `C<int>::D' is a specialization of `C<T>::D'
863          while in the second case, `C<int>::D' is a primary template
864          and `C<T>::D' may not exist.  */
865
866       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
867           && !COMPLETE_TYPE_P (type))
868         {
869           tree t;
870           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
871
872           if (current_namespace
873               != decl_namespace_context (tmpl))
874             {
875               permerror (input_location, "specializing %q#T in different namespace", type);
876               permerror (input_location, "  from definition of %q+#D", tmpl);
877             }
878
879           /* Check for invalid specialization after instantiation:
880
881                template <> template <> class C<int>::D<int>;
882                template <> template <class U> class C<int>::D;  */
883
884           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
885                t; t = TREE_CHAIN (t))
886             {
887               tree inst = TREE_VALUE (t);
888               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
889                 {
890                   /* We already have a full specialization of this partial
891                      instantiation.  Reassign it to the new member
892                      specialization template.  */
893                   spec_entry elt;
894                   spec_entry **slot;
895
896                   elt.tmpl = most_general_template (tmpl);
897                   elt.args = CLASSTYPE_TI_ARGS (inst);
898                   elt.spec = inst;
899
900                   htab_remove_elt (type_specializations, &elt);
901
902                   elt.tmpl = tmpl;
903                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
904
905                   slot = (spec_entry **)
906                     htab_find_slot (type_specializations, &elt, INSERT);
907                   *slot = ggc_alloc_spec_entry ();
908                   **slot = elt;
909                 }
910               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
911                 /* But if we've had an implicit instantiation, that's a
912                    problem ([temp.expl.spec]/6).  */
913                 error ("specialization %qT after instantiation %qT",
914                        type, inst);
915             }
916
917           /* Mark TYPE as a specialization.  And as a result, we only
918              have one level of template argument for the innermost
919              class template.  */
920           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
921           CLASSTYPE_TI_ARGS (type)
922             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
923         }
924     }
925   else if (processing_specialization)
926     {
927        /* Someday C++0x may allow for enum template specialization.  */
928       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
929           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
930         pedwarn (input_location, OPT_pedantic, "template specialization "
931                  "of %qD not allowed by ISO C++", type);
932       else
933         {
934           error ("explicit specialization of non-template %qT", type);
935           return error_mark_node;
936         }
937     }
938
939   return type;
940 }
941
942 /* Returns nonzero if we can optimize the retrieval of specializations
943    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
944    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
945
946 static inline bool
947 optimize_specialization_lookup_p (tree tmpl)
948 {
949   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
950           && DECL_CLASS_SCOPE_P (tmpl)
951           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
952              parameter.  */
953           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
954           /* The optimized lookup depends on the fact that the
955              template arguments for the member function template apply
956              purely to the containing class, which is not true if the
957              containing class is an explicit or partial
958              specialization.  */
959           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
960           && !DECL_MEMBER_TEMPLATE_P (tmpl)
961           && !DECL_CONV_FN_P (tmpl)
962           /* It is possible to have a template that is not a member
963              template and is not a member of a template class:
964
965              template <typename T>
966              struct S { friend A::f(); };
967
968              Here, the friend function is a template, but the context does
969              not have template information.  The optimized lookup relies
970              on having ARGS be the template arguments for both the class
971              and the function template.  */
972           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
973 }
974
975 /* Retrieve the specialization (in the sense of [temp.spec] - a
976    specialization is either an instantiation or an explicit
977    specialization) of TMPL for the given template ARGS.  If there is
978    no such specialization, return NULL_TREE.  The ARGS are a vector of
979    arguments, or a vector of vectors of arguments, in the case of
980    templates with more than one level of parameters.
981
982    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
983    then we search for a partial specialization matching ARGS.  This
984    parameter is ignored if TMPL is not a class template.  */
985
986 static tree
987 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
988 {
989   if (args == error_mark_node)
990     return NULL_TREE;
991
992   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
993
994   /* There should be as many levels of arguments as there are
995      levels of parameters.  */
996   gcc_assert (TMPL_ARGS_DEPTH (args)
997               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
998
999   if (optimize_specialization_lookup_p (tmpl))
1000     {
1001       tree class_template;
1002       tree class_specialization;
1003       VEC(tree,gc) *methods;
1004       tree fns;
1005       int idx;
1006
1007       /* The template arguments actually apply to the containing
1008          class.  Find the class specialization with those
1009          arguments.  */
1010       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1011       class_specialization
1012         = retrieve_specialization (class_template, args, 0);
1013       if (!class_specialization)
1014         return NULL_TREE;
1015       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1016          for the specialization.  */
1017       idx = class_method_index_for_fn (class_specialization, tmpl);
1018       if (idx == -1)
1019         return NULL_TREE;
1020       /* Iterate through the methods with the indicated name, looking
1021          for the one that has an instance of TMPL.  */
1022       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1023       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1024         {
1025           tree fn = OVL_CURRENT (fns);
1026           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1027               /* using-declarations can add base methods to the method vec,
1028                  and we don't want those here.  */
1029               && DECL_CONTEXT (fn) == class_specialization)
1030             return fn;
1031         }
1032       return NULL_TREE;
1033     }
1034   else
1035     {
1036       spec_entry *found;
1037       spec_entry elt;
1038       htab_t specializations;
1039
1040       elt.tmpl = tmpl;
1041       elt.args = args;
1042       elt.spec = NULL_TREE;
1043
1044       if (DECL_CLASS_TEMPLATE_P (tmpl))
1045         specializations = type_specializations;
1046       else
1047         specializations = decl_specializations;
1048
1049       if (hash == 0)
1050         hash = hash_specialization (&elt);
1051       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1052       if (found)
1053         return found->spec;
1054     }
1055
1056   return NULL_TREE;
1057 }
1058
1059 /* Like retrieve_specialization, but for local declarations.  */
1060
1061 static tree
1062 retrieve_local_specialization (tree tmpl)
1063 {
1064   tree spec;
1065
1066   if (local_specializations == NULL)
1067     return NULL_TREE;
1068
1069   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1070                                      htab_hash_pointer (tmpl));
1071   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1072 }
1073
1074 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1075
1076 int
1077 is_specialization_of (tree decl, tree tmpl)
1078 {
1079   tree t;
1080
1081   if (TREE_CODE (decl) == FUNCTION_DECL)
1082     {
1083       for (t = decl;
1084            t != NULL_TREE;
1085            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1086         if (t == tmpl)
1087           return 1;
1088     }
1089   else
1090     {
1091       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1092
1093       for (t = TREE_TYPE (decl);
1094            t != NULL_TREE;
1095            t = CLASSTYPE_USE_TEMPLATE (t)
1096              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1097         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1098           return 1;
1099     }
1100
1101   return 0;
1102 }
1103
1104 /* Returns nonzero iff DECL is a specialization of friend declaration
1105    FRIEND_DECL according to [temp.friend].  */
1106
1107 bool
1108 is_specialization_of_friend (tree decl, tree friend_decl)
1109 {
1110   bool need_template = true;
1111   int template_depth;
1112
1113   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1114               || TREE_CODE (decl) == TYPE_DECL);
1115
1116   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1117      of a template class, we want to check if DECL is a specialization
1118      if this.  */
1119   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1120       && DECL_TEMPLATE_INFO (friend_decl)
1121       && !DECL_USE_TEMPLATE (friend_decl))
1122     {
1123       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1124       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1125       need_template = false;
1126     }
1127   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1128            && !PRIMARY_TEMPLATE_P (friend_decl))
1129     need_template = false;
1130
1131   /* There is nothing to do if this is not a template friend.  */
1132   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1133     return false;
1134
1135   if (is_specialization_of (decl, friend_decl))
1136     return true;
1137
1138   /* [temp.friend/6]
1139      A member of a class template may be declared to be a friend of a
1140      non-template class.  In this case, the corresponding member of
1141      every specialization of the class template is a friend of the
1142      class granting friendship.
1143
1144      For example, given a template friend declaration
1145
1146        template <class T> friend void A<T>::f();
1147
1148      the member function below is considered a friend
1149
1150        template <> struct A<int> {
1151          void f();
1152        };
1153
1154      For this type of template friend, TEMPLATE_DEPTH below will be
1155      nonzero.  To determine if DECL is a friend of FRIEND, we first
1156      check if the enclosing class is a specialization of another.  */
1157
1158   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1159   if (template_depth
1160       && DECL_CLASS_SCOPE_P (decl)
1161       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1162                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1163     {
1164       /* Next, we check the members themselves.  In order to handle
1165          a few tricky cases, such as when FRIEND_DECL's are
1166
1167            template <class T> friend void A<T>::g(T t);
1168            template <class T> template <T t> friend void A<T>::h();
1169
1170          and DECL's are
1171
1172            void A<int>::g(int);
1173            template <int> void A<int>::h();
1174
1175          we need to figure out ARGS, the template arguments from
1176          the context of DECL.  This is required for template substitution
1177          of `T' in the function parameter of `g' and template parameter
1178          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1179
1180       tree context = DECL_CONTEXT (decl);
1181       tree args = NULL_TREE;
1182       int current_depth = 0;
1183
1184       while (current_depth < template_depth)
1185         {
1186           if (CLASSTYPE_TEMPLATE_INFO (context))
1187             {
1188               if (current_depth == 0)
1189                 args = TYPE_TI_ARGS (context);
1190               else
1191                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1192               current_depth++;
1193             }
1194           context = TYPE_CONTEXT (context);
1195         }
1196
1197       if (TREE_CODE (decl) == FUNCTION_DECL)
1198         {
1199           bool is_template;
1200           tree friend_type;
1201           tree decl_type;
1202           tree friend_args_type;
1203           tree decl_args_type;
1204
1205           /* Make sure that both DECL and FRIEND_DECL are templates or
1206              non-templates.  */
1207           is_template = DECL_TEMPLATE_INFO (decl)
1208                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1209           if (need_template ^ is_template)
1210             return false;
1211           else if (is_template)
1212             {
1213               /* If both are templates, check template parameter list.  */
1214               tree friend_parms
1215                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1216                                          args, tf_none);
1217               if (!comp_template_parms
1218                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1219                       friend_parms))
1220                 return false;
1221
1222               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1223             }
1224           else
1225             decl_type = TREE_TYPE (decl);
1226
1227           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1228                                               tf_none, NULL_TREE);
1229           if (friend_type == error_mark_node)
1230             return false;
1231
1232           /* Check if return types match.  */
1233           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1234             return false;
1235
1236           /* Check if function parameter types match, ignoring the
1237              `this' parameter.  */
1238           friend_args_type = TYPE_ARG_TYPES (friend_type);
1239           decl_args_type = TYPE_ARG_TYPES (decl_type);
1240           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1241             friend_args_type = TREE_CHAIN (friend_args_type);
1242           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1243             decl_args_type = TREE_CHAIN (decl_args_type);
1244
1245           return compparms (decl_args_type, friend_args_type);
1246         }
1247       else
1248         {
1249           /* DECL is a TYPE_DECL */
1250           bool is_template;
1251           tree decl_type = TREE_TYPE (decl);
1252
1253           /* Make sure that both DECL and FRIEND_DECL are templates or
1254              non-templates.  */
1255           is_template
1256             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1257               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1258
1259           if (need_template ^ is_template)
1260             return false;
1261           else if (is_template)
1262             {
1263               tree friend_parms;
1264               /* If both are templates, check the name of the two
1265                  TEMPLATE_DECL's first because is_friend didn't.  */
1266               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1267                   != DECL_NAME (friend_decl))
1268                 return false;
1269
1270               /* Now check template parameter list.  */
1271               friend_parms
1272                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1273                                          args, tf_none);
1274               return comp_template_parms
1275                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1276                  friend_parms);
1277             }
1278           else
1279             return (DECL_NAME (decl)
1280                     == DECL_NAME (friend_decl));
1281         }
1282     }
1283   return false;
1284 }
1285
1286 /* Register the specialization SPEC as a specialization of TMPL with
1287    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1288    is actually just a friend declaration.  Returns SPEC, or an
1289    equivalent prior declaration, if available.  */
1290
1291 static tree
1292 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1293                          hashval_t hash)
1294 {
1295   tree fn;
1296   spec_entry **slot = NULL;
1297   spec_entry elt;
1298
1299   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1300
1301   if (TREE_CODE (spec) == FUNCTION_DECL
1302       && uses_template_parms (DECL_TI_ARGS (spec)))
1303     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1304        register it; we want the corresponding TEMPLATE_DECL instead.
1305        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1306        the more obvious `uses_template_parms (spec)' to avoid problems
1307        with default function arguments.  In particular, given
1308        something like this:
1309
1310           template <class T> void f(T t1, T t = T())
1311
1312        the default argument expression is not substituted for in an
1313        instantiation unless and until it is actually needed.  */
1314     return spec;
1315
1316   if (optimize_specialization_lookup_p (tmpl))
1317     /* We don't put these specializations in the hash table, but we might
1318        want to give an error about a mismatch.  */
1319     fn = retrieve_specialization (tmpl, args, 0);
1320   else
1321     {
1322       elt.tmpl = tmpl;
1323       elt.args = args;
1324       elt.spec = spec;
1325
1326       if (hash == 0)
1327         hash = hash_specialization (&elt);
1328
1329       slot = (spec_entry **)
1330         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1331       if (*slot)
1332         fn = (*slot)->spec;
1333       else
1334         fn = NULL_TREE;
1335     }
1336
1337   /* We can sometimes try to re-register a specialization that we've
1338      already got.  In particular, regenerate_decl_from_template calls
1339      duplicate_decls which will update the specialization list.  But,
1340      we'll still get called again here anyhow.  It's more convenient
1341      to simply allow this than to try to prevent it.  */
1342   if (fn == spec)
1343     return spec;
1344   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1345     {
1346       if (DECL_TEMPLATE_INSTANTIATION (fn))
1347         {
1348           if (DECL_ODR_USED (fn)
1349               || DECL_EXPLICIT_INSTANTIATION (fn))
1350             {
1351               error ("specialization of %qD after instantiation",
1352                      fn);
1353               return error_mark_node;
1354             }
1355           else
1356             {
1357               tree clone;
1358               /* This situation should occur only if the first
1359                  specialization is an implicit instantiation, the
1360                  second is an explicit specialization, and the
1361                  implicit instantiation has not yet been used.  That
1362                  situation can occur if we have implicitly
1363                  instantiated a member function and then specialized
1364                  it later.
1365
1366                  We can also wind up here if a friend declaration that
1367                  looked like an instantiation turns out to be a
1368                  specialization:
1369
1370                    template <class T> void foo(T);
1371                    class S { friend void foo<>(int) };
1372                    template <> void foo(int);
1373
1374                  We transform the existing DECL in place so that any
1375                  pointers to it become pointers to the updated
1376                  declaration.
1377
1378                  If there was a definition for the template, but not
1379                  for the specialization, we want this to look as if
1380                  there were no definition, and vice versa.  */
1381               DECL_INITIAL (fn) = NULL_TREE;
1382               duplicate_decls (spec, fn, is_friend);
1383               /* The call to duplicate_decls will have applied
1384                  [temp.expl.spec]:
1385
1386                    An explicit specialization of a function template
1387                    is inline only if it is explicitly declared to be,
1388                    and independently of whether its function template
1389                    is.
1390
1391                 to the primary function; now copy the inline bits to
1392                 the various clones.  */
1393               FOR_EACH_CLONE (clone, fn)
1394                 {
1395                   DECL_DECLARED_INLINE_P (clone)
1396                     = DECL_DECLARED_INLINE_P (fn);
1397                   DECL_SOURCE_LOCATION (clone)
1398                     = DECL_SOURCE_LOCATION (fn);
1399                 }
1400               check_specialization_namespace (fn);
1401
1402               return fn;
1403             }
1404         }
1405       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1406         {
1407           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1408             /* Dup decl failed, but this is a new definition. Set the
1409                line number so any errors match this new
1410                definition.  */
1411             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1412
1413           return fn;
1414         }
1415     }
1416   else if (fn)
1417     return duplicate_decls (spec, fn, is_friend);
1418
1419   /* A specialization must be declared in the same namespace as the
1420      template it is specializing.  */
1421   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1422       && !check_specialization_namespace (tmpl))
1423     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1424
1425   if (!optimize_specialization_lookup_p (tmpl))
1426     {
1427       gcc_assert (tmpl && args && spec);
1428       *slot = ggc_alloc_spec_entry ();
1429       **slot = elt;
1430       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1431           && PRIMARY_TEMPLATE_P (tmpl)
1432           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1433         /* TMPL is a forward declaration of a template function; keep a list
1434            of all specializations in case we need to reassign them to a friend
1435            template later in tsubst_friend_function.  */
1436         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1437           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1438     }
1439
1440   return spec;
1441 }
1442
1443 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1444    TMPL and ARGS members, ignores SPEC.  */
1445
1446 static int
1447 eq_specializations (const void *p1, const void *p2)
1448 {
1449   const spec_entry *e1 = (const spec_entry *)p1;
1450   const spec_entry *e2 = (const spec_entry *)p2;
1451
1452   return (e1->tmpl == e2->tmpl
1453           && comp_template_args (e1->args, e2->args));
1454 }
1455
1456 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1457
1458 static hashval_t
1459 hash_tmpl_and_args (tree tmpl, tree args)
1460 {
1461   hashval_t val = DECL_UID (tmpl);
1462   return iterative_hash_template_arg (args, val);
1463 }
1464
1465 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1466    ignoring SPEC.  */
1467
1468 static hashval_t
1469 hash_specialization (const void *p)
1470 {
1471   const spec_entry *e = (const spec_entry *)p;
1472   return hash_tmpl_and_args (e->tmpl, e->args);
1473 }
1474
1475 /* Recursively calculate a hash value for a template argument ARG, for use
1476    in the hash tables of template specializations.  */
1477
1478 hashval_t
1479 iterative_hash_template_arg (tree arg, hashval_t val)
1480 {
1481   unsigned HOST_WIDE_INT i;
1482   enum tree_code code;
1483   char tclass;
1484
1485   if (arg == NULL_TREE)
1486     return iterative_hash_object (arg, val);
1487
1488   if (!TYPE_P (arg))
1489     STRIP_NOPS (arg);
1490
1491   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1492     /* We can get one of these when re-hashing a previous entry in the middle
1493        of substituting into a pack expansion.  Just look through it.  */
1494     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1495
1496   code = TREE_CODE (arg);
1497   tclass = TREE_CODE_CLASS (code);
1498
1499   val = iterative_hash_object (code, val);
1500
1501   switch (code)
1502     {
1503     case ERROR_MARK:
1504       return val;
1505
1506     case IDENTIFIER_NODE:
1507       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1508
1509     case TREE_VEC:
1510       {
1511         int i, len = TREE_VEC_LENGTH (arg);
1512         for (i = 0; i < len; ++i)
1513           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1514         return val;
1515       }
1516
1517     case TYPE_PACK_EXPANSION:
1518     case EXPR_PACK_EXPANSION:
1519       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1520
1521     case TYPE_ARGUMENT_PACK:
1522     case NONTYPE_ARGUMENT_PACK:
1523       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1524
1525     case TREE_LIST:
1526       for (; arg; arg = TREE_CHAIN (arg))
1527         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1528       return val;
1529
1530     case OVERLOAD:
1531       for (; arg; arg = OVL_NEXT (arg))
1532         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1533       return val;
1534
1535     case CONSTRUCTOR:
1536       {
1537         tree field, value;
1538         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1539           {
1540             val = iterative_hash_template_arg (field, val);
1541             val = iterative_hash_template_arg (value, val);
1542           }
1543         return val;
1544       }
1545
1546     case PARM_DECL:
1547       if (!DECL_ARTIFICIAL (arg))
1548         {
1549           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1550           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1551         }
1552       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1553
1554     case TARGET_EXPR:
1555       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1556
1557     case PTRMEM_CST:
1558       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1559       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1560
1561     case TEMPLATE_PARM_INDEX:
1562       val = iterative_hash_template_arg
1563         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1564       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1565       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1566
1567     case TRAIT_EXPR:
1568       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1569       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1570       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1571
1572     case BASELINK:
1573       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1574                                          val);
1575       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1576                                           val);
1577
1578     case MODOP_EXPR:
1579       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1580       code = TREE_CODE (TREE_OPERAND (arg, 1));
1581       val = iterative_hash_object (code, val);
1582       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1583
1584     case LAMBDA_EXPR:
1585       /* A lambda can't appear in a template arg, but don't crash on
1586          erroneous input.  */
1587       gcc_assert (seen_error ());
1588       return val;
1589
1590     case CAST_EXPR:
1591     case STATIC_CAST_EXPR:
1592     case REINTERPRET_CAST_EXPR:
1593     case CONST_CAST_EXPR:
1594     case DYNAMIC_CAST_EXPR:
1595     case NEW_EXPR:
1596       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1597       /* Now hash operands as usual.  */
1598       break;
1599
1600     default:
1601       break;
1602     }
1603
1604   switch (tclass)
1605     {
1606     case tcc_type:
1607       if (TYPE_CANONICAL (arg))
1608         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1609                                       val);
1610       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1611         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1612       /* Otherwise just compare the types during lookup.  */
1613       return val;
1614
1615     case tcc_declaration:
1616     case tcc_constant:
1617       return iterative_hash_expr (arg, val);
1618
1619     default:
1620       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1621       {
1622         unsigned n = cp_tree_operand_length (arg);
1623         for (i = 0; i < n; ++i)
1624           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1625         return val;
1626       }
1627     }
1628   gcc_unreachable ();
1629   return 0;
1630 }
1631
1632 /* Unregister the specialization SPEC as a specialization of TMPL.
1633    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1634    if the SPEC was listed as a specialization of TMPL.
1635
1636    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1637
1638 bool
1639 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1640 {
1641   spec_entry **slot;
1642   spec_entry elt;
1643
1644   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1645   elt.args = TI_ARGS (tinfo);
1646   elt.spec = NULL_TREE;
1647
1648   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1649   if (*slot)
1650     {
1651       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1652       gcc_assert (new_spec != NULL_TREE);
1653       (*slot)->spec = new_spec;
1654       return 1;
1655     }
1656
1657   return 0;
1658 }
1659
1660 /* Compare an entry in the local specializations hash table P1 (which
1661    is really a pointer to a TREE_LIST) with P2 (which is really a
1662    DECL).  */
1663
1664 static int
1665 eq_local_specializations (const void *p1, const void *p2)
1666 {
1667   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1668 }
1669
1670 /* Hash P1, an entry in the local specializations table.  */
1671
1672 static hashval_t
1673 hash_local_specialization (const void* p1)
1674 {
1675   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1676 }
1677
1678 /* Like register_specialization, but for local declarations.  We are
1679    registering SPEC, an instantiation of TMPL.  */
1680
1681 static void
1682 register_local_specialization (tree spec, tree tmpl)
1683 {
1684   void **slot;
1685
1686   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1687                                    htab_hash_pointer (tmpl), INSERT);
1688   *slot = build_tree_list (spec, tmpl);
1689 }
1690
1691 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1692    specialized class.  */
1693
1694 bool
1695 explicit_class_specialization_p (tree type)
1696 {
1697   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1698     return false;
1699   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1700 }
1701
1702 /* Print the list of functions at FNS, going through all the overloads
1703    for each element of the list.  Alternatively, FNS can not be a
1704    TREE_LIST, in which case it will be printed together with all the
1705    overloads.
1706
1707    MORE and *STR should respectively be FALSE and NULL when the function
1708    is called from the outside.  They are used internally on recursive
1709    calls.  print_candidates manages the two parameters and leaves NULL
1710    in *STR when it ends.  */
1711
1712 static void
1713 print_candidates_1 (tree fns, bool more, const char **str)
1714 {
1715   tree fn, fn2;
1716   char *spaces = NULL;
1717
1718   for (fn = fns; fn; fn = OVL_NEXT (fn))
1719     if (TREE_CODE (fn) == TREE_LIST)
1720       {
1721         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1722           print_candidates_1 (TREE_VALUE (fn2),
1723                               TREE_CHAIN (fn2) || more, str);
1724       }
1725     else
1726       {
1727         if (!*str)
1728           {
1729             /* Pick the prefix string.  */
1730             if (!more && !OVL_NEXT (fns))
1731               {
1732                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1733                 continue;
1734               }
1735
1736             *str = _("candidates are:");
1737             spaces = get_spaces (*str);
1738           }
1739         error ("%s %+#D", *str, OVL_CURRENT (fn));
1740         *str = spaces ? spaces : *str;
1741       }
1742
1743   if (!more)
1744     {
1745       free (spaces);
1746       *str = NULL;
1747     }
1748 }
1749
1750 /* Print the list of candidate FNS in an error message.  FNS can also
1751    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1752
1753 void
1754 print_candidates (tree fns)
1755 {
1756   const char *str = NULL;
1757   print_candidates_1 (fns, false, &str);
1758   gcc_assert (str == NULL);
1759 }
1760
1761 /* Returns the template (one of the functions given by TEMPLATE_ID)
1762    which can be specialized to match the indicated DECL with the
1763    explicit template args given in TEMPLATE_ID.  The DECL may be
1764    NULL_TREE if none is available.  In that case, the functions in
1765    TEMPLATE_ID are non-members.
1766
1767    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1768    specialization of a member template.
1769
1770    The TEMPLATE_COUNT is the number of references to qualifying
1771    template classes that appeared in the name of the function. See
1772    check_explicit_specialization for a more accurate description.
1773
1774    TSK indicates what kind of template declaration (if any) is being
1775    declared.  TSK_TEMPLATE indicates that the declaration given by
1776    DECL, though a FUNCTION_DECL, has template parameters, and is
1777    therefore a template function.
1778
1779    The template args (those explicitly specified and those deduced)
1780    are output in a newly created vector *TARGS_OUT.
1781
1782    If it is impossible to determine the result, an error message is
1783    issued.  The error_mark_node is returned to indicate failure.  */
1784
1785 static tree
1786 determine_specialization (tree template_id,
1787                           tree decl,
1788                           tree* targs_out,
1789                           int need_member_template,
1790                           int template_count,
1791                           tmpl_spec_kind tsk)
1792 {
1793   tree fns;
1794   tree targs;
1795   tree explicit_targs;
1796   tree candidates = NULL_TREE;
1797   /* A TREE_LIST of templates of which DECL may be a specialization.
1798      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1799      corresponding TREE_PURPOSE is the set of template arguments that,
1800      when used to instantiate the template, would produce a function
1801      with the signature of DECL.  */
1802   tree templates = NULL_TREE;
1803   int header_count;
1804   cp_binding_level *b;
1805
1806   *targs_out = NULL_TREE;
1807
1808   if (template_id == error_mark_node || decl == error_mark_node)
1809     return error_mark_node;
1810
1811   fns = TREE_OPERAND (template_id, 0);
1812   explicit_targs = TREE_OPERAND (template_id, 1);
1813
1814   if (fns == error_mark_node)
1815     return error_mark_node;
1816
1817   /* Check for baselinks.  */
1818   if (BASELINK_P (fns))
1819     fns = BASELINK_FUNCTIONS (fns);
1820
1821   if (!is_overloaded_fn (fns))
1822     {
1823       error ("%qD is not a function template", fns);
1824       return error_mark_node;
1825     }
1826
1827   /* Count the number of template headers specified for this
1828      specialization.  */
1829   header_count = 0;
1830   for (b = current_binding_level;
1831        b->kind == sk_template_parms;
1832        b = b->level_chain)
1833     ++header_count;
1834
1835   for (; fns; fns = OVL_NEXT (fns))
1836     {
1837       tree fn = OVL_CURRENT (fns);
1838
1839       if (TREE_CODE (fn) == TEMPLATE_DECL)
1840         {
1841           tree decl_arg_types;
1842           tree fn_arg_types;
1843
1844           /* In case of explicit specialization, we need to check if
1845              the number of template headers appearing in the specialization
1846              is correct. This is usually done in check_explicit_specialization,
1847              but the check done there cannot be exhaustive when specializing
1848              member functions. Consider the following code:
1849
1850              template <> void A<int>::f(int);
1851              template <> template <> void A<int>::f(int);
1852
1853              Assuming that A<int> is not itself an explicit specialization
1854              already, the first line specializes "f" which is a non-template
1855              member function, whilst the second line specializes "f" which
1856              is a template member function. So both lines are syntactically
1857              correct, and check_explicit_specialization does not reject
1858              them.
1859
1860              Here, we can do better, as we are matching the specialization
1861              against the declarations. We count the number of template
1862              headers, and we check if they match TEMPLATE_COUNT + 1
1863              (TEMPLATE_COUNT is the number of qualifying template classes,
1864              plus there must be another header for the member template
1865              itself).
1866
1867              Notice that if header_count is zero, this is not a
1868              specialization but rather a template instantiation, so there
1869              is no check we can perform here.  */
1870           if (header_count && header_count != template_count + 1)
1871             continue;
1872
1873           /* Check that the number of template arguments at the
1874              innermost level for DECL is the same as for FN.  */
1875           if (current_binding_level->kind == sk_template_parms
1876               && !current_binding_level->explicit_spec_p
1877               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1878                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1879                                       (current_template_parms))))
1880             continue;
1881
1882           /* DECL might be a specialization of FN.  */
1883           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1884           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1885
1886           /* For a non-static member function, we need to make sure
1887              that the const qualification is the same.  Since
1888              get_bindings does not try to merge the "this" parameter,
1889              we must do the comparison explicitly.  */
1890           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1891               && !same_type_p (TREE_VALUE (fn_arg_types),
1892                                TREE_VALUE (decl_arg_types)))
1893             continue;
1894
1895           /* Skip the "this" parameter and, for constructors of
1896              classes with virtual bases, the VTT parameter.  A
1897              full specialization of a constructor will have a VTT
1898              parameter, but a template never will.  */ 
1899           decl_arg_types 
1900             = skip_artificial_parms_for (decl, decl_arg_types);
1901           fn_arg_types 
1902             = skip_artificial_parms_for (fn, fn_arg_types);
1903
1904           /* Check that the number of function parameters matches.
1905              For example,
1906                template <class T> void f(int i = 0);
1907                template <> void f<int>();
1908              The specialization f<int> is invalid but is not caught
1909              by get_bindings below.  */
1910           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1911             continue;
1912
1913           /* Function templates cannot be specializations; there are
1914              no partial specializations of functions.  Therefore, if
1915              the type of DECL does not match FN, there is no
1916              match.  */
1917           if (tsk == tsk_template)
1918             {
1919               if (compparms (fn_arg_types, decl_arg_types))
1920                 candidates = tree_cons (NULL_TREE, fn, candidates);
1921               continue;
1922             }
1923
1924           /* See whether this function might be a specialization of this
1925              template.  */
1926           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1927
1928           if (!targs)
1929             /* We cannot deduce template arguments that when used to
1930                specialize TMPL will produce DECL.  */
1931             continue;
1932
1933           /* Save this template, and the arguments deduced.  */
1934           templates = tree_cons (targs, fn, templates);
1935         }
1936       else if (need_member_template)
1937         /* FN is an ordinary member function, and we need a
1938            specialization of a member template.  */
1939         ;
1940       else if (TREE_CODE (fn) != FUNCTION_DECL)
1941         /* We can get IDENTIFIER_NODEs here in certain erroneous
1942            cases.  */
1943         ;
1944       else if (!DECL_FUNCTION_MEMBER_P (fn))
1945         /* This is just an ordinary non-member function.  Nothing can
1946            be a specialization of that.  */
1947         ;
1948       else if (DECL_ARTIFICIAL (fn))
1949         /* Cannot specialize functions that are created implicitly.  */
1950         ;
1951       else
1952         {
1953           tree decl_arg_types;
1954
1955           /* This is an ordinary member function.  However, since
1956              we're here, we can assume it's enclosing class is a
1957              template class.  For example,
1958
1959                template <typename T> struct S { void f(); };
1960                template <> void S<int>::f() {}
1961
1962              Here, S<int>::f is a non-template, but S<int> is a
1963              template class.  If FN has the same type as DECL, we
1964              might be in business.  */
1965
1966           if (!DECL_TEMPLATE_INFO (fn))
1967             /* Its enclosing class is an explicit specialization
1968                of a template class.  This is not a candidate.  */
1969             continue;
1970
1971           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1972                             TREE_TYPE (TREE_TYPE (fn))))
1973             /* The return types differ.  */
1974             continue;
1975
1976           /* Adjust the type of DECL in case FN is a static member.  */
1977           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1978           if (DECL_STATIC_FUNCTION_P (fn)
1979               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1980             decl_arg_types = TREE_CHAIN (decl_arg_types);
1981
1982           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1983                          decl_arg_types))
1984             /* They match!  */
1985             candidates = tree_cons (NULL_TREE, fn, candidates);
1986         }
1987     }
1988
1989   if (templates && TREE_CHAIN (templates))
1990     {
1991       /* We have:
1992
1993            [temp.expl.spec]
1994
1995            It is possible for a specialization with a given function
1996            signature to be instantiated from more than one function
1997            template.  In such cases, explicit specification of the
1998            template arguments must be used to uniquely identify the
1999            function template specialization being specialized.
2000
2001          Note that here, there's no suggestion that we're supposed to
2002          determine which of the candidate templates is most
2003          specialized.  However, we, also have:
2004
2005            [temp.func.order]
2006
2007            Partial ordering of overloaded function template
2008            declarations is used in the following contexts to select
2009            the function template to which a function template
2010            specialization refers:
2011
2012            -- when an explicit specialization refers to a function
2013               template.
2014
2015          So, we do use the partial ordering rules, at least for now.
2016          This extension can only serve to make invalid programs valid,
2017          so it's safe.  And, there is strong anecdotal evidence that
2018          the committee intended the partial ordering rules to apply;
2019          the EDG front end has that behavior, and John Spicer claims
2020          that the committee simply forgot to delete the wording in
2021          [temp.expl.spec].  */
2022       tree tmpl = most_specialized_instantiation (templates);
2023       if (tmpl != error_mark_node)
2024         {
2025           templates = tmpl;
2026           TREE_CHAIN (templates) = NULL_TREE;
2027         }
2028     }
2029
2030   if (templates == NULL_TREE && candidates == NULL_TREE)
2031     {
2032       error ("template-id %qD for %q+D does not match any template "
2033              "declaration", template_id, decl);
2034       if (header_count && header_count != template_count + 1)
2035         inform (input_location, "saw %d %<template<>%>, need %d for "
2036                 "specializing a member function template",
2037                 header_count, template_count + 1);
2038       return error_mark_node;
2039     }
2040   else if ((templates && TREE_CHAIN (templates))
2041            || (candidates && TREE_CHAIN (candidates))
2042            || (templates && candidates))
2043     {
2044       error ("ambiguous template specialization %qD for %q+D",
2045              template_id, decl);
2046       candidates = chainon (candidates, templates);
2047       print_candidates (candidates);
2048       return error_mark_node;
2049     }
2050
2051   /* We have one, and exactly one, match.  */
2052   if (candidates)
2053     {
2054       tree fn = TREE_VALUE (candidates);
2055       *targs_out = copy_node (DECL_TI_ARGS (fn));
2056       /* DECL is a re-declaration or partial instantiation of a template
2057          function.  */
2058       if (TREE_CODE (fn) == TEMPLATE_DECL)
2059         return fn;
2060       /* It was a specialization of an ordinary member function in a
2061          template class.  */
2062       return DECL_TI_TEMPLATE (fn);
2063     }
2064
2065   /* It was a specialization of a template.  */
2066   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2067   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2068     {
2069       *targs_out = copy_node (targs);
2070       SET_TMPL_ARGS_LEVEL (*targs_out,
2071                            TMPL_ARGS_DEPTH (*targs_out),
2072                            TREE_PURPOSE (templates));
2073     }
2074   else
2075     *targs_out = TREE_PURPOSE (templates);
2076   return TREE_VALUE (templates);
2077 }
2078
2079 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2080    but with the default argument values filled in from those in the
2081    TMPL_TYPES.  */
2082
2083 static tree
2084 copy_default_args_to_explicit_spec_1 (tree spec_types,
2085                                       tree tmpl_types)
2086 {
2087   tree new_spec_types;
2088
2089   if (!spec_types)
2090     return NULL_TREE;
2091
2092   if (spec_types == void_list_node)
2093     return void_list_node;
2094
2095   /* Substitute into the rest of the list.  */
2096   new_spec_types =
2097     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2098                                           TREE_CHAIN (tmpl_types));
2099
2100   /* Add the default argument for this parameter.  */
2101   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2102                          TREE_VALUE (spec_types),
2103                          new_spec_types);
2104 }
2105
2106 /* DECL is an explicit specialization.  Replicate default arguments
2107    from the template it specializes.  (That way, code like:
2108
2109      template <class T> void f(T = 3);
2110      template <> void f(double);
2111      void g () { f (); }
2112
2113    works, as required.)  An alternative approach would be to look up
2114    the correct default arguments at the call-site, but this approach
2115    is consistent with how implicit instantiations are handled.  */
2116
2117 static void
2118 copy_default_args_to_explicit_spec (tree decl)
2119 {
2120   tree tmpl;
2121   tree spec_types;
2122   tree tmpl_types;
2123   tree new_spec_types;
2124   tree old_type;
2125   tree new_type;
2126   tree t;
2127   tree object_type = NULL_TREE;
2128   tree in_charge = NULL_TREE;
2129   tree vtt = NULL_TREE;
2130
2131   /* See if there's anything we need to do.  */
2132   tmpl = DECL_TI_TEMPLATE (decl);
2133   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2134   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2135     if (TREE_PURPOSE (t))
2136       break;
2137   if (!t)
2138     return;
2139
2140   old_type = TREE_TYPE (decl);
2141   spec_types = TYPE_ARG_TYPES (old_type);
2142
2143   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2144     {
2145       /* Remove the this pointer, but remember the object's type for
2146          CV quals.  */
2147       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2148       spec_types = TREE_CHAIN (spec_types);
2149       tmpl_types = TREE_CHAIN (tmpl_types);
2150
2151       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2152         {
2153           /* DECL may contain more parameters than TMPL due to the extra
2154              in-charge parameter in constructors and destructors.  */
2155           in_charge = spec_types;
2156           spec_types = TREE_CHAIN (spec_types);
2157         }
2158       if (DECL_HAS_VTT_PARM_P (decl))
2159         {
2160           vtt = spec_types;
2161           spec_types = TREE_CHAIN (spec_types);
2162         }
2163     }
2164
2165   /* Compute the merged default arguments.  */
2166   new_spec_types =
2167     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2168
2169   /* Compute the new FUNCTION_TYPE.  */
2170   if (object_type)
2171     {
2172       if (vtt)
2173         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2174                                          TREE_VALUE (vtt),
2175                                          new_spec_types);
2176
2177       if (in_charge)
2178         /* Put the in-charge parameter back.  */
2179         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2180                                          TREE_VALUE (in_charge),
2181                                          new_spec_types);
2182
2183       new_type = build_method_type_directly (object_type,
2184                                              TREE_TYPE (old_type),
2185                                              new_spec_types);
2186     }
2187   else
2188     new_type = build_function_type (TREE_TYPE (old_type),
2189                                     new_spec_types);
2190   new_type = cp_build_type_attribute_variant (new_type,
2191                                               TYPE_ATTRIBUTES (old_type));
2192   new_type = build_exception_variant (new_type,
2193                                       TYPE_RAISES_EXCEPTIONS (old_type));
2194   TREE_TYPE (decl) = new_type;
2195 }
2196
2197 /* Check to see if the function just declared, as indicated in
2198    DECLARATOR, and in DECL, is a specialization of a function
2199    template.  We may also discover that the declaration is an explicit
2200    instantiation at this point.
2201
2202    Returns DECL, or an equivalent declaration that should be used
2203    instead if all goes well.  Issues an error message if something is
2204    amiss.  Returns error_mark_node if the error is not easily
2205    recoverable.
2206
2207    FLAGS is a bitmask consisting of the following flags:
2208
2209    2: The function has a definition.
2210    4: The function is a friend.
2211
2212    The TEMPLATE_COUNT is the number of references to qualifying
2213    template classes that appeared in the name of the function.  For
2214    example, in
2215
2216      template <class T> struct S { void f(); };
2217      void S<int>::f();
2218
2219    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2220    classes are not counted in the TEMPLATE_COUNT, so that in
2221
2222      template <class T> struct S {};
2223      template <> struct S<int> { void f(); }
2224      template <> void S<int>::f();
2225
2226    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2227    invalid; there should be no template <>.)
2228
2229    If the function is a specialization, it is marked as such via
2230    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2231    is set up correctly, and it is added to the list of specializations
2232    for that template.  */
2233
2234 tree
2235 check_explicit_specialization (tree declarator,
2236                                tree decl,
2237                                int template_count,
2238                                int flags)
2239 {
2240   int have_def = flags & 2;
2241   int is_friend = flags & 4;
2242   int specialization = 0;
2243   int explicit_instantiation = 0;
2244   int member_specialization = 0;
2245   tree ctype = DECL_CLASS_CONTEXT (decl);
2246   tree dname = DECL_NAME (decl);
2247   tmpl_spec_kind tsk;
2248
2249   if (is_friend)
2250     {
2251       if (!processing_specialization)
2252         tsk = tsk_none;
2253       else
2254         tsk = tsk_excessive_parms;
2255     }
2256   else
2257     tsk = current_tmpl_spec_kind (template_count);
2258
2259   switch (tsk)
2260     {
2261     case tsk_none:
2262       if (processing_specialization)
2263         {
2264           specialization = 1;
2265           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2266         }
2267       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2268         {
2269           if (is_friend)
2270             /* This could be something like:
2271
2272                template <class T> void f(T);
2273                class S { friend void f<>(int); }  */
2274             specialization = 1;
2275           else
2276             {
2277               /* This case handles bogus declarations like template <>
2278                  template <class T> void f<int>(); */
2279
2280               error ("template-id %qD in declaration of primary template",
2281                      declarator);
2282               return decl;
2283             }
2284         }
2285       break;
2286
2287     case tsk_invalid_member_spec:
2288       /* The error has already been reported in
2289          check_specialization_scope.  */
2290       return error_mark_node;
2291
2292     case tsk_invalid_expl_inst:
2293       error ("template parameter list used in explicit instantiation");
2294
2295       /* Fall through.  */
2296
2297     case tsk_expl_inst:
2298       if (have_def)
2299         error ("definition provided for explicit instantiation");
2300
2301       explicit_instantiation = 1;
2302       break;
2303
2304     case tsk_excessive_parms:
2305     case tsk_insufficient_parms:
2306       if (tsk == tsk_excessive_parms)
2307         error ("too many template parameter lists in declaration of %qD",
2308                decl);
2309       else if (template_header_count)
2310         error("too few template parameter lists in declaration of %qD", decl);
2311       else
2312         error("explicit specialization of %qD must be introduced by "
2313               "%<template <>%>", decl);
2314
2315       /* Fall through.  */
2316     case tsk_expl_spec:
2317       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2318       if (ctype)
2319         member_specialization = 1;
2320       else
2321         specialization = 1;
2322       break;
2323
2324     case tsk_template:
2325       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2326         {
2327           /* This case handles bogus declarations like template <>
2328              template <class T> void f<int>(); */
2329
2330           if (uses_template_parms (declarator))
2331             error ("function template partial specialization %qD "
2332                    "is not allowed", declarator);
2333           else
2334             error ("template-id %qD in declaration of primary template",
2335                    declarator);
2336           return decl;
2337         }
2338
2339       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2340         /* This is a specialization of a member template, without
2341            specialization the containing class.  Something like:
2342
2343              template <class T> struct S {
2344                template <class U> void f (U);
2345              };
2346              template <> template <class U> void S<int>::f(U) {}
2347
2348            That's a specialization -- but of the entire template.  */
2349         specialization = 1;
2350       break;
2351
2352     default:
2353       gcc_unreachable ();
2354     }
2355
2356   if (specialization || member_specialization)
2357     {
2358       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2359       for (; t; t = TREE_CHAIN (t))
2360         if (TREE_PURPOSE (t))
2361           {
2362             permerror (input_location, 
2363                        "default argument specified in explicit specialization");
2364             break;
2365           }
2366     }
2367
2368   if (specialization || member_specialization || explicit_instantiation)
2369     {
2370       tree tmpl = NULL_TREE;
2371       tree targs = NULL_TREE;
2372
2373       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2374       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2375         {
2376           tree fns;
2377
2378           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2379           if (ctype)
2380             fns = dname;
2381           else
2382             {
2383               /* If there is no class context, the explicit instantiation
2384                  must be at namespace scope.  */
2385               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2386
2387               /* Find the namespace binding, using the declaration
2388                  context.  */
2389               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2390                                            false, true);
2391               if (fns == error_mark_node || !is_overloaded_fn (fns))
2392                 {
2393                   error ("%qD is not a template function", dname);
2394                   fns = error_mark_node;
2395                 }
2396               else
2397                 {
2398                   tree fn = OVL_CURRENT (fns);
2399                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2400                                                 CP_DECL_CONTEXT (fn)))
2401                     error ("%qD is not declared in %qD",
2402                            decl, current_namespace);
2403                 }
2404             }
2405
2406           declarator = lookup_template_function (fns, NULL_TREE);
2407         }
2408
2409       if (declarator == error_mark_node)
2410         return error_mark_node;
2411
2412       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2413         {
2414           if (!explicit_instantiation)
2415             /* A specialization in class scope.  This is invalid,
2416                but the error will already have been flagged by
2417                check_specialization_scope.  */
2418             return error_mark_node;
2419           else
2420             {
2421               /* It's not valid to write an explicit instantiation in
2422                  class scope, e.g.:
2423
2424                    class C { template void f(); }
2425
2426                    This case is caught by the parser.  However, on
2427                    something like:
2428
2429                    template class C { void f(); };
2430
2431                    (which is invalid) we can get here.  The error will be
2432                    issued later.  */
2433               ;
2434             }
2435
2436           return decl;
2437         }
2438       else if (ctype != NULL_TREE
2439                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2440                    IDENTIFIER_NODE))
2441         {
2442           /* Find the list of functions in ctype that have the same
2443              name as the declared function.  */
2444           tree name = TREE_OPERAND (declarator, 0);
2445           tree fns = NULL_TREE;
2446           int idx;
2447
2448           if (constructor_name_p (name, ctype))
2449             {
2450               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2451
2452               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2453                   : !CLASSTYPE_DESTRUCTORS (ctype))
2454                 {
2455                   /* From [temp.expl.spec]:
2456
2457                      If such an explicit specialization for the member
2458                      of a class template names an implicitly-declared
2459                      special member function (clause _special_), the
2460                      program is ill-formed.
2461
2462                      Similar language is found in [temp.explicit].  */
2463                   error ("specialization of implicitly-declared special member function");
2464                   return error_mark_node;
2465                 }
2466
2467               name = is_constructor ? ctor_identifier : dtor_identifier;
2468             }
2469
2470           if (!DECL_CONV_FN_P (decl))
2471             {
2472               idx = lookup_fnfields_1 (ctype, name);
2473               if (idx >= 0)
2474                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2475             }
2476           else
2477             {
2478               VEC(tree,gc) *methods;
2479               tree ovl;
2480
2481               /* For a type-conversion operator, we cannot do a
2482                  name-based lookup.  We might be looking for `operator
2483                  int' which will be a specialization of `operator T'.
2484                  So, we find *all* the conversion operators, and then
2485                  select from them.  */
2486               fns = NULL_TREE;
2487
2488               methods = CLASSTYPE_METHOD_VEC (ctype);
2489               if (methods)
2490                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2491                      VEC_iterate (tree, methods, idx, ovl);
2492                      ++idx)
2493                   {
2494                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2495                       /* There are no more conversion functions.  */
2496                       break;
2497
2498                     /* Glue all these conversion functions together
2499                        with those we already have.  */
2500                     for (; ovl; ovl = OVL_NEXT (ovl))
2501                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2502                   }
2503             }
2504
2505           if (fns == NULL_TREE)
2506             {
2507               error ("no member function %qD declared in %qT", name, ctype);
2508               return error_mark_node;
2509             }
2510           else
2511             TREE_OPERAND (declarator, 0) = fns;
2512         }
2513
2514       /* Figure out what exactly is being specialized at this point.
2515          Note that for an explicit instantiation, even one for a
2516          member function, we cannot tell apriori whether the
2517          instantiation is for a member template, or just a member
2518          function of a template class.  Even if a member template is
2519          being instantiated, the member template arguments may be
2520          elided if they can be deduced from the rest of the
2521          declaration.  */
2522       tmpl = determine_specialization (declarator, decl,
2523                                        &targs,
2524                                        member_specialization,
2525                                        template_count,
2526                                        tsk);
2527
2528       if (!tmpl || tmpl == error_mark_node)
2529         /* We couldn't figure out what this declaration was
2530            specializing.  */
2531         return error_mark_node;
2532       else
2533         {
2534           tree gen_tmpl = most_general_template (tmpl);
2535
2536           if (explicit_instantiation)
2537             {
2538               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2539                  is done by do_decl_instantiation later.  */
2540
2541               int arg_depth = TMPL_ARGS_DEPTH (targs);
2542               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2543
2544               if (arg_depth > parm_depth)
2545                 {
2546                   /* If TMPL is not the most general template (for
2547                      example, if TMPL is a friend template that is
2548                      injected into namespace scope), then there will
2549                      be too many levels of TARGS.  Remove some of them
2550                      here.  */
2551                   int i;
2552                   tree new_targs;
2553
2554                   new_targs = make_tree_vec (parm_depth);
2555                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2556                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2557                       = TREE_VEC_ELT (targs, i);
2558                   targs = new_targs;
2559                 }
2560
2561               return instantiate_template (tmpl, targs, tf_error);
2562             }
2563
2564           /* If we thought that the DECL was a member function, but it
2565              turns out to be specializing a static member function,
2566              make DECL a static member function as well.  */
2567           if (DECL_STATIC_FUNCTION_P (tmpl)
2568               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2569             revert_static_member_fn (decl);
2570
2571           /* If this is a specialization of a member template of a
2572              template class, we want to return the TEMPLATE_DECL, not
2573              the specialization of it.  */
2574           if (tsk == tsk_template)
2575             {
2576               tree result = DECL_TEMPLATE_RESULT (tmpl);
2577               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2578               DECL_INITIAL (result) = NULL_TREE;
2579               if (have_def)
2580                 {
2581                   tree parm;
2582                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2583                   DECL_SOURCE_LOCATION (result)
2584                     = DECL_SOURCE_LOCATION (decl);
2585                   /* We want to use the argument list specified in the
2586                      definition, not in the original declaration.  */
2587                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2588                   for (parm = DECL_ARGUMENTS (result); parm;
2589                        parm = DECL_CHAIN (parm))
2590                     DECL_CONTEXT (parm) = result;
2591                 }
2592               return register_specialization (tmpl, gen_tmpl, targs,
2593                                               is_friend, 0);
2594             }
2595
2596           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2597           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2598
2599           /* Inherit default function arguments from the template
2600              DECL is specializing.  */
2601           copy_default_args_to_explicit_spec (decl);
2602
2603           /* This specialization has the same protection as the
2604              template it specializes.  */
2605           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2606           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2607
2608           /* 7.1.1-1 [dcl.stc]
2609
2610              A storage-class-specifier shall not be specified in an
2611              explicit specialization...
2612
2613              The parser rejects these, so unless action is taken here,
2614              explicit function specializations will always appear with
2615              global linkage.
2616
2617              The action recommended by the C++ CWG in response to C++
2618              defect report 605 is to make the storage class and linkage
2619              of the explicit specialization match the templated function:
2620
2621              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2622            */
2623           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2624             {
2625               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2626               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2627
2628               /* This specialization has the same linkage and visibility as
2629                  the function template it specializes.  */
2630               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2631               if (! TREE_PUBLIC (decl))
2632                 {
2633                   DECL_INTERFACE_KNOWN (decl) = 1;
2634                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2635                 }
2636               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2637               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2638                 {
2639                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2640                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2641                 }
2642             }
2643
2644           /* If DECL is a friend declaration, declared using an
2645              unqualified name, the namespace associated with DECL may
2646              have been set incorrectly.  For example, in:
2647
2648                template <typename T> void f(T);
2649                namespace N {
2650                  struct S { friend void f<int>(int); }
2651                }
2652
2653              we will have set the DECL_CONTEXT for the friend
2654              declaration to N, rather than to the global namespace.  */
2655           if (DECL_NAMESPACE_SCOPE_P (decl))
2656             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2657
2658           if (is_friend && !have_def)
2659             /* This is not really a declaration of a specialization.
2660                It's just the name of an instantiation.  But, it's not
2661                a request for an instantiation, either.  */
2662             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2663           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2664             /* This is indeed a specialization.  In case of constructors
2665                and destructors, we need in-charge and not-in-charge
2666                versions in V3 ABI.  */
2667             clone_function_decl (decl, /*update_method_vec_p=*/0);
2668
2669           /* Register this specialization so that we can find it
2670              again.  */
2671           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2672         }
2673     }
2674
2675   return decl;
2676 }
2677
2678 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2679    parameters.  These are represented in the same format used for
2680    DECL_TEMPLATE_PARMS.  */
2681
2682 int
2683 comp_template_parms (const_tree parms1, const_tree parms2)
2684 {
2685   const_tree p1;
2686   const_tree p2;
2687
2688   if (parms1 == parms2)
2689     return 1;
2690
2691   for (p1 = parms1, p2 = parms2;
2692        p1 != NULL_TREE && p2 != NULL_TREE;
2693        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2694     {
2695       tree t1 = TREE_VALUE (p1);
2696       tree t2 = TREE_VALUE (p2);
2697       int i;
2698
2699       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2700       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2701
2702       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2703         return 0;
2704
2705       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2706         {
2707           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2708           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2709
2710           /* If either of the template parameters are invalid, assume
2711              they match for the sake of error recovery. */
2712           if (parm1 == error_mark_node || parm2 == error_mark_node)
2713             return 1;
2714
2715           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2716             return 0;
2717
2718           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2719               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2720                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2721             continue;
2722           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2723             return 0;
2724         }
2725     }
2726
2727   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2728     /* One set of parameters has more parameters lists than the
2729        other.  */
2730     return 0;
2731
2732   return 1;
2733 }
2734
2735 /* Determine whether PARM is a parameter pack.  */
2736
2737 bool 
2738 template_parameter_pack_p (const_tree parm)
2739 {
2740   /* Determine if we have a non-type template parameter pack.  */
2741   if (TREE_CODE (parm) == PARM_DECL)
2742     return (DECL_TEMPLATE_PARM_P (parm) 
2743             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2744
2745   /* If this is a list of template parameters, we could get a
2746      TYPE_DECL or a TEMPLATE_DECL.  */ 
2747   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2748     parm = TREE_TYPE (parm);
2749
2750   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2751            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2752           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2753 }
2754
2755 /* Determine if T is a function parameter pack.  */
2756
2757 bool
2758 function_parameter_pack_p (const_tree t)
2759 {
2760   if (t && TREE_CODE (t) == PARM_DECL)
2761     return FUNCTION_PARAMETER_PACK_P (t);
2762   return false;
2763 }
2764
2765 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2766    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2767
2768 tree
2769 get_function_template_decl (const_tree primary_func_tmpl_inst)
2770 {
2771   if (! primary_func_tmpl_inst
2772       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2773       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2774     return NULL;
2775
2776   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2777 }
2778
2779 /* Return true iff the function parameter PARAM_DECL was expanded
2780    from the function parameter pack PACK.  */
2781
2782 bool
2783 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2784 {
2785   if (DECL_ARTIFICIAL (param_decl)
2786       || !function_parameter_pack_p (pack))
2787     return false;
2788
2789   /* The parameter pack and its pack arguments have the same
2790      DECL_PARM_INDEX.  */
2791   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2792 }
2793
2794 /* Determine whether ARGS describes a variadic template args list,
2795    i.e., one that is terminated by a template argument pack.  */
2796
2797 static bool 
2798 template_args_variadic_p (tree args)
2799 {
2800   int nargs;
2801   tree last_parm;
2802
2803   if (args == NULL_TREE)
2804     return false;
2805
2806   args = INNERMOST_TEMPLATE_ARGS (args);
2807   nargs = TREE_VEC_LENGTH (args);
2808
2809   if (nargs == 0)
2810     return false;
2811
2812   last_parm = TREE_VEC_ELT (args, nargs - 1);
2813
2814   return ARGUMENT_PACK_P (last_parm);
2815 }
2816
2817 /* Generate a new name for the parameter pack name NAME (an
2818    IDENTIFIER_NODE) that incorporates its */
2819
2820 static tree
2821 make_ith_pack_parameter_name (tree name, int i)
2822 {
2823   /* Munge the name to include the parameter index.  */
2824 #define NUMBUF_LEN 128
2825   char numbuf[NUMBUF_LEN];
2826   char* newname;
2827   int newname_len;
2828
2829   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2830   newname_len = IDENTIFIER_LENGTH (name)
2831                 + strlen (numbuf) + 2;
2832   newname = (char*)alloca (newname_len);
2833   snprintf (newname, newname_len,
2834             "%s#%i", IDENTIFIER_POINTER (name), i);
2835   return get_identifier (newname);
2836 }
2837
2838 /* Return true if T is a primary function
2839    or class template instantiation.  */
2840
2841 bool
2842 primary_template_instantiation_p (const_tree t)
2843 {
2844   if (!t)
2845     return false;
2846
2847   if (TREE_CODE (t) == FUNCTION_DECL)
2848     return DECL_LANG_SPECIFIC (t)
2849            && DECL_TEMPLATE_INSTANTIATION (t)
2850            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2851   else if (CLASS_TYPE_P (t))
2852     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2853            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2854   return false;
2855 }
2856
2857 /* Return true if PARM is a template template parameter.  */
2858
2859 bool
2860 template_template_parameter_p (const_tree parm)
2861 {
2862   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2863 }
2864
2865 /* Return the template parameters of T if T is a
2866    primary template instantiation, NULL otherwise.  */
2867
2868 tree
2869 get_primary_template_innermost_parameters (const_tree t)
2870 {
2871   tree parms = NULL, template_info = NULL;
2872
2873   if ((template_info = get_template_info (t))
2874       && primary_template_instantiation_p (t))
2875     parms = INNERMOST_TEMPLATE_PARMS
2876         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2877
2878   return parms;
2879 }
2880
2881 /* Return the template parameters of the LEVELth level from the full list
2882    of template parameters PARMS.  */
2883
2884 tree
2885 get_template_parms_at_level (tree parms, int level)
2886 {
2887   tree p;
2888   if (!parms
2889       || TREE_CODE (parms) != TREE_LIST
2890       || level > TMPL_PARMS_DEPTH (parms))
2891     return NULL_TREE;
2892
2893   for (p = parms; p; p = TREE_CHAIN (p))
2894     if (TMPL_PARMS_DEPTH (p) == level)
2895       return p;
2896
2897   return NULL_TREE;
2898 }
2899
2900 /* Returns the template arguments of T if T is a template instantiation,
2901    NULL otherwise.  */
2902
2903 tree
2904 get_template_innermost_arguments (const_tree t)
2905 {
2906   tree args = NULL, template_info = NULL;
2907
2908   if ((template_info = get_template_info (t))
2909       && TI_ARGS (template_info))
2910     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2911
2912   return args;
2913 }
2914
2915 /* Return the argument pack elements of T if T is a template argument pack,
2916    NULL otherwise.  */
2917
2918 tree
2919 get_template_argument_pack_elems (const_tree t)
2920 {
2921   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2922       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2923     return NULL;
2924
2925   return ARGUMENT_PACK_ARGS (t);
2926 }
2927
2928 /* Structure used to track the progress of find_parameter_packs_r.  */
2929 struct find_parameter_pack_data 
2930 {
2931   /* TREE_LIST that will contain all of the parameter packs found by
2932      the traversal.  */
2933   tree* parameter_packs;
2934
2935   /* Set of AST nodes that have been visited by the traversal.  */
2936   struct pointer_set_t *visited;
2937 };
2938
2939 /* Identifies all of the argument packs that occur in a template
2940    argument and appends them to the TREE_LIST inside DATA, which is a
2941    find_parameter_pack_data structure. This is a subroutine of
2942    make_pack_expansion and uses_parameter_packs.  */
2943 static tree
2944 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2945 {
2946   tree t = *tp;
2947   struct find_parameter_pack_data* ppd = 
2948     (struct find_parameter_pack_data*)data;
2949   bool parameter_pack_p = false;
2950
2951   /* Identify whether this is a parameter pack or not.  */
2952   switch (TREE_CODE (t))
2953     {
2954     case TEMPLATE_PARM_INDEX:
2955       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2956         parameter_pack_p = true;
2957       break;
2958
2959     case TEMPLATE_TYPE_PARM:
2960     case TEMPLATE_TEMPLATE_PARM:
2961       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2962         parameter_pack_p = true;
2963       break;
2964
2965     case PARM_DECL:
2966       if (FUNCTION_PARAMETER_PACK_P (t))
2967         {
2968           /* We don't want to walk into the type of a PARM_DECL,
2969              because we don't want to see the type parameter pack.  */
2970           *walk_subtrees = 0;
2971           parameter_pack_p = true;
2972         }
2973       break;
2974
2975     default:
2976       /* Not a parameter pack.  */
2977       break;
2978     }
2979
2980   if (parameter_pack_p)
2981     {
2982       /* Add this parameter pack to the list.  */
2983       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2984     }
2985
2986   if (TYPE_P (t))
2987     cp_walk_tree (&TYPE_CONTEXT (t), 
2988                   &find_parameter_packs_r, ppd, ppd->visited);
2989
2990   /* This switch statement will return immediately if we don't find a
2991      parameter pack.  */
2992   switch (TREE_CODE (t)) 
2993     {
2994     case TEMPLATE_PARM_INDEX:
2995       return NULL_TREE;
2996
2997     case BOUND_TEMPLATE_TEMPLATE_PARM:
2998       /* Check the template itself.  */
2999       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3000                     &find_parameter_packs_r, ppd, ppd->visited);
3001       /* Check the template arguments.  */
3002       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3003                     ppd->visited);
3004       *walk_subtrees = 0;
3005       return NULL_TREE;
3006
3007     case TEMPLATE_TYPE_PARM:
3008     case TEMPLATE_TEMPLATE_PARM:
3009       return NULL_TREE;
3010
3011     case PARM_DECL:
3012       return NULL_TREE;
3013
3014     case RECORD_TYPE:
3015       if (TYPE_PTRMEMFUNC_P (t))
3016         return NULL_TREE;
3017       /* Fall through.  */
3018
3019     case UNION_TYPE:
3020     case ENUMERAL_TYPE:
3021       if (TYPE_TEMPLATE_INFO (t))
3022         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3023                       &find_parameter_packs_r, ppd, ppd->visited);
3024
3025       *walk_subtrees = 0;
3026       return NULL_TREE;
3027
3028     case CONSTRUCTOR:
3029     case TEMPLATE_DECL:
3030       cp_walk_tree (&TREE_TYPE (t),
3031                     &find_parameter_packs_r, ppd, ppd->visited);
3032       return NULL_TREE;
3033  
3034     case TYPENAME_TYPE:
3035       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3036                    ppd, ppd->visited);
3037       *walk_subtrees = 0;
3038       return NULL_TREE;
3039       
3040     case TYPE_PACK_EXPANSION:
3041     case EXPR_PACK_EXPANSION:
3042       *walk_subtrees = 0;
3043       return NULL_TREE;
3044
3045     case INTEGER_TYPE:
3046       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3047                     ppd, ppd->visited);
3048       *walk_subtrees = 0;
3049       return NULL_TREE;
3050
3051     case IDENTIFIER_NODE:
3052       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3053                     ppd->visited);
3054       *walk_subtrees = 0;
3055       return NULL_TREE;
3056
3057     default:
3058       return NULL_TREE;
3059     }
3060
3061   return NULL_TREE;
3062 }
3063
3064 /* Determines if the expression or type T uses any parameter packs.  */
3065 bool
3066 uses_parameter_packs (tree t)
3067 {
3068   tree parameter_packs = NULL_TREE;
3069   struct find_parameter_pack_data ppd;
3070   ppd.parameter_packs = &parameter_packs;
3071   ppd.visited = pointer_set_create ();
3072   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3073   pointer_set_destroy (ppd.visited);
3074   return parameter_packs != NULL_TREE;
3075 }
3076
3077 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3078    representation a base-class initializer into a parameter pack
3079    expansion. If all goes well, the resulting node will be an
3080    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3081    respectively.  */
3082 tree 
3083 make_pack_expansion (tree arg)
3084 {
3085   tree result;
3086   tree parameter_packs = NULL_TREE;
3087   bool for_types = false;
3088   struct find_parameter_pack_data ppd;
3089
3090   if (!arg || arg == error_mark_node)
3091     return arg;
3092
3093   if (TREE_CODE (arg) == TREE_LIST)
3094     {
3095       /* The only time we will see a TREE_LIST here is for a base
3096          class initializer.  In this case, the TREE_PURPOSE will be a
3097          _TYPE node (representing the base class expansion we're
3098          initializing) and the TREE_VALUE will be a TREE_LIST
3099          containing the initialization arguments. 
3100
3101          The resulting expansion looks somewhat different from most
3102          expansions. Rather than returning just one _EXPANSION, we
3103          return a TREE_LIST whose TREE_PURPOSE is a
3104          TYPE_PACK_EXPANSION containing the bases that will be
3105          initialized.  The TREE_VALUE will be identical to the
3106          original TREE_VALUE, which is a list of arguments that will
3107          be passed to each base.  We do not introduce any new pack
3108          expansion nodes into the TREE_VALUE (although it is possible
3109          that some already exist), because the TREE_PURPOSE and
3110          TREE_VALUE all need to be expanded together with the same
3111          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3112          resulting TREE_PURPOSE will mention the parameter packs in
3113          both the bases and the arguments to the bases.  */
3114       tree purpose;
3115       tree value;
3116       tree parameter_packs = NULL_TREE;
3117
3118       /* Determine which parameter packs will be used by the base
3119          class expansion.  */
3120       ppd.visited = pointer_set_create ();
3121       ppd.parameter_packs = &parameter_packs;
3122       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3123                     &ppd, ppd.visited);
3124
3125       if (parameter_packs == NULL_TREE)
3126         {
3127           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3128           pointer_set_destroy (ppd.visited);
3129           return error_mark_node;
3130         }
3131
3132       if (TREE_VALUE (arg) != void_type_node)
3133         {
3134           /* Collect the sets of parameter packs used in each of the
3135              initialization arguments.  */
3136           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3137             {
3138               /* Determine which parameter packs will be expanded in this
3139                  argument.  */
3140               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3141                             &ppd, ppd.visited);
3142             }
3143         }
3144
3145       pointer_set_destroy (ppd.visited);
3146
3147       /* Create the pack expansion type for the base type.  */
3148       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3149       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3150       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3151
3152       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3153          they will rarely be compared to anything.  */
3154       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3155
3156       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3157     }
3158
3159   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3160     for_types = true;
3161
3162   /* Build the PACK_EXPANSION_* node.  */
3163   result = for_types
3164      ? cxx_make_type (TYPE_PACK_EXPANSION)
3165      : make_node (EXPR_PACK_EXPANSION);
3166   SET_PACK_EXPANSION_PATTERN (result, arg);
3167   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3168     {
3169       /* Propagate type and const-expression information.  */
3170       TREE_TYPE (result) = TREE_TYPE (arg);
3171       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3172     }
3173   else
3174     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3175        they will rarely be compared to anything.  */
3176     SET_TYPE_STRUCTURAL_EQUALITY (result);
3177
3178   /* Determine which parameter packs will be expanded.  */
3179   ppd.parameter_packs = &parameter_packs;
3180   ppd.visited = pointer_set_create ();
3181   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3182   pointer_set_destroy (ppd.visited);
3183
3184   /* Make sure we found some parameter packs.  */
3185   if (parameter_packs == NULL_TREE)
3186     {
3187       if (TYPE_P (arg))
3188         error ("expansion pattern %<%T%> contains no argument packs", arg);
3189       else
3190         error ("expansion pattern %<%E%> contains no argument packs", arg);
3191       return error_mark_node;
3192     }
3193   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3194
3195   return result;
3196 }
3197
3198 /* Checks T for any "bare" parameter packs, which have not yet been
3199    expanded, and issues an error if any are found. This operation can
3200    only be done on full expressions or types (e.g., an expression
3201    statement, "if" condition, etc.), because we could have expressions like:
3202
3203      foo(f(g(h(args)))...)
3204
3205    where "args" is a parameter pack. check_for_bare_parameter_packs
3206    should not be called for the subexpressions args, h(args),
3207    g(h(args)), or f(g(h(args))), because we would produce erroneous
3208    error messages. 
3209
3210    Returns TRUE and emits an error if there were bare parameter packs,
3211    returns FALSE otherwise.  */
3212 bool 
3213 check_for_bare_parameter_packs (tree t)
3214 {
3215   tree parameter_packs = NULL_TREE;
3216   struct find_parameter_pack_data ppd;
3217
3218   if (!processing_template_decl || !t || t == error_mark_node)
3219     return false;
3220
3221   if (TREE_CODE (t) == TYPE_DECL)
3222     t = TREE_TYPE (t);
3223
3224   ppd.parameter_packs = &parameter_packs;
3225   ppd.visited = pointer_set_create ();
3226   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3227   pointer_set_destroy (ppd.visited);
3228
3229   if (parameter_packs) 
3230     {
3231       error ("parameter packs not expanded with %<...%>:");
3232       while (parameter_packs)
3233         {
3234           tree pack = TREE_VALUE (parameter_packs);
3235           tree name = NULL_TREE;
3236
3237           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3238               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3239             name = TYPE_NAME (pack);
3240           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3241             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3242           else
3243             name = DECL_NAME (pack);
3244
3245           if (name)
3246             inform (input_location, "        %qD", name);
3247           else
3248             inform (input_location, "        <anonymous>");
3249
3250           parameter_packs = TREE_CHAIN (parameter_packs);
3251         }
3252
3253       return true;
3254     }
3255
3256   return false;
3257 }
3258
3259 /* Expand any parameter packs that occur in the template arguments in
3260    ARGS.  */
3261 tree
3262 expand_template_argument_pack (tree args)
3263 {
3264   tree result_args = NULL_TREE;
3265   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3266   int num_result_args = -1;
3267   int non_default_args_count = -1;
3268
3269   /* First, determine if we need to expand anything, and the number of
3270      slots we'll need.  */
3271   for (in_arg = 0; in_arg < nargs; ++in_arg)
3272     {
3273       tree arg = TREE_VEC_ELT (args, in_arg);
3274       if (arg == NULL_TREE)
3275         return args;
3276       if (ARGUMENT_PACK_P (arg))
3277         {
3278           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3279           if (num_result_args < 0)
3280             num_result_args = in_arg + num_packed;
3281           else
3282             num_result_args += num_packed;
3283         }
3284       else
3285         {
3286           if (num_result_args >= 0)
3287             num_result_args++;
3288         }
3289     }
3290
3291   /* If no expansion is necessary, we're done.  */
3292   if (num_result_args < 0)
3293     return args;
3294
3295   /* Expand arguments.  */
3296   result_args = make_tree_vec (num_result_args);
3297   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3298     non_default_args_count =
3299       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3300   for (in_arg = 0; in_arg < nargs; ++in_arg)
3301     {
3302       tree arg = TREE_VEC_ELT (args, in_arg);
3303       if (ARGUMENT_PACK_P (arg))
3304         {
3305           tree packed = ARGUMENT_PACK_ARGS (arg);
3306           int i, num_packed = TREE_VEC_LENGTH (packed);
3307           for (i = 0; i < num_packed; ++i, ++out_arg)
3308             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3309           if (non_default_args_count > 0)
3310             non_default_args_count += num_packed;
3311         }
3312       else
3313         {
3314           TREE_VEC_ELT (result_args, out_arg) = arg;
3315           ++out_arg;
3316         }
3317     }
3318   if (non_default_args_count >= 0)
3319     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3320   return result_args;
3321 }
3322
3323 /* Checks if DECL shadows a template parameter.
3324
3325    [temp.local]: A template-parameter shall not be redeclared within its
3326    scope (including nested scopes).
3327
3328    Emits an error and returns TRUE if the DECL shadows a parameter,
3329    returns FALSE otherwise.  */
3330
3331 bool
3332 check_template_shadow (tree decl)
3333 {
3334   tree olddecl;
3335
3336   /* If we're not in a template, we can't possibly shadow a template
3337      parameter.  */
3338   if (!current_template_parms)
3339     return true;
3340
3341   /* Figure out what we're shadowing.  */
3342   if (TREE_CODE (decl) == OVERLOAD)
3343     decl = OVL_CURRENT (decl);
3344   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3345
3346   /* If there's no previous binding for this name, we're not shadowing
3347      anything, let alone a template parameter.  */
3348   if (!olddecl)
3349     return true;
3350
3351   /* If we're not shadowing a template parameter, we're done.  Note
3352      that OLDDECL might be an OVERLOAD (or perhaps even an
3353      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3354      node.  */
3355   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3356     return true;
3357
3358   /* We check for decl != olddecl to avoid bogus errors for using a
3359      name inside a class.  We check TPFI to avoid duplicate errors for
3360      inline member templates.  */
3361   if (decl == olddecl
3362       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3363     return true;
3364
3365   error ("declaration of %q+#D", decl);
3366   error (" shadows template parm %q+#D", olddecl);
3367   return false;
3368 }
3369
3370 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3371    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3372    template parameters.  */
3373
3374 static tree
3375 build_template_parm_index (int index,
3376                            int level,
3377                            int orig_level,
3378                            int num_siblings,
3379                            tree decl,
3380                            tree type)
3381 {
3382   tree t = make_node (TEMPLATE_PARM_INDEX);
3383   TEMPLATE_PARM_IDX (t) = index;
3384   TEMPLATE_PARM_LEVEL (t) = level;
3385   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3386   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3387   TEMPLATE_PARM_DECL (t) = decl;
3388   TREE_TYPE (t) = type;
3389   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3390   TREE_READONLY (t) = TREE_READONLY (decl);
3391
3392   return t;
3393 }
3394
3395 /* Find the canonical type parameter for the given template type
3396    parameter.  Returns the canonical type parameter, which may be TYPE
3397    if no such parameter existed.  */
3398
3399 static tree
3400 canonical_type_parameter (tree type)
3401 {
3402   tree list;
3403   int idx = TEMPLATE_TYPE_IDX (type);
3404   if (!canonical_template_parms)
3405     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3406
3407   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3408     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3409
3410   list = VEC_index (tree, canonical_template_parms, idx);
3411   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3412     list = TREE_CHAIN (list);
3413
3414   if (list)
3415     return TREE_VALUE (list);
3416   else
3417     {
3418       VEC_replace(tree, canonical_template_parms, idx,
3419                   tree_cons (NULL_TREE, type, 
3420                              VEC_index (tree, canonical_template_parms, idx)));
3421       return type;
3422     }
3423 }
3424
3425 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3426    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3427    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3428    new one is created.  */
3429
3430 static tree
3431 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3432                             tsubst_flags_t complain)
3433 {
3434   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3435       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3436           != TEMPLATE_PARM_LEVEL (index) - levels)
3437       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3438     {
3439       tree orig_decl = TEMPLATE_PARM_DECL (index);
3440       tree decl, t;
3441
3442       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3443                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3444       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3445       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3446       DECL_ARTIFICIAL (decl) = 1;
3447       SET_DECL_TEMPLATE_PARM_P (decl);
3448
3449       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3450                                      TEMPLATE_PARM_LEVEL (index) - levels,
3451                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3452                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3453                                      decl, type);
3454       TEMPLATE_PARM_DESCENDANTS (index) = t;
3455       TEMPLATE_PARM_PARAMETER_PACK (t) 
3456         = TEMPLATE_PARM_PARAMETER_PACK (index);
3457
3458         /* Template template parameters need this.  */
3459       if (TREE_CODE (decl) == TEMPLATE_DECL)
3460         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3461           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3462            args, complain);
3463     }
3464
3465   return TEMPLATE_PARM_DESCENDANTS (index);
3466 }
3467
3468 /* Process information from new template parameter PARM and append it
3469    to the LIST being built.  This new parameter is a non-type
3470    parameter iff IS_NON_TYPE is true. This new parameter is a
3471    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3472    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3473    parameter list PARM belongs to. This is used used to create a
3474    proper canonical type for the type of PARM that is to be created,
3475    iff PARM is a type.  If the size is not known, this parameter shall
3476    be set to 0.  */
3477
3478 tree
3479 process_template_parm (tree list, location_t parm_loc, tree parm,
3480                        bool is_non_type, bool is_parameter_pack,
3481                        unsigned num_template_parms)
3482 {
3483   tree decl = 0;
3484   tree defval;
3485   tree err_parm_list;
3486   int idx = 0;
3487
3488   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3489   defval = TREE_PURPOSE (parm);
3490
3491   if (list)
3492     {
3493       tree p = tree_last (list);
3494
3495       if (p && TREE_VALUE (p) != error_mark_node)
3496         {
3497           p = TREE_VALUE (p);
3498           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3499             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3500           else
3501             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3502         }
3503
3504       ++idx;
3505     }
3506   else
3507     idx = 0;
3508
3509   if (is_non_type)
3510     {
3511       parm = TREE_VALUE (parm);
3512
3513       SET_DECL_TEMPLATE_PARM_P (parm);
3514
3515       if (TREE_TYPE (parm) == error_mark_node)
3516         {
3517           err_parm_list = build_tree_list (defval, parm);
3518           TREE_VALUE (err_parm_list) = error_mark_node;
3519            return chainon (list, err_parm_list);
3520         }
3521       else
3522       {
3523         /* [temp.param]
3524
3525            The top-level cv-qualifiers on the template-parameter are
3526            ignored when determining its type.  */
3527         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3528         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3529           {
3530             err_parm_list = build_tree_list (defval, parm);
3531             TREE_VALUE (err_parm_list) = error_mark_node;
3532              return chainon (list, err_parm_list);
3533           }
3534
3535         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3536           {
3537             /* This template parameter is not a parameter pack, but it
3538                should be. Complain about "bare" parameter packs.  */
3539             check_for_bare_parameter_packs (TREE_TYPE (parm));
3540             
3541             /* Recover by calling this a parameter pack.  */
3542             is_parameter_pack = true;
3543           }
3544       }
3545
3546       /* A template parameter is not modifiable.  */
3547       TREE_CONSTANT (parm) = 1;
3548       TREE_READONLY (parm) = 1;
3549       decl = build_decl (parm_loc,
3550                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3551       TREE_CONSTANT (decl) = 1;
3552       TREE_READONLY (decl) = 1;
3553       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3554         = build_template_parm_index (idx, processing_template_decl,
3555                                      processing_template_decl,
3556                                      num_template_parms,
3557                                      decl, TREE_TYPE (parm));
3558
3559       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3560         = is_parameter_pack;
3561     }
3562   else
3563     {
3564       tree t;
3565       parm = TREE_VALUE (TREE_VALUE (parm));
3566
3567       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3568         {
3569           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3570           /* This is for distinguishing between real templates and template
3571              template parameters */
3572           TREE_TYPE (parm) = t;
3573           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3574           decl = parm;
3575         }
3576       else
3577         {
3578           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3579           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3580           decl = build_decl (parm_loc,
3581                              TYPE_DECL, parm, t);
3582         }
3583
3584       TYPE_NAME (t) = decl;
3585       TYPE_STUB_DECL (t) = decl;
3586       parm = decl;
3587       TEMPLATE_TYPE_PARM_INDEX (t)
3588         = build_template_parm_index (idx, processing_template_decl,
3589                                      processing_template_decl,
3590                                      num_template_parms,
3591                                      decl, TREE_TYPE (parm));
3592       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3593       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3594     }
3595   DECL_ARTIFICIAL (decl) = 1;
3596   SET_DECL_TEMPLATE_PARM_P (decl);
3597   pushdecl (decl);
3598   parm = build_tree_list (defval, parm);
3599   return chainon (list, parm);
3600 }
3601
3602 /* The end of a template parameter list has been reached.  Process the
3603    tree list into a parameter vector, converting each parameter into a more
3604    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3605    as PARM_DECLs.  */
3606
3607 tree
3608 end_template_parm_list (tree parms)
3609 {
3610   int nparms;
3611   tree parm, next;
3612   tree saved_parmlist = make_tree_vec (list_length (parms));
3613
3614   current_template_parms
3615     = tree_cons (size_int (processing_template_decl),
3616                  saved_parmlist, current_template_parms);
3617
3618   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3619     {
3620       next = TREE_CHAIN (parm);
3621       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3622       TREE_CHAIN (parm) = NULL_TREE;
3623     }
3624
3625   --processing_template_parmlist;
3626
3627   return saved_parmlist;
3628 }
3629
3630 /* Create a new type almost identical to TYPE but which has the
3631    following differences:
3632
3633      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3634      template sibling parameters of T.
3635
3636      2/ T has a new canonical type that matches the new number
3637      of sibling parms.
3638
3639      3/ From now on, T is going to be what lookups referring to the
3640      name of TYPE will return. No lookup should return TYPE anymore.
3641
3642    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3643
3644    This is a subroutine of fixup_template_parms.  */
3645
3646 static tree
3647 fixup_template_type_parm_type (tree type, int num_parms)
3648 {
3649   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3650   tree t;
3651   /* This is the decl which name is inserted into the symbol table for
3652      the template parm type. So whenever we lookup the type name, this
3653      is the DECL we get.  */
3654   tree decl;
3655
3656   /* Do not fix up the type twice.  */
3657   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3658     return type;
3659
3660   t = copy_type (type);
3661   decl = TYPE_NAME (t);
3662
3663   TYPE_MAIN_VARIANT (t) = t;
3664   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3665   TYPE_POINTER_TO (t) = 0;
3666   TYPE_REFERENCE_TO (t) = 0;
3667
3668   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3669                                    TEMPLATE_PARM_LEVEL (orig_idx),
3670                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3671                                    num_parms,
3672                                    decl, t);
3673   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3674   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3675   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3676
3677   TYPE_STUB_DECL (t) = decl;
3678   TEMPLATE_TYPE_DECL (t) = decl;
3679   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3680     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3681
3682   /* Update the type associated to the type name stored in the symbol
3683      table. Now, whenever the type name is looked up, the resulting
3684      type is properly fixed up.  */
3685   TREE_TYPE (decl) = t;
3686
3687   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3688
3689   return t;
3690 }
3691
3692 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3693    identical to I, but that is fixed up as to:
3694
3695    1/ carry the number of sibling parms (NUM_PARMS) of the template
3696    parm represented by I.
3697
3698    2/ replace all references to template parm types declared before I
3699    (in the same template parm list as I) by references to template
3700    parm types contained in ARGS. ARGS should contain the list of
3701    template parms that have been fixed up so far, in a form suitable
3702    to be passed to tsubst.
3703
3704    This is a subroutine of fixup_template_parms.  */
3705
3706 static tree
3707 fixup_template_parm_index (tree i, tree args, int num_parms)
3708 {
3709   tree index, decl, type;
3710
3711   if (i == NULL_TREE
3712       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3713       /* Do not fix up the index twice.  */
3714       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3715     return i;
3716
3717   decl = TEMPLATE_PARM_DECL (i);
3718   type = TREE_TYPE (decl);
3719
3720   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3721                                      TEMPLATE_PARM_LEVEL (i),
3722                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3723                                      num_parms,
3724                                      decl, type);
3725
3726   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3727   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3728
3729   type = tsubst (type, args, tf_none, NULL_TREE);
3730   
3731   TREE_TYPE (decl) = type;
3732   TREE_TYPE (index) = type;
3733
3734   return index;
3735 }
3736
3737 /* 
3738    This is a subroutine of fixup_template_parms.
3739
3740    It computes the canonical type of the type of the template
3741    parameter PARM_DESC and update all references to that type so that
3742    they use the newly computed canonical type. No access check is
3743    performed during the fixup. PARM_DESC is a TREE_LIST which
3744    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3745    default argument of the template parm if any. IDX is the index of
3746    the template parameter, starting at 0. NUM_PARMS is the number of
3747    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3748    TREE_VEC containing the full set of template parameters in a form
3749    suitable to be passed to substs functions as their ARGS
3750    argument. This is what current_template_args returns for a given
3751    template. The innermost vector of args in ARGLIST is the set of
3752    template parms that have been fixed up so far. This function adds
3753    the fixed up parameter into that vector.  */
3754
3755 static void
3756 fixup_template_parm (tree parm_desc,
3757                      int idx,
3758                      int num_parms,
3759                      tree arglist)
3760 {
3761   tree parm = TREE_VALUE (parm_desc);
3762   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3763
3764   push_deferring_access_checks (dk_no_check);
3765
3766   if (TREE_CODE (parm) == TYPE_DECL)
3767     {
3768       /* PARM is a template type parameter. Fix up its type, add
3769          the fixed-up template parm to the vector of fixed-up
3770          template parms so far, and substitute the fixed-up
3771          template parms into the default argument of this
3772          parameter.  */
3773       tree t =
3774         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3775       TREE_TYPE (parm) = t;
3776
3777       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3778     }
3779   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3780     {
3781       /* PARM is a template template parameter. This is going to
3782          be interesting.  */
3783       tree tparms, targs, innermost_args, t;
3784       int j;
3785
3786       /* First, fix up the parms of the template template parm
3787          because the parms are involved in defining the new canonical
3788          type of the template template parm.  */
3789
3790       /* So we need to substitute the template parm types that have
3791          been fixed up so far into the template parms of this template
3792          template parm. E.g, consider this:
3793
3794          template<class T, template<T u> class TT> class S;
3795
3796          In this case we want to substitute T into the
3797          template parameters of TT.
3798
3799          So let's walk the template parms of PARM here, and
3800          tsubst ARGLIST into into each of the template
3801          parms.   */
3802
3803       /* For this substitution we need to build the full set of
3804          template parameters and use that as arguments for the
3805          tsubsting function.  */
3806       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3807
3808       /* This will contain the innermost parms of PARM into which
3809          we have substituted so far.  */
3810       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3811       targs = add_to_template_args (arglist, innermost_args);
3812       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3813         {
3814           tree parameter;
3815
3816           parameter = TREE_VEC_ELT (tparms, j);
3817
3818           /* INNERMOST_ARGS needs to have at least the same number
3819              of elements as the index PARAMETER, ortherwise
3820              tsubsting into PARAMETER will result in partially
3821              instantiating it, reducing its tempate parm
3822              level. Let's tactically fill INNERMOST_ARGS for that
3823              purpose.  */
3824           TREE_VEC_ELT (innermost_args, j) =
3825             template_parm_to_arg (parameter);
3826
3827           fixup_template_parm (parameter, j,
3828                                TREE_VEC_LENGTH (tparms),
3829                                targs);
3830         }
3831
3832       /* Now fix up the type of the template template parm.  */
3833
3834       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3835       TREE_TYPE (parm) = t;
3836
3837       TREE_VEC_ELT (fixedup_args, idx) =
3838         template_parm_to_arg (parm_desc);
3839     }
3840   else if (TREE_CODE (parm) == PARM_DECL)
3841     {
3842       /* PARM is a non-type template parameter. We need to:
3843
3844        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3845        proper number of sibling parameters.
3846
3847        * Make lookups of the template parameter return a reference
3848        to the fixed-up index. No lookup should return references
3849        to the former index anymore.
3850
3851        * Substitute the template parms that got fixed up so far
3852
3853        * into the type of PARM.  */
3854
3855       tree index = DECL_INITIAL (parm);
3856
3857       /* PUSHED_DECL is the decl added to the symbol table with
3858          the name of the parameter. E,g:
3859              
3860          template<class T, T u> //#0
3861          auto my_function(T t) -> decltype(u); //#1
3862
3863          Here, when looking up u at //#1, we get the decl of u
3864          resulting from the declaration in #0. This is what
3865          PUSHED_DECL is. We need to replace the reference to the
3866          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3867          fixed-up TEMPLATE_PARM_INDEX.  */
3868       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3869
3870       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3871          fixup the type of PUSHED_DECL as well and luckily
3872          fixup_template_parm_index does it for us too.  */
3873       tree fixed_up_index =
3874         fixup_template_parm_index (index, arglist, num_parms);
3875
3876       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3877
3878       /* Add this fixed up PARM to the template parms we've fixed
3879          up so far and use that to substitute the fixed-up
3880          template parms into the type of PARM.  */
3881       TREE_VEC_ELT (fixedup_args, idx) =
3882         template_parm_to_arg (parm_desc);
3883       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3884                                  tf_none, NULL_TREE);
3885     }
3886
3887   TREE_PURPOSE (parm_desc) =
3888     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3889                          arglist, tf_none, parm);
3890
3891   pop_deferring_access_checks ();
3892 }
3893
3894 /* Walk the current template parms and properly compute the canonical
3895    types of the dependent types created during
3896    cp_parser_template_parameter_list.  */
3897
3898 void
3899 fixup_template_parms (void)
3900 {
3901   tree arglist;
3902   tree parameter_vec;
3903   tree fixedup_args;
3904   int i, num_parms;
3905
3906   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3907   if (parameter_vec == NULL_TREE)
3908     return;
3909
3910   num_parms = TREE_VEC_LENGTH (parameter_vec);
3911
3912   /* This vector contains the current innermost template parms that
3913      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3914      to be passed to tsubst* functions as their ARGS argument.  */
3915   fixedup_args = make_tree_vec (num_parms);
3916
3917   /* This vector contains the full set of template parms in a form
3918      suitable to be passed to substs functions as their ARGS
3919      argument.  */
3920   arglist = current_template_args ();
3921   arglist = add_outermost_template_args (arglist, fixedup_args);
3922
3923   /* Let's do the proper fixup now.  */
3924   for (i = 0; i < num_parms; ++i)
3925     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3926                          i, num_parms, arglist);
3927 }
3928
3929 /* end_template_decl is called after a template declaration is seen.  */
3930
3931 void
3932 end_template_decl (void)
3933 {
3934   reset_specialization ();
3935
3936   if (! processing_template_decl)
3937     return;
3938
3939   /* This matches the pushlevel in begin_template_parm_list.  */
3940   finish_scope ();
3941
3942   --processing_template_decl;
3943   current_template_parms = TREE_CHAIN (current_template_parms);
3944 }
3945
3946 /* Takes a TREE_LIST representing a template parameter and convert it
3947    into an argument suitable to be passed to the type substitution
3948    functions.  Note that If the TREE_LIST contains an error_mark
3949    node, the returned argument is error_mark_node.  */
3950
3951 static tree
3952 template_parm_to_arg (tree t)
3953 {
3954
3955   if (t == NULL_TREE
3956       || TREE_CODE (t) != TREE_LIST)
3957     return t;
3958
3959   if (error_operand_p (TREE_VALUE (t)))
3960     return error_mark_node;
3961
3962   t = TREE_VALUE (t);
3963
3964   if (TREE_CODE (t) == TYPE_DECL
3965       || TREE_CODE (t) == TEMPLATE_DECL)
3966     {
3967       t = TREE_TYPE (t);
3968
3969       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3970         {
3971           /* Turn this argument into a TYPE_ARGUMENT_PACK
3972              with a single element, which expands T.  */
3973           tree vec = make_tree_vec (1);
3974 #ifdef ENABLE_CHECKING
3975           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3976             (vec, TREE_VEC_LENGTH (vec));
3977 #endif
3978           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3979
3980           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3981           SET_ARGUMENT_PACK_ARGS (t, vec);
3982         }
3983     }
3984   else
3985     {
3986       t = DECL_INITIAL (t);
3987
3988       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3989         {
3990           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3991              with a single element, which expands T.  */
3992           tree vec = make_tree_vec (1);
3993           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3994 #ifdef ENABLE_CHECKING
3995           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3996             (vec, TREE_VEC_LENGTH (vec));
3997 #endif
3998           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3999
4000           t  = make_node (NONTYPE_ARGUMENT_PACK);
4001           SET_ARGUMENT_PACK_ARGS (t, vec);
4002           TREE_TYPE (t) = type;
4003         }
4004     }
4005   return t;
4006 }
4007
4008 /* Within the declaration of a template, return all levels of template
4009    parameters that apply.  The template parameters are represented as
4010    a TREE_VEC, in the form documented in cp-tree.h for template
4011    arguments.  */
4012
4013 static tree
4014 current_template_args (void)
4015 {
4016   tree header;
4017   tree args = NULL_TREE;
4018   int length = TMPL_PARMS_DEPTH (current_template_parms);
4019   int l = length;
4020
4021   /* If there is only one level of template parameters, we do not
4022      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4023      TREE_VEC containing the arguments.  */
4024   if (length > 1)
4025     args = make_tree_vec (length);
4026
4027   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4028     {
4029       tree a = copy_node (TREE_VALUE (header));
4030       int i;
4031
4032       TREE_TYPE (a) = NULL_TREE;
4033       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4034         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4035
4036 #ifdef ENABLE_CHECKING
4037       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4038 #endif
4039
4040       if (length > 1)
4041         TREE_VEC_ELT (args, --l) = a;
4042       else
4043         args = a;
4044     }
4045
4046     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4047       /* This can happen for template parms of a template template
4048          parameter, e.g:
4049
4050          template<template<class T, class U> class TT> struct S;
4051
4052          Consider the level of the parms of TT; T and U both have
4053          level 2; TT has no template parm of level 1. So in this case
4054          the first element of full_template_args is NULL_TREE. If we
4055          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4056          of 2. This will make tsubst wrongly consider that T and U
4057          have level 1. Instead, let's create a dummy vector as the
4058          first element of full_template_args so that TMPL_ARG_DEPTH
4059          returns the correct depth for args.  */
4060       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4061   return args;
4062 }
4063
4064 /* Update the declared TYPE by doing any lookups which were thought to be
4065    dependent, but are not now that we know the SCOPE of the declarator.  */
4066
4067 tree
4068 maybe_update_decl_type (tree orig_type, tree scope)
4069 {
4070   tree type = orig_type;
4071
4072   if (type == NULL_TREE)
4073     return type;
4074
4075   if (TREE_CODE (orig_type) == TYPE_DECL)
4076     type = TREE_TYPE (type);
4077
4078   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4079       && dependent_type_p (type)
4080       /* Don't bother building up the args in this case.  */
4081       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4082     {
4083       /* tsubst in the args corresponding to the template parameters,
4084          including auto if present.  Most things will be unchanged, but
4085          make_typename_type and tsubst_qualified_id will resolve
4086          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4087       tree args = current_template_args ();
4088       tree auto_node = type_uses_auto (type);
4089       tree pushed;
4090       if (auto_node)
4091         {
4092           tree auto_vec = make_tree_vec (1);
4093           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4094           args = add_to_template_args (args, auto_vec);
4095         }
4096       pushed = push_scope (scope);
4097       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4098       if (pushed)
4099         pop_scope (scope);
4100     }
4101
4102   if (type == error_mark_node)
4103     return orig_type;
4104
4105   if (TREE_CODE (orig_type) == TYPE_DECL)
4106     {
4107       if (same_type_p (type, TREE_TYPE (orig_type)))
4108         type = orig_type;
4109       else
4110         type = TYPE_NAME (type);
4111     }
4112   return type;
4113 }
4114
4115 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4116    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4117    a member template.  Used by push_template_decl below.  */
4118
4119 static tree
4120 build_template_decl (tree decl, tree parms, bool member_template_p)
4121 {
4122   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4123   DECL_TEMPLATE_PARMS (tmpl) = parms;
4124   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4125   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4126   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4127
4128   return tmpl;
4129 }
4130
4131 struct template_parm_data
4132 {
4133   /* The level of the template parameters we are currently
4134      processing.  */
4135   int level;
4136
4137   /* The index of the specialization argument we are currently
4138      processing.  */
4139   int current_arg;
4140
4141   /* An array whose size is the number of template parameters.  The
4142      elements are nonzero if the parameter has been used in any one
4143      of the arguments processed so far.  */
4144   int* parms;
4145
4146   /* An array whose size is the number of template arguments.  The
4147      elements are nonzero if the argument makes use of template
4148      parameters of this level.  */
4149   int* arg_uses_template_parms;
4150 };
4151
4152 /* Subroutine of push_template_decl used to see if each template
4153    parameter in a partial specialization is used in the explicit
4154    argument list.  If T is of the LEVEL given in DATA (which is
4155    treated as a template_parm_data*), then DATA->PARMS is marked
4156    appropriately.  */
4157
4158 static int
4159 mark_template_parm (tree t, void* data)
4160 {
4161   int level;
4162   int idx;
4163   struct template_parm_data* tpd = (struct template_parm_data*) data;
4164
4165   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4166     {
4167       level = TEMPLATE_PARM_LEVEL (t);
4168       idx = TEMPLATE_PARM_IDX (t);
4169     }
4170   else
4171     {
4172       level = TEMPLATE_TYPE_LEVEL (t);
4173       idx = TEMPLATE_TYPE_IDX (t);
4174     }
4175
4176   if (level == tpd->level)
4177     {
4178       tpd->parms[idx] = 1;
4179       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4180     }
4181
4182   /* Return zero so that for_each_template_parm will continue the
4183      traversal of the tree; we want to mark *every* template parm.  */
4184   return 0;
4185 }
4186
4187 /* Process the partial specialization DECL.  */
4188
4189 static tree
4190 process_partial_specialization (tree decl)
4191 {
4192   tree type = TREE_TYPE (decl);
4193   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4194   tree specargs = CLASSTYPE_TI_ARGS (type);
4195   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4196   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4197   tree inner_parms;
4198   tree inst;
4199   int nargs = TREE_VEC_LENGTH (inner_args);
4200   int ntparms;
4201   int  i;
4202   bool did_error_intro = false;
4203   struct template_parm_data tpd;
4204   struct template_parm_data tpd2;
4205
4206   gcc_assert (current_template_parms);
4207
4208   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4209   ntparms = TREE_VEC_LENGTH (inner_parms);
4210
4211   /* We check that each of the template parameters given in the
4212      partial specialization is used in the argument list to the
4213      specialization.  For example:
4214
4215        template <class T> struct S;
4216        template <class T> struct S<T*>;
4217
4218      The second declaration is OK because `T*' uses the template
4219      parameter T, whereas
4220
4221        template <class T> struct S<int>;
4222
4223      is no good.  Even trickier is:
4224
4225        template <class T>
4226        struct S1
4227        {
4228           template <class U>
4229           struct S2;
4230           template <class U>
4231           struct S2<T>;
4232        };
4233
4234      The S2<T> declaration is actually invalid; it is a
4235      full-specialization.  Of course,
4236
4237           template <class U>
4238           struct S2<T (*)(U)>;
4239
4240      or some such would have been OK.  */
4241   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4242   tpd.parms = XALLOCAVEC (int, ntparms);
4243   memset (tpd.parms, 0, sizeof (int) * ntparms);
4244
4245   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4246   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4247   for (i = 0; i < nargs; ++i)
4248     {
4249       tpd.current_arg = i;
4250       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4251                               &mark_template_parm,
4252                               &tpd,
4253                               NULL,
4254                               /*include_nondeduced_p=*/false);
4255     }
4256   for (i = 0; i < ntparms; ++i)
4257     if (tpd.parms[i] == 0)
4258       {
4259         /* One of the template parms was not used in the
4260            specialization.  */
4261         if (!did_error_intro)
4262           {
4263             error ("template parameters not used in partial specialization:");
4264             did_error_intro = true;
4265           }
4266
4267         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4268       }
4269
4270   if (did_error_intro)
4271     return error_mark_node;
4272
4273   /* [temp.class.spec]
4274
4275      The argument list of the specialization shall not be identical to
4276      the implicit argument list of the primary template.  */
4277   if (comp_template_args
4278       (inner_args,
4279        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4280                                                    (maintmpl)))))
4281     error ("partial specialization %qT does not specialize any template arguments", type);
4282
4283   /* [temp.class.spec]
4284
4285      A partially specialized non-type argument expression shall not
4286      involve template parameters of the partial specialization except
4287      when the argument expression is a simple identifier.
4288
4289      The type of a template parameter corresponding to a specialized
4290      non-type argument shall not be dependent on a parameter of the
4291      specialization. 
4292
4293      Also, we verify that pack expansions only occur at the
4294      end of the argument list.  */
4295   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4296   tpd2.parms = 0;
4297   for (i = 0; i < nargs; ++i)
4298     {
4299       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4300       tree arg = TREE_VEC_ELT (inner_args, i);
4301       tree packed_args = NULL_TREE;
4302       int j, len = 1;
4303
4304       if (ARGUMENT_PACK_P (arg))
4305         {
4306           /* Extract the arguments from the argument pack. We'll be
4307              iterating over these in the following loop.  */
4308           packed_args = ARGUMENT_PACK_ARGS (arg);
4309           len = TREE_VEC_LENGTH (packed_args);
4310         }
4311
4312       for (j = 0; j < len; j++)
4313         {
4314           if (packed_args)
4315             /* Get the Jth argument in the parameter pack.  */
4316             arg = TREE_VEC_ELT (packed_args, j);
4317
4318           if (PACK_EXPANSION_P (arg))
4319             {
4320               /* Pack expansions must come at the end of the
4321                  argument list.  */
4322               if ((packed_args && j < len - 1)
4323                   || (!packed_args && i < nargs - 1))
4324                 {
4325                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4326                     error ("parameter pack argument %qE must be at the "
4327                            "end of the template argument list", arg);
4328                   else
4329                     error ("parameter pack argument %qT must be at the "
4330                            "end of the template argument list", arg);
4331                 }
4332             }
4333
4334           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4335             /* We only care about the pattern.  */
4336             arg = PACK_EXPANSION_PATTERN (arg);
4337
4338           if (/* These first two lines are the `non-type' bit.  */
4339               !TYPE_P (arg)
4340               && TREE_CODE (arg) != TEMPLATE_DECL
4341               /* This next line is the `argument expression is not just a
4342                  simple identifier' condition and also the `specialized
4343                  non-type argument' bit.  */
4344               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4345             {
4346               if ((!packed_args && tpd.arg_uses_template_parms[i])
4347                   || (packed_args && uses_template_parms (arg)))
4348                 error ("template argument %qE involves template parameter(s)",
4349                        arg);
4350               else 
4351                 {
4352                   /* Look at the corresponding template parameter,
4353                      marking which template parameters its type depends
4354                      upon.  */
4355                   tree type = TREE_TYPE (parm);
4356
4357                   if (!tpd2.parms)
4358                     {
4359                       /* We haven't yet initialized TPD2.  Do so now.  */
4360                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4361                       /* The number of parameters here is the number in the
4362                          main template, which, as checked in the assertion
4363                          above, is NARGS.  */
4364                       tpd2.parms = XALLOCAVEC (int, nargs);
4365                       tpd2.level = 
4366                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4367                     }
4368
4369                   /* Mark the template parameters.  But this time, we're
4370                      looking for the template parameters of the main
4371                      template, not in the specialization.  */
4372                   tpd2.current_arg = i;
4373                   tpd2.arg_uses_template_parms[i] = 0;
4374                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4375                   for_each_template_parm (type,
4376                                           &mark_template_parm,
4377                                           &tpd2,
4378                                           NULL,
4379                                           /*include_nondeduced_p=*/false);
4380
4381                   if (tpd2.arg_uses_template_parms [i])
4382                     {
4383                       /* The type depended on some template parameters.
4384                          If they are fully specialized in the
4385                          specialization, that's OK.  */
4386                       int j;
4387                       int count = 0;
4388                       for (j = 0; j < nargs; ++j)
4389                         if (tpd2.parms[j] != 0
4390                             && tpd.arg_uses_template_parms [j])
4391                           ++count;
4392                       if (count != 0)
4393                         error_n (input_location, count,
4394                                  "type %qT of template argument %qE depends "
4395                                  "on a template parameter",
4396                                  "type %qT of template argument %qE depends "
4397                                  "on template parameters",
4398                                  type,
4399                                  arg);
4400                     }
4401                 }
4402             }
4403         }
4404     }
4405
4406   /* We should only get here once.  */
4407   gcc_assert (!COMPLETE_TYPE_P (type));
4408
4409   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4410     = tree_cons (specargs, inner_parms,
4411                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4412   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4413
4414   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4415        inst = TREE_CHAIN (inst))
4416     {
4417       tree inst_type = TREE_VALUE (inst);
4418       if (COMPLETE_TYPE_P (inst_type)
4419           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4420         {
4421           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4422           if (spec && TREE_TYPE (spec) == type)
4423             permerror (input_location,
4424                        "partial specialization of %qT after instantiation "
4425                        "of %qT", type, inst_type);
4426         }
4427     }
4428
4429   return decl;
4430 }
4431
4432 /* Check that a template declaration's use of default arguments and
4433    parameter packs is not invalid.  Here, PARMS are the template
4434    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4435    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4436    specialization.
4437    
4438
4439    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4440    declaration (but not a definition); 1 indicates a declaration, 2
4441    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4442    emitted for extraneous default arguments.
4443
4444    Returns TRUE if there were no errors found, FALSE otherwise. */
4445
4446 bool
4447 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4448                          int is_partial, int is_friend_decl)
4449 {
4450   const char *msg;
4451   int last_level_to_check;
4452   tree parm_level;
4453   bool no_errors = true;
4454
4455   /* [temp.param]
4456
4457      A default template-argument shall not be specified in a
4458      function template declaration or a function template definition, nor
4459      in the template-parameter-list of the definition of a member of a
4460      class template.  */
4461
4462   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4463     /* You can't have a function template declaration in a local
4464        scope, nor you can you define a member of a class template in a
4465        local scope.  */
4466     return true;
4467
4468   if (current_class_type
4469       && !TYPE_BEING_DEFINED (current_class_type)
4470       && DECL_LANG_SPECIFIC (decl)
4471       && DECL_DECLARES_FUNCTION_P (decl)
4472       /* If this is either a friend defined in the scope of the class
4473          or a member function.  */
4474       && (DECL_FUNCTION_MEMBER_P (decl)
4475           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4476           : DECL_FRIEND_CONTEXT (decl)
4477           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4478           : false)
4479       /* And, if it was a member function, it really was defined in
4480          the scope of the class.  */
4481       && (!DECL_FUNCTION_MEMBER_P (decl)
4482           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4483     /* We already checked these parameters when the template was
4484        declared, so there's no need to do it again now.  This function
4485        was defined in class scope, but we're processing it's body now
4486        that the class is complete.  */
4487     return true;
4488
4489   /* Core issue 226 (C++0x only): the following only applies to class
4490      templates.  */
4491   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4492     {
4493       /* [temp.param]
4494
4495          If a template-parameter has a default template-argument, all
4496          subsequent template-parameters shall have a default
4497          template-argument supplied.  */
4498       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4499         {
4500           tree inner_parms = TREE_VALUE (parm_level);
4501           int ntparms = TREE_VEC_LENGTH (inner_parms);
4502           int seen_def_arg_p = 0;
4503           int i;
4504
4505           for (i = 0; i < ntparms; ++i)
4506             {
4507               tree parm = TREE_VEC_ELT (inner_parms, i);
4508
4509               if (parm == error_mark_node)
4510                 continue;
4511
4512               if (TREE_PURPOSE (parm))
4513                 seen_def_arg_p = 1;
4514               else if (seen_def_arg_p
4515                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4516                 {
4517                   error ("no default argument for %qD", TREE_VALUE (parm));
4518                   /* For better subsequent error-recovery, we indicate that
4519                      there should have been a default argument.  */
4520                   TREE_PURPOSE (parm) = error_mark_node;
4521                   no_errors = false;
4522                 }
4523               else if (is_primary
4524                        && !is_partial
4525                        && !is_friend_decl
4526                        /* Don't complain about an enclosing partial
4527                           specialization.  */
4528                        && parm_level == parms
4529                        && TREE_CODE (decl) == TYPE_DECL
4530                        && i < ntparms - 1
4531                        && template_parameter_pack_p (TREE_VALUE (parm)))
4532                 {
4533                   /* A primary class template can only have one
4534                      parameter pack, at the end of the template
4535                      parameter list.  */
4536
4537                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4538                     error ("parameter pack %qE must be at the end of the"
4539                            " template parameter list", TREE_VALUE (parm));
4540                   else
4541                     error ("parameter pack %qT must be at the end of the"
4542                            " template parameter list", 
4543                            TREE_TYPE (TREE_VALUE (parm)));
4544
4545                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4546                     = error_mark_node;
4547                   no_errors = false;
4548                 }
4549             }
4550         }
4551     }
4552
4553   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4554       || is_partial 
4555       || !is_primary
4556       || is_friend_decl)
4557     /* For an ordinary class template, default template arguments are
4558        allowed at the innermost level, e.g.:
4559          template <class T = int>
4560          struct S {};
4561        but, in a partial specialization, they're not allowed even
4562        there, as we have in [temp.class.spec]:
4563
4564          The template parameter list of a specialization shall not
4565          contain default template argument values.
4566
4567        So, for a partial specialization, or for a function template
4568        (in C++98/C++03), we look at all of them.  */
4569     ;
4570   else
4571     /* But, for a primary class template that is not a partial
4572        specialization we look at all template parameters except the
4573        innermost ones.  */
4574     parms = TREE_CHAIN (parms);
4575
4576   /* Figure out what error message to issue.  */
4577   if (is_friend_decl == 2)
4578     msg = G_("default template arguments may not be used in function template "
4579              "friend re-declaration");
4580   else if (is_friend_decl)
4581     msg = G_("default template arguments may not be used in function template "
4582              "friend declarations");
4583   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4584     msg = G_("default template arguments may not be used in function templates "
4585              "without -std=c++0x or -std=gnu++0x");
4586   else if (is_partial)
4587     msg = G_("default template arguments may not be used in "
4588              "partial specializations");
4589   else
4590     msg = G_("default argument for template parameter for class enclosing %qD");
4591
4592   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4593     /* If we're inside a class definition, there's no need to
4594        examine the parameters to the class itself.  On the one
4595        hand, they will be checked when the class is defined, and,
4596        on the other, default arguments are valid in things like:
4597          template <class T = double>
4598          struct S { template <class U> void f(U); };
4599        Here the default argument for `S' has no bearing on the
4600        declaration of `f'.  */
4601     last_level_to_check = template_class_depth (current_class_type) + 1;
4602   else
4603     /* Check everything.  */
4604     last_level_to_check = 0;
4605
4606   for (parm_level = parms;
4607        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4608        parm_level = TREE_CHAIN (parm_level))
4609     {
4610       tree inner_parms = TREE_VALUE (parm_level);
4611       int i;
4612       int ntparms;
4613
4614       ntparms = TREE_VEC_LENGTH (inner_parms);
4615       for (i = 0; i < ntparms; ++i)
4616         {
4617           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4618             continue;
4619
4620           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4621             {
4622               if (msg)
4623                 {
4624                   no_errors = false;
4625                   if (is_friend_decl == 2)
4626                     return no_errors;
4627
4628                   error (msg, decl);
4629                   msg = 0;
4630                 }
4631
4632               /* Clear out the default argument so that we are not
4633                  confused later.  */
4634               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4635             }
4636         }
4637
4638       /* At this point, if we're still interested in issuing messages,
4639          they must apply to classes surrounding the object declared.  */
4640       if (msg)
4641         msg = G_("default argument for template parameter for class "
4642                  "enclosing %qD");
4643     }
4644
4645   return no_errors;
4646 }
4647
4648 /* Worker for push_template_decl_real, called via
4649    for_each_template_parm.  DATA is really an int, indicating the
4650    level of the parameters we are interested in.  If T is a template
4651    parameter of that level, return nonzero.  */
4652
4653 static int
4654 template_parm_this_level_p (tree t, void* data)
4655 {
4656   int this_level = *(int *)data;
4657   int level;
4658
4659   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4660     level = TEMPLATE_PARM_LEVEL (t);
4661   else
4662     level = TEMPLATE_TYPE_LEVEL (t);
4663   return level == this_level;
4664 }
4665
4666 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4667    parameters given by current_template_args, or reuses a
4668    previously existing one, if appropriate.  Returns the DECL, or an
4669    equivalent one, if it is replaced via a call to duplicate_decls.
4670
4671    If IS_FRIEND is true, DECL is a friend declaration.  */
4672
4673 tree
4674 push_template_decl_real (tree decl, bool is_friend)
4675 {
4676   tree tmpl;
4677   tree args;
4678   tree info;
4679   tree ctx;
4680   int primary;
4681   int is_partial;
4682   int new_template_p = 0;
4683   /* True if the template is a member template, in the sense of
4684      [temp.mem].  */
4685   bool member_template_p = false;
4686
4687   if (decl == error_mark_node || !current_template_parms)
4688     return error_mark_node;
4689
4690   /* See if this is a partial specialization.  */
4691   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4692                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4693                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4694
4695   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4696     is_friend = true;
4697
4698   if (is_friend)
4699     /* For a friend, we want the context of the friend function, not
4700        the type of which it is a friend.  */
4701     ctx = CP_DECL_CONTEXT (decl);
4702   else if (CP_DECL_CONTEXT (decl)
4703            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4704     /* In the case of a virtual function, we want the class in which
4705        it is defined.  */
4706     ctx = CP_DECL_CONTEXT (decl);
4707   else
4708     /* Otherwise, if we're currently defining some class, the DECL
4709        is assumed to be a member of the class.  */
4710     ctx = current_scope ();
4711
4712   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4713     ctx = NULL_TREE;
4714
4715   if (!DECL_CONTEXT (decl))
4716     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4717
4718   /* See if this is a primary template.  */
4719   if (is_friend && ctx)
4720     /* A friend template that specifies a class context, i.e.
4721          template <typename T> friend void A<T>::f();
4722        is not primary.  */
4723     primary = 0;
4724   else
4725     primary = template_parm_scope_p ();
4726
4727   if (primary)
4728     {
4729       if (DECL_CLASS_SCOPE_P (decl))
4730         member_template_p = true;
4731       if (TREE_CODE (decl) == TYPE_DECL
4732           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4733         {
4734           error ("template class without a name");
4735           return error_mark_node;
4736         }
4737       else if (TREE_CODE (decl) == FUNCTION_DECL)
4738         {
4739           if (DECL_DESTRUCTOR_P (decl))
4740             {
4741               /* [temp.mem]
4742
4743                  A destructor shall not be a member template.  */
4744               error ("destructor %qD declared as member template", decl);
4745               return error_mark_node;
4746             }
4747           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4748               && (!prototype_p (TREE_TYPE (decl))
4749                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4750                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4751                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4752                       == void_list_node)))
4753             {
4754               /* [basic.stc.dynamic.allocation]
4755
4756                  An allocation function can be a function
4757                  template. ... Template allocation functions shall
4758                  have two or more parameters.  */
4759               error ("invalid template declaration of %qD", decl);
4760               return error_mark_node;
4761             }
4762         }
4763       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4764                && CLASS_TYPE_P (TREE_TYPE (decl)))
4765         /* OK */;
4766       else
4767         {
4768           error ("template declaration of %q#D", decl);
4769           return error_mark_node;
4770         }
4771     }
4772
4773   /* Check to see that the rules regarding the use of default
4774      arguments are not being violated.  */
4775   check_default_tmpl_args (decl, current_template_parms,
4776                            primary, is_partial, /*is_friend_decl=*/0);
4777
4778   /* Ensure that there are no parameter packs in the type of this
4779      declaration that have not been expanded.  */
4780   if (TREE_CODE (decl) == FUNCTION_DECL)
4781     {
4782       /* Check each of the arguments individually to see if there are
4783          any bare parameter packs.  */
4784       tree type = TREE_TYPE (decl);
4785       tree arg = DECL_ARGUMENTS (decl);
4786       tree argtype = TYPE_ARG_TYPES (type);
4787
4788       while (arg && argtype)
4789         {
4790           if (!FUNCTION_PARAMETER_PACK_P (arg)
4791               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4792             {
4793             /* This is a PARM_DECL that contains unexpanded parameter
4794                packs. We have already complained about this in the
4795                check_for_bare_parameter_packs call, so just replace
4796                these types with ERROR_MARK_NODE.  */
4797               TREE_TYPE (arg) = error_mark_node;
4798               TREE_VALUE (argtype) = error_mark_node;
4799             }
4800
4801           arg = DECL_CHAIN (arg);
4802           argtype = TREE_CHAIN (argtype);
4803         }
4804
4805       /* Check for bare parameter packs in the return type and the
4806          exception specifiers.  */
4807       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4808         /* Errors were already issued, set return type to int
4809            as the frontend doesn't expect error_mark_node as
4810            the return type.  */
4811         TREE_TYPE (type) = integer_type_node;
4812       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4813         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4814     }
4815   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4816     {
4817       TREE_TYPE (decl) = error_mark_node;
4818       return error_mark_node;
4819     }
4820
4821   if (is_partial)
4822     return process_partial_specialization (decl);
4823
4824   args = current_template_args ();
4825
4826   if (!ctx
4827       || TREE_CODE (ctx) == FUNCTION_DECL
4828       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4829       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4830     {
4831       if (DECL_LANG_SPECIFIC (decl)
4832           && DECL_TEMPLATE_INFO (decl)
4833           && DECL_TI_TEMPLATE (decl))
4834         tmpl = DECL_TI_TEMPLATE (decl);
4835       /* If DECL is a TYPE_DECL for a class-template, then there won't
4836          be DECL_LANG_SPECIFIC.  The information equivalent to
4837          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4838       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4839                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4840                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4841         {
4842           /* Since a template declaration already existed for this
4843              class-type, we must be redeclaring it here.  Make sure
4844              that the redeclaration is valid.  */
4845           redeclare_class_template (TREE_TYPE (decl),
4846                                     current_template_parms);
4847           /* We don't need to create a new TEMPLATE_DECL; just use the
4848              one we already had.  */
4849           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4850         }
4851       else
4852         {
4853           tmpl = build_template_decl (decl, current_template_parms,
4854                                       member_template_p);
4855           new_template_p = 1;
4856
4857           if (DECL_LANG_SPECIFIC (decl)
4858               && DECL_TEMPLATE_SPECIALIZATION (decl))
4859             {
4860               /* A specialization of a member template of a template
4861                  class.  */
4862               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4863               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4864               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4865             }
4866         }
4867     }
4868   else
4869     {
4870       tree a, t, current, parms;
4871       int i;
4872       tree tinfo = get_template_info (decl);
4873
4874       if (!tinfo)
4875         {
4876           error ("template definition of non-template %q#D", decl);
4877           return error_mark_node;
4878         }
4879
4880       tmpl = TI_TEMPLATE (tinfo);
4881
4882       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4883           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4884           && DECL_TEMPLATE_SPECIALIZATION (decl)
4885           && DECL_MEMBER_TEMPLATE_P (tmpl))
4886         {
4887           tree new_tmpl;
4888
4889           /* The declaration is a specialization of a member
4890              template, declared outside the class.  Therefore, the
4891              innermost template arguments will be NULL, so we
4892              replace them with the arguments determined by the
4893              earlier call to check_explicit_specialization.  */
4894           args = DECL_TI_ARGS (decl);
4895
4896           new_tmpl
4897             = build_template_decl (decl, current_template_parms,
4898                                    member_template_p);
4899           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4900           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4901           DECL_TI_TEMPLATE (decl) = new_tmpl;
4902           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4903           DECL_TEMPLATE_INFO (new_tmpl)
4904             = build_template_info (tmpl, args);
4905
4906           register_specialization (new_tmpl,
4907                                    most_general_template (tmpl),
4908                                    args,
4909                                    is_friend, 0);
4910           return decl;
4911         }
4912
4913       /* Make sure the template headers we got make sense.  */
4914
4915       parms = DECL_TEMPLATE_PARMS (tmpl);
4916       i = TMPL_PARMS_DEPTH (parms);
4917       if (TMPL_ARGS_DEPTH (args) != i)
4918         {
4919           error ("expected %d levels of template parms for %q#D, got %d",
4920                  i, decl, TMPL_ARGS_DEPTH (args));
4921         }
4922       else
4923         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4924           {
4925             a = TMPL_ARGS_LEVEL (args, i);
4926             t = INNERMOST_TEMPLATE_PARMS (parms);
4927
4928             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4929               {
4930                 if (current == decl)
4931                   error ("got %d template parameters for %q#D",
4932                          TREE_VEC_LENGTH (a), decl);
4933                 else
4934                   error ("got %d template parameters for %q#T",
4935                          TREE_VEC_LENGTH (a), current);
4936                 error ("  but %d required", TREE_VEC_LENGTH (t));
4937                 return error_mark_node;
4938               }
4939
4940             if (current == decl)
4941               current = ctx;
4942             else if (current == NULL_TREE)
4943               /* Can happen in erroneous input.  */
4944               break;
4945             else
4946               current = (TYPE_P (current)
4947                          ? TYPE_CONTEXT (current)
4948                          : DECL_CONTEXT (current));
4949           }
4950
4951       /* Check that the parms are used in the appropriate qualifying scopes
4952          in the declarator.  */
4953       if (!comp_template_args
4954           (TI_ARGS (tinfo),
4955            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4956         {
4957           error ("\
4958 template arguments to %qD do not match original template %qD",
4959                  decl, DECL_TEMPLATE_RESULT (tmpl));
4960           if (!uses_template_parms (TI_ARGS (tinfo)))
4961             inform (input_location, "use template<> for an explicit specialization");
4962           /* Avoid crash in import_export_decl.  */
4963           DECL_INTERFACE_KNOWN (decl) = 1;
4964           return error_mark_node;
4965         }
4966     }
4967
4968   DECL_TEMPLATE_RESULT (tmpl) = decl;
4969   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4970
4971   /* Push template declarations for global functions and types.  Note
4972      that we do not try to push a global template friend declared in a
4973      template class; such a thing may well depend on the template
4974      parameters of the class.  */
4975   if (new_template_p && !ctx
4976       && !(is_friend && template_class_depth (current_class_type) > 0))
4977     {
4978       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4979       if (tmpl == error_mark_node)
4980         return error_mark_node;
4981
4982       /* Hide template friend classes that haven't been declared yet.  */
4983       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4984         {
4985           DECL_ANTICIPATED (tmpl) = 1;
4986           DECL_FRIEND_P (tmpl) = 1;
4987         }
4988     }
4989
4990   if (primary)
4991     {
4992       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4993       int i;
4994
4995       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4996       if (DECL_CONV_FN_P (tmpl))
4997         {
4998           int depth = TMPL_PARMS_DEPTH (parms);
4999
5000           /* It is a conversion operator. See if the type converted to
5001              depends on innermost template operands.  */
5002
5003           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5004                                          depth))
5005             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5006         }
5007
5008       /* Give template template parms a DECL_CONTEXT of the template
5009          for which they are a parameter.  */
5010       parms = INNERMOST_TEMPLATE_PARMS (parms);
5011       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5012         {
5013           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5014           if (TREE_CODE (parm) == TEMPLATE_DECL)
5015             DECL_CONTEXT (parm) = tmpl;
5016         }
5017     }
5018
5019   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5020      back to its most general template.  If TMPL is a specialization,
5021      ARGS may only have the innermost set of arguments.  Add the missing
5022      argument levels if necessary.  */
5023   if (DECL_TEMPLATE_INFO (tmpl))
5024     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5025
5026   info = build_template_info (tmpl, args);
5027
5028   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5029     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5030   else if (DECL_LANG_SPECIFIC (decl))
5031     DECL_TEMPLATE_INFO (decl) = info;
5032
5033   return DECL_TEMPLATE_RESULT (tmpl);
5034 }
5035
5036 tree
5037 push_template_decl (tree decl)
5038 {
5039   return push_template_decl_real (decl, false);
5040 }
5041
5042 /* Called when a class template TYPE is redeclared with the indicated
5043    template PARMS, e.g.:
5044
5045      template <class T> struct S;
5046      template <class T> struct S {};  */
5047
5048 bool
5049 redeclare_class_template (tree type, tree parms)
5050 {
5051   tree tmpl;
5052   tree tmpl_parms;
5053   int i;
5054
5055   if (!TYPE_TEMPLATE_INFO (type))
5056     {
5057       error ("%qT is not a template type", type);
5058       return false;
5059     }
5060
5061   tmpl = TYPE_TI_TEMPLATE (type);
5062   if (!PRIMARY_TEMPLATE_P (tmpl))
5063     /* The type is nested in some template class.  Nothing to worry
5064        about here; there are no new template parameters for the nested
5065        type.  */
5066     return true;
5067
5068   if (!parms)
5069     {
5070       error ("template specifiers not specified in declaration of %qD",
5071              tmpl);
5072       return false;
5073     }
5074
5075   parms = INNERMOST_TEMPLATE_PARMS (parms);
5076   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5077
5078   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5079     {
5080       error_n (input_location, TREE_VEC_LENGTH (parms),
5081                "redeclared with %d template parameter",
5082                "redeclared with %d template parameters",
5083                TREE_VEC_LENGTH (parms));
5084       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5085                 "previous declaration %q+D used %d template parameter",
5086                 "previous declaration %q+D used %d template parameters",
5087                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5088       return false;
5089     }
5090
5091   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5092     {
5093       tree tmpl_parm;
5094       tree parm;
5095       tree tmpl_default;
5096       tree parm_default;
5097
5098       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5099           || TREE_VEC_ELT (parms, i) == error_mark_node)
5100         continue;
5101
5102       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5103       if (tmpl_parm == error_mark_node)
5104         return false;
5105
5106       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5107       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5108       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5109
5110       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5111          TEMPLATE_DECL.  */
5112       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5113           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5114               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5115           || (TREE_CODE (tmpl_parm) != PARM_DECL
5116               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5117                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5118           || (TREE_CODE (tmpl_parm) == PARM_DECL
5119               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5120                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5121         {
5122           error ("template parameter %q+#D", tmpl_parm);
5123           error ("redeclared here as %q#D", parm);
5124           return false;
5125         }
5126
5127       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5128         {
5129           /* We have in [temp.param]:
5130
5131              A template-parameter may not be given default arguments
5132              by two different declarations in the same scope.  */
5133           error_at (input_location, "redefinition of default argument for %q#D", parm);
5134           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5135                   "original definition appeared here");
5136           return false;
5137         }
5138
5139       if (parm_default != NULL_TREE)
5140         /* Update the previous template parameters (which are the ones
5141            that will really count) with the new default value.  */
5142         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5143       else if (tmpl_default != NULL_TREE)
5144         /* Update the new parameters, too; they'll be used as the
5145            parameters for any members.  */
5146         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5147     }
5148
5149     return true;
5150 }
5151
5152 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5153    (possibly simplified) expression.  */
5154
5155 static tree
5156 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5157 {
5158   if (expr == NULL_TREE)
5159     return NULL_TREE;
5160
5161   /* If we're in a template, but EXPR isn't value dependent, simplify
5162      it.  We're supposed to treat:
5163
5164        template <typename T> void f(T[1 + 1]);
5165        template <typename T> void f(T[2]);
5166
5167      as two declarations of the same function, for example.  */
5168   if (processing_template_decl
5169       && !type_dependent_expression_p (expr)
5170       && potential_constant_expression (expr)
5171       && !value_dependent_expression_p (expr))
5172     {
5173       HOST_WIDE_INT saved_processing_template_decl;
5174
5175       saved_processing_template_decl = processing_template_decl;
5176       processing_template_decl = 0;
5177       expr = tsubst_copy_and_build (expr,
5178                                     /*args=*/NULL_TREE,
5179                                     complain,
5180                                     /*in_decl=*/NULL_TREE,
5181                                     /*function_p=*/false,
5182                                     /*integral_constant_expression_p=*/true);
5183       processing_template_decl = saved_processing_template_decl;
5184     }
5185   return expr;
5186 }
5187
5188 tree
5189 fold_non_dependent_expr (tree expr)
5190 {
5191   return fold_non_dependent_expr_sfinae (expr, tf_error);
5192 }
5193
5194 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5195    must be a function or a pointer-to-function type, as specified
5196    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5197    and check that the resulting function has external linkage.  */
5198
5199 static tree
5200 convert_nontype_argument_function (tree type, tree expr)
5201 {
5202   tree fns = expr;
5203   tree fn, fn_no_ptr;
5204
5205   fn = instantiate_type (type, fns, tf_none);
5206   if (fn == error_mark_node)
5207     return error_mark_node;
5208
5209   fn_no_ptr = fn;
5210   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5211     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5212   if (TREE_CODE (fn_no_ptr) == BASELINK)
5213     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5214  
5215   /* [temp.arg.nontype]/1
5216
5217      A template-argument for a non-type, non-template template-parameter
5218      shall be one of:
5219      [...]
5220      -- the address of an object or function with external linkage.  */
5221   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5222     {
5223       error ("%qE is not a valid template argument for type %qT "
5224              "because function %qD has not external linkage",
5225              expr, type, fn_no_ptr);
5226       return NULL_TREE;
5227     }
5228
5229   return fn;
5230 }
5231
5232 /* Subroutine of convert_nontype_argument.
5233    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5234    Emit an error otherwise.  */
5235
5236 static bool
5237 check_valid_ptrmem_cst_expr (tree type, tree expr,
5238                              tsubst_flags_t complain)
5239 {
5240   STRIP_NOPS (expr);
5241   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5242     return true;
5243   if (complain & tf_error)
5244     {
5245       error ("%qE is not a valid template argument for type %qT",
5246              expr, type);
5247       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5248     }
5249   return false;
5250 }
5251
5252 /* Returns TRUE iff the address of OP is value-dependent.
5253
5254    14.6.2.4 [temp.dep.temp]:
5255    A non-integral non-type template-argument is dependent if its type is
5256    dependent or it has either of the following forms
5257      qualified-id
5258      & qualified-id
5259    and contains a nested-name-specifier which specifies a class-name that
5260    names a dependent type.
5261
5262    We generalize this to just say that the address of a member of a
5263    dependent class is value-dependent; the above doesn't cover the
5264    address of a static data member named with an unqualified-id.  */
5265
5266 static bool
5267 has_value_dependent_address (tree op)
5268 {
5269   /* We could use get_inner_reference here, but there's no need;
5270      this is only relevant for template non-type arguments, which
5271      can only be expressed as &id-expression.  */
5272   if (DECL_P (op))
5273     {
5274       tree ctx = CP_DECL_CONTEXT (op);
5275       if (TYPE_P (ctx) && dependent_type_p (ctx))
5276         return true;
5277     }
5278
5279   return false;
5280 }
5281
5282 /* The next set of functions are used for providing helpful explanatory
5283    diagnostics for failed overload resolution.  Their messages should be
5284    indented by two spaces for consistency with the messages in
5285    call.c  */
5286
5287 static int
5288 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5289 {
5290   return 0;
5291 }
5292
5293 static int
5294 unify_parameter_deduction_failure (bool explain_p, tree parm)
5295 {
5296   if (explain_p)
5297     inform (input_location,
5298             "  couldn't deduce template parameter %qD", parm);
5299   return 1;
5300 }
5301
5302 static int
5303 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5304 {
5305   return 1;
5306 }
5307
5308 static int
5309 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5310 {
5311   if (explain_p)
5312     inform (input_location,
5313             "  types %qT and %qT have incompatible cv-qualifiers",
5314             parm, arg);
5315   return 1;
5316 }
5317
5318 static int
5319 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5320 {
5321   if (explain_p)
5322     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5323   return 1;
5324 }
5325
5326 static int
5327 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5328 {
5329   if (explain_p)
5330     inform (input_location,
5331             "  template parameter %qD is not a parameter pack, but "
5332             "argument %qD is",
5333             parm, arg);
5334   return 1;
5335 }
5336
5337 static int
5338 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5339 {
5340   if (explain_p)
5341     inform (input_location,
5342             "  template argument %qE does not match "
5343             "pointer-to-member constant %qE",
5344             arg, parm);
5345   return 1;
5346 }
5347
5348 static int
5349 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5350 {
5351   if (explain_p)
5352     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5353   return 1;
5354 }
5355
5356 static int
5357 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5358 {
5359   if (explain_p)
5360     inform (input_location,
5361             "  inconsistent parameter pack deduction with %qT and %qT",
5362             old_arg, new_arg);
5363   return 1;
5364 }
5365
5366 static int
5367 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5368 {
5369   if (explain_p)
5370     inform (input_location,
5371             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5372             parm, first, second);
5373   return 1;
5374 }
5375
5376 static int
5377 unify_vla_arg (bool explain_p, tree arg)
5378 {
5379   if (explain_p)
5380     inform (input_location,
5381             "  variable-sized array type %qT is not "
5382             "a valid template argument",
5383             arg);
5384   return 1;
5385 }
5386
5387 static int
5388 unify_method_type_error (bool explain_p, tree arg)
5389 {
5390   if (explain_p)
5391     inform (input_location,
5392             "  member function type %qT is not a valid template argument",
5393             arg);
5394   return 1;
5395 }
5396
5397 static int
5398 unify_arity (bool explain_p, int have, int wanted)
5399 {
5400   if (explain_p)
5401     inform_n (input_location, wanted,
5402               "  candidate expects %d argument, %d provided",
5403               "  candidate expects %d arguments, %d provided",
5404               wanted, have);
5405   return 1;
5406 }
5407
5408 static int
5409 unify_too_many_arguments (bool explain_p, int have, int wanted)
5410 {
5411   return unify_arity (explain_p, have, wanted);
5412 }
5413
5414 static int
5415 unify_too_few_arguments (bool explain_p, int have, int wanted)
5416 {
5417   return unify_arity (explain_p, have, wanted);
5418 }
5419
5420 static int
5421 unify_arg_conversion (bool explain_p, tree to_type,
5422                       tree from_type, tree arg)
5423 {
5424   if (explain_p)
5425     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5426             arg, from_type, to_type);
5427   return 1;
5428 }
5429
5430 static int
5431 unify_no_common_base (bool explain_p, enum template_base_result r,
5432                       tree parm, tree arg)
5433 {
5434   if (explain_p)
5435     switch (r)
5436       {
5437       case tbr_ambiguous_baseclass:
5438         inform (input_location, "  %qT is an ambiguous base class of %qT",
5439                 arg, parm);
5440         break;
5441       default:
5442         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5443         break;
5444       }
5445   return 1;
5446 }
5447
5448 static int
5449 unify_inconsistent_template_template_parameters (bool explain_p)
5450 {
5451   if (explain_p)
5452     inform (input_location,
5453             "  template parameters of a template template argument are "
5454             "inconsistent with other deduced template arguments");
5455   return 1;
5456 }
5457
5458 static int
5459 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5460 {
5461   if (explain_p)
5462     inform (input_location,
5463             "  can't deduce a template for %qT from non-template type %qT",
5464             parm, arg);
5465   return 1;
5466 }
5467
5468 static int
5469 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5470 {
5471   if (explain_p)
5472     inform (input_location,
5473             "  template argument %qE does not match %qD", arg, parm);
5474   return 1;
5475 }
5476
5477 static int
5478 unify_overload_resolution_failure (bool explain_p, tree arg)
5479 {
5480   if (explain_p)
5481     inform (input_location,
5482             "  could not resolve address from overloaded function %qE",
5483             arg);
5484   return 1;
5485 }
5486
5487 /* Attempt to convert the non-type template parameter EXPR to the
5488    indicated TYPE.  If the conversion is successful, return the
5489    converted value.  If the conversion is unsuccessful, return
5490    NULL_TREE if we issued an error message, or error_mark_node if we
5491    did not.  We issue error messages for out-and-out bad template
5492    parameters, but not simply because the conversion failed, since we
5493    might be just trying to do argument deduction.  Both TYPE and EXPR
5494    must be non-dependent.
5495
5496    The conversion follows the special rules described in
5497    [temp.arg.nontype], and it is much more strict than an implicit
5498    conversion.
5499
5500    This function is called twice for each template argument (see
5501    lookup_template_class for a more accurate description of this
5502    problem). This means that we need to handle expressions which
5503    are not valid in a C++ source, but can be created from the
5504    first call (for instance, casts to perform conversions). These
5505    hacks can go away after we fix the double coercion problem.  */
5506
5507 static tree
5508 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5509 {
5510   tree expr_type;
5511
5512   /* Detect immediately string literals as invalid non-type argument.
5513      This special-case is not needed for correctness (we would easily
5514      catch this later), but only to provide better diagnostic for this
5515      common user mistake. As suggested by DR 100, we do not mention
5516      linkage issues in the diagnostic as this is not the point.  */
5517   /* FIXME we're making this OK.  */
5518   if (TREE_CODE (expr) == STRING_CST)
5519     {
5520       if (complain & tf_error)
5521         error ("%qE is not a valid template argument for type %qT "
5522                "because string literals can never be used in this context",
5523                expr, type);
5524       return NULL_TREE;
5525     }
5526
5527   /* Add the ADDR_EXPR now for the benefit of
5528      value_dependent_expression_p.  */
5529   if (TYPE_PTROBV_P (type)
5530       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5531     expr = decay_conversion (expr);
5532
5533   /* If we are in a template, EXPR may be non-dependent, but still
5534      have a syntactic, rather than semantic, form.  For example, EXPR
5535      might be a SCOPE_REF, rather than the VAR_DECL to which the
5536      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5537      so that access checking can be performed when the template is
5538      instantiated -- but here we need the resolved form so that we can
5539      convert the argument.  */
5540   if (TYPE_REF_OBJ_P (type)
5541       && has_value_dependent_address (expr))
5542     /* If we want the address and it's value-dependent, don't fold.  */;
5543   else if (!type_unknown_p (expr))
5544     expr = fold_non_dependent_expr_sfinae (expr, complain);
5545   if (error_operand_p (expr))
5546     return error_mark_node;
5547   expr_type = TREE_TYPE (expr);
5548   if (TREE_CODE (type) == REFERENCE_TYPE)
5549     expr = mark_lvalue_use (expr);
5550   else
5551     expr = mark_rvalue_use (expr);
5552
5553   /* HACK: Due to double coercion, we can get a
5554      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5555      which is the tree that we built on the first call (see
5556      below when coercing to reference to object or to reference to
5557      function). We just strip everything and get to the arg.
5558      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5559      for examples.  */
5560   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5561     {
5562       tree probe_type, probe = expr;
5563       if (REFERENCE_REF_P (probe))
5564         probe = TREE_OPERAND (probe, 0);
5565       probe_type = TREE_TYPE (probe);
5566       if (TREE_CODE (probe) == NOP_EXPR)
5567         {
5568           /* ??? Maybe we could use convert_from_reference here, but we
5569              would need to relax its constraints because the NOP_EXPR
5570              could actually change the type to something more cv-qualified,
5571              and this is not folded by convert_from_reference.  */
5572           tree addr = TREE_OPERAND (probe, 0);
5573           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5574           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5575           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5576           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5577                       (TREE_TYPE (probe_type),
5578                        TREE_TYPE (TREE_TYPE (addr))));
5579
5580           expr = TREE_OPERAND (addr, 0);
5581           expr_type = TREE_TYPE (expr);
5582         }
5583     }
5584
5585   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5586      parameter is a pointer to object, through decay and
5587      qualification conversion. Let's strip everything.  */
5588   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5589     {
5590       STRIP_NOPS (expr);
5591       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5592       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5593       /* Skip the ADDR_EXPR only if it is part of the decay for
5594          an array. Otherwise, it is part of the original argument
5595          in the source code.  */
5596       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5597         expr = TREE_OPERAND (expr, 0);
5598       expr_type = TREE_TYPE (expr);
5599     }
5600
5601   /* [temp.arg.nontype]/5, bullet 1
5602
5603      For a non-type template-parameter of integral or enumeration type,
5604      integral promotions (_conv.prom_) and integral conversions
5605      (_conv.integral_) are applied.  */
5606   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5607     {
5608       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5609       t = maybe_constant_value (t);
5610       if (t != error_mark_node)
5611         expr = t;
5612
5613       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5614         return error_mark_node;
5615
5616       /* Notice that there are constant expressions like '4 % 0' which
5617          do not fold into integer constants.  */
5618       if (TREE_CODE (expr) != INTEGER_CST)
5619         {
5620           if (complain & tf_error)
5621             {
5622               int errs = errorcount, warns = warningcount;
5623               expr = cxx_constant_value (expr);
5624               if (errorcount > errs || warningcount > warns)
5625                 inform (EXPR_LOC_OR_HERE (expr),
5626                         "in template argument for type %qT ", type);
5627               if (expr == error_mark_node)
5628                 return NULL_TREE;
5629               /* else cxx_constant_value complained but gave us
5630                  a real constant, so go ahead.  */
5631               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5632             }
5633           else
5634             return NULL_TREE;
5635         }
5636     }
5637   /* [temp.arg.nontype]/5, bullet 2
5638
5639      For a non-type template-parameter of type pointer to object,
5640      qualification conversions (_conv.qual_) and the array-to-pointer
5641      conversion (_conv.array_) are applied.  */
5642   else if (TYPE_PTROBV_P (type))
5643     {
5644       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5645
5646          A template-argument for a non-type, non-template template-parameter
5647          shall be one of: [...]
5648
5649          -- the name of a non-type template-parameter;
5650          -- the address of an object or function with external linkage, [...]
5651             expressed as "& id-expression" where the & is optional if the name
5652             refers to a function or array, or if the corresponding
5653             template-parameter is a reference.
5654
5655         Here, we do not care about functions, as they are invalid anyway
5656         for a parameter of type pointer-to-object.  */
5657
5658       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5659         /* Non-type template parameters are OK.  */
5660         ;
5661       else if (TREE_CODE (expr) != ADDR_EXPR
5662                && TREE_CODE (expr_type) != ARRAY_TYPE)
5663         {
5664           if (TREE_CODE (expr) == VAR_DECL)
5665             {
5666               error ("%qD is not a valid template argument "
5667                      "because %qD is a variable, not the address of "
5668                      "a variable",
5669                      expr, expr);
5670               return NULL_TREE;
5671             }
5672           /* Other values, like integer constants, might be valid
5673              non-type arguments of some other type.  */
5674           return error_mark_node;
5675         }
5676       else
5677         {
5678           tree decl;
5679
5680           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5681                   ? TREE_OPERAND (expr, 0) : expr);
5682           if (TREE_CODE (decl) != VAR_DECL)
5683             {
5684               error ("%qE is not a valid template argument of type %qT "
5685                      "because %qE is not a variable",
5686                      expr, type, decl);
5687               return NULL_TREE;
5688             }
5689           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5690             {
5691               error ("%qE is not a valid template argument of type %qT "
5692                      "because %qD does not have external linkage",
5693                      expr, type, decl);
5694               return NULL_TREE;
5695             }
5696         }
5697
5698       expr = decay_conversion (expr);
5699       if (expr == error_mark_node)
5700         return error_mark_node;
5701
5702       expr = perform_qualification_conversions (type, expr);
5703       if (expr == error_mark_node)
5704         return error_mark_node;
5705     }
5706   /* [temp.arg.nontype]/5, bullet 3
5707
5708      For a non-type template-parameter of type reference to object, no
5709      conversions apply. The type referred to by the reference may be more
5710      cv-qualified than the (otherwise identical) type of the
5711      template-argument. The template-parameter is bound directly to the
5712      template-argument, which must be an lvalue.  */
5713   else if (TYPE_REF_OBJ_P (type))
5714     {
5715       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5716                                                       expr_type))
5717         return error_mark_node;
5718
5719       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5720         {
5721           error ("%qE is not a valid template argument for type %qT "
5722                  "because of conflicts in cv-qualification", expr, type);
5723           return NULL_TREE;
5724         }
5725
5726       if (!real_lvalue_p (expr))
5727         {
5728           error ("%qE is not a valid template argument for type %qT "
5729                  "because it is not an lvalue", expr, type);
5730           return NULL_TREE;
5731         }
5732
5733       /* [temp.arg.nontype]/1
5734
5735          A template-argument for a non-type, non-template template-parameter
5736          shall be one of: [...]
5737
5738          -- the address of an object or function with external linkage.  */
5739       if (TREE_CODE (expr) == INDIRECT_REF
5740           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5741         {
5742           expr = TREE_OPERAND (expr, 0);
5743           if (DECL_P (expr))
5744             {
5745               error ("%q#D is not a valid template argument for type %qT "
5746                      "because a reference variable does not have a constant "
5747                      "address", expr, type);
5748               return NULL_TREE;
5749             }
5750         }
5751
5752       if (!DECL_P (expr))
5753         {
5754           error ("%qE is not a valid template argument for type %qT "
5755                  "because it is not an object with external linkage",
5756                  expr, type);
5757           return NULL_TREE;
5758         }
5759
5760       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5761         {
5762           error ("%qE is not a valid template argument for type %qT "
5763                  "because object %qD has not external linkage",
5764                  expr, type, expr);
5765           return NULL_TREE;
5766         }
5767
5768       expr = build_nop (type, build_address (expr));
5769     }
5770   /* [temp.arg.nontype]/5, bullet 4
5771
5772      For a non-type template-parameter of type pointer to function, only
5773      the function-to-pointer conversion (_conv.func_) is applied. If the
5774      template-argument represents a set of overloaded functions (or a
5775      pointer to such), the matching function is selected from the set
5776      (_over.over_).  */
5777   else if (TYPE_PTRFN_P (type))
5778     {
5779       /* If the argument is a template-id, we might not have enough
5780          context information to decay the pointer.  */
5781       if (!type_unknown_p (expr_type))
5782         {
5783           expr = decay_conversion (expr);
5784           if (expr == error_mark_node)
5785             return error_mark_node;
5786         }
5787
5788       expr = convert_nontype_argument_function (type, expr);
5789       if (!expr || expr == error_mark_node)
5790         return expr;
5791
5792       if (TREE_CODE (expr) != ADDR_EXPR)
5793         {
5794           error ("%qE is not a valid template argument for type %qT", expr, type);
5795           error ("it must be the address of a function with external linkage");
5796           return NULL_TREE;
5797         }
5798     }
5799   /* [temp.arg.nontype]/5, bullet 5
5800
5801      For a non-type template-parameter of type reference to function, no
5802      conversions apply. If the template-argument represents a set of
5803      overloaded functions, the matching function is selected from the set
5804      (_over.over_).  */
5805   else if (TYPE_REFFN_P (type))
5806     {
5807       if (TREE_CODE (expr) == ADDR_EXPR)
5808         {
5809           error ("%qE is not a valid template argument for type %qT "
5810                  "because it is a pointer", expr, type);
5811           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5812           return NULL_TREE;
5813         }
5814
5815       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5816       if (!expr || expr == error_mark_node)
5817         return expr;
5818
5819       expr = build_nop (type, build_address (expr));
5820     }
5821   /* [temp.arg.nontype]/5, bullet 6
5822
5823      For a non-type template-parameter of type pointer to member function,
5824      no conversions apply. If the template-argument represents a set of
5825      overloaded member functions, the matching member function is selected
5826      from the set (_over.over_).  */
5827   else if (TYPE_PTRMEMFUNC_P (type))
5828     {
5829       expr = instantiate_type (type, expr, tf_none);
5830       if (expr == error_mark_node)
5831         return error_mark_node;
5832
5833       /* [temp.arg.nontype] bullet 1 says the pointer to member
5834          expression must be a pointer-to-member constant.  */
5835       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5836         return error_mark_node;
5837
5838       /* There is no way to disable standard conversions in
5839          resolve_address_of_overloaded_function (called by
5840          instantiate_type). It is possible that the call succeeded by
5841          converting &B::I to &D::I (where B is a base of D), so we need
5842          to reject this conversion here.
5843
5844          Actually, even if there was a way to disable standard conversions,
5845          it would still be better to reject them here so that we can
5846          provide a superior diagnostic.  */
5847       if (!same_type_p (TREE_TYPE (expr), type))
5848         {
5849           error ("%qE is not a valid template argument for type %qT "
5850                  "because it is of type %qT", expr, type,
5851                  TREE_TYPE (expr));
5852           /* If we are just one standard conversion off, explain.  */
5853           if (can_convert (type, TREE_TYPE (expr)))
5854             inform (input_location,
5855                     "standard conversions are not allowed in this context");
5856           return NULL_TREE;
5857         }
5858     }
5859   /* [temp.arg.nontype]/5, bullet 7
5860
5861      For a non-type template-parameter of type pointer to data member,
5862      qualification conversions (_conv.qual_) are applied.  */
5863   else if (TYPE_PTRMEM_P (type))
5864     {
5865       /* [temp.arg.nontype] bullet 1 says the pointer to member
5866          expression must be a pointer-to-member constant.  */
5867       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5868         return error_mark_node;
5869
5870       expr = perform_qualification_conversions (type, expr);
5871       if (expr == error_mark_node)
5872         return expr;
5873     }
5874   /* A template non-type parameter must be one of the above.  */
5875   else
5876     gcc_unreachable ();
5877
5878   /* Sanity check: did we actually convert the argument to the
5879      right type?  */
5880   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5881               (type, TREE_TYPE (expr)));
5882   return expr;
5883 }
5884
5885 /* Subroutine of coerce_template_template_parms, which returns 1 if
5886    PARM_PARM and ARG_PARM match using the rule for the template
5887    parameters of template template parameters. Both PARM and ARG are
5888    template parameters; the rest of the arguments are the same as for
5889    coerce_template_template_parms.
5890  */
5891 static int
5892 coerce_template_template_parm (tree parm,
5893                               tree arg,
5894                               tsubst_flags_t complain,
5895                               tree in_decl,
5896                               tree outer_args)
5897 {
5898   if (arg == NULL_TREE || arg == error_mark_node
5899       || parm == NULL_TREE || parm == error_mark_node)
5900     return 0;
5901   
5902   if (TREE_CODE (arg) != TREE_CODE (parm))
5903     return 0;
5904   
5905   switch (TREE_CODE (parm))
5906     {
5907     case TEMPLATE_DECL:
5908       /* We encounter instantiations of templates like
5909          template <template <template <class> class> class TT>
5910          class C;  */
5911       {
5912         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5913         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5914         
5915         if (!coerce_template_template_parms
5916             (parmparm, argparm, complain, in_decl, outer_args))
5917           return 0;
5918       }
5919       /* Fall through.  */
5920       
5921     case TYPE_DECL:
5922       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5923           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5924         /* Argument is a parameter pack but parameter is not.  */
5925         return 0;
5926       break;
5927       
5928     case PARM_DECL:
5929       /* The tsubst call is used to handle cases such as
5930          
5931            template <int> class C {};
5932            template <class T, template <T> class TT> class D {};
5933            D<int, C> d;
5934
5935          i.e. the parameter list of TT depends on earlier parameters.  */
5936       if (!uses_template_parms (TREE_TYPE (arg))
5937           && !same_type_p
5938                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5939                  TREE_TYPE (arg)))
5940         return 0;
5941       
5942       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5943           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5944         /* Argument is a parameter pack but parameter is not.  */
5945         return 0;
5946       
5947       break;
5948
5949     default:
5950       gcc_unreachable ();
5951     }
5952
5953   return 1;
5954 }
5955
5956
5957 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5958    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5959    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5960    or PARM_DECL.
5961
5962    Consider the example:
5963      template <class T> class A;
5964      template<template <class U> class TT> class B;
5965
5966    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5967    the parameters to A, and OUTER_ARGS contains A.  */
5968
5969 static int
5970 coerce_template_template_parms (tree parm_parms,
5971                                 tree arg_parms,
5972                                 tsubst_flags_t complain,
5973                                 tree in_decl,
5974                                 tree outer_args)
5975 {
5976   int nparms, nargs, i;
5977   tree parm, arg;
5978   int variadic_p = 0;
5979
5980   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5981   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5982
5983   nparms = TREE_VEC_LENGTH (parm_parms);
5984   nargs = TREE_VEC_LENGTH (arg_parms);
5985
5986   /* Determine whether we have a parameter pack at the end of the
5987      template template parameter's template parameter list.  */
5988   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5989     {
5990       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5991       
5992       if (parm == error_mark_node)
5993         return 0;
5994
5995       switch (TREE_CODE (parm))
5996         {
5997         case TEMPLATE_DECL:
5998         case TYPE_DECL:
5999           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6000             variadic_p = 1;
6001           break;
6002           
6003         case PARM_DECL:
6004           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6005             variadic_p = 1;
6006           break;
6007           
6008         default:
6009           gcc_unreachable ();
6010         }
6011     }
6012  
6013   if (nargs != nparms
6014       && !(variadic_p && nargs >= nparms - 1))
6015     return 0;
6016
6017   /* Check all of the template parameters except the parameter pack at
6018      the end (if any).  */
6019   for (i = 0; i < nparms - variadic_p; ++i)
6020     {
6021       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6022           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6023         continue;
6024
6025       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6026       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6027
6028       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6029                                           outer_args))
6030         return 0;
6031
6032     }
6033
6034   if (variadic_p)
6035     {
6036       /* Check each of the template parameters in the template
6037          argument against the template parameter pack at the end of
6038          the template template parameter.  */
6039       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6040         return 0;
6041
6042       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6043
6044       for (; i < nargs; ++i)
6045         {
6046           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6047             continue;
6048  
6049           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6050  
6051           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6052                                               outer_args))
6053             return 0;
6054         }
6055     }
6056
6057   return 1;
6058 }
6059
6060 /* Verifies that the deduced template arguments (in TARGS) for the
6061    template template parameters (in TPARMS) represent valid bindings,
6062    by comparing the template parameter list of each template argument
6063    to the template parameter list of its corresponding template
6064    template parameter, in accordance with DR150. This
6065    routine can only be called after all template arguments have been
6066    deduced. It will return TRUE if all of the template template
6067    parameter bindings are okay, FALSE otherwise.  */
6068 bool 
6069 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6070 {
6071   int i, ntparms = TREE_VEC_LENGTH (tparms);
6072   bool ret = true;
6073
6074   /* We're dealing with template parms in this process.  */
6075   ++processing_template_decl;
6076
6077   targs = INNERMOST_TEMPLATE_ARGS (targs);
6078
6079   for (i = 0; i < ntparms; ++i)
6080     {
6081       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6082       tree targ = TREE_VEC_ELT (targs, i);
6083
6084       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6085         {
6086           tree packed_args = NULL_TREE;
6087           int idx, len = 1;
6088
6089           if (ARGUMENT_PACK_P (targ))
6090             {
6091               /* Look inside the argument pack.  */
6092               packed_args = ARGUMENT_PACK_ARGS (targ);
6093               len = TREE_VEC_LENGTH (packed_args);
6094             }
6095
6096           for (idx = 0; idx < len; ++idx)
6097             {
6098               tree targ_parms = NULL_TREE;
6099
6100               if (packed_args)
6101                 /* Extract the next argument from the argument
6102                    pack.  */
6103                 targ = TREE_VEC_ELT (packed_args, idx);
6104
6105               if (PACK_EXPANSION_P (targ))
6106                 /* Look at the pattern of the pack expansion.  */
6107                 targ = PACK_EXPANSION_PATTERN (targ);
6108
6109               /* Extract the template parameters from the template
6110                  argument.  */
6111               if (TREE_CODE (targ) == TEMPLATE_DECL)
6112                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6113               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6114                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6115
6116               /* Verify that we can coerce the template template
6117                  parameters from the template argument to the template
6118                  parameter.  This requires an exact match.  */
6119               if (targ_parms
6120                   && !coerce_template_template_parms
6121                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6122                         targ_parms,
6123                         tf_none,
6124                         tparm,
6125                         targs))
6126                 {
6127                   ret = false;
6128                   goto out;
6129                 }
6130             }
6131         }
6132     }
6133
6134  out:
6135
6136   --processing_template_decl;
6137   return ret;
6138 }
6139
6140 /* Since type attributes aren't mangled, we need to strip them from
6141    template type arguments.  */
6142
6143 static tree
6144 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6145 {
6146   tree mv;
6147   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6148     return arg;
6149   mv = TYPE_MAIN_VARIANT (arg);
6150   arg = strip_typedefs (arg);
6151   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6152       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6153     {
6154       if (complain & tf_warning)
6155         warning (0, "ignoring attributes on template argument %qT", arg);
6156       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6157       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6158     }
6159   return arg;
6160 }
6161
6162 /* Convert the indicated template ARG as necessary to match the
6163    indicated template PARM.  Returns the converted ARG, or
6164    error_mark_node if the conversion was unsuccessful.  Error and
6165    warning messages are issued under control of COMPLAIN.  This
6166    conversion is for the Ith parameter in the parameter list.  ARGS is
6167    the full set of template arguments deduced so far.  */
6168
6169 static tree
6170 convert_template_argument (tree parm,
6171                            tree arg,
6172                            tree args,
6173                            tsubst_flags_t complain,
6174                            int i,
6175                            tree in_decl)
6176 {
6177   tree orig_arg;
6178   tree val;
6179   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6180
6181   if (TREE_CODE (arg) == TREE_LIST
6182       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6183     {
6184       /* The template argument was the name of some
6185          member function.  That's usually
6186          invalid, but static members are OK.  In any
6187          case, grab the underlying fields/functions
6188          and issue an error later if required.  */
6189       orig_arg = TREE_VALUE (arg);
6190       TREE_TYPE (arg) = unknown_type_node;
6191     }
6192
6193   orig_arg = arg;
6194
6195   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6196   requires_type = (TREE_CODE (parm) == TYPE_DECL
6197                    || requires_tmpl_type);
6198
6199   /* When determining whether an argument pack expansion is a template,
6200      look at the pattern.  */
6201   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6202     arg = PACK_EXPANSION_PATTERN (arg);
6203
6204   /* Deal with an injected-class-name used as a template template arg.  */
6205   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6206     {
6207       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6208       if (TREE_CODE (t) == TEMPLATE_DECL)
6209         {
6210           if (cxx_dialect >= cxx0x)
6211             /* OK under DR 1004.  */;
6212           else if (complain & tf_warning_or_error)
6213             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6214                      " used as template template argument", TYPE_NAME (arg));
6215           else if (flag_pedantic_errors)
6216             t = arg;
6217
6218           arg = t;
6219         }
6220     }
6221
6222   is_tmpl_type = 
6223     ((TREE_CODE (arg) == TEMPLATE_DECL
6224       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6225      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6226      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6227
6228   if (is_tmpl_type
6229       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6230           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6231     arg = TYPE_STUB_DECL (arg);
6232
6233   is_type = TYPE_P (arg) || is_tmpl_type;
6234
6235   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6236       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6237     {
6238       permerror (input_location, "to refer to a type member of a template parameter, "
6239                  "use %<typename %E%>", orig_arg);
6240
6241       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6242                                      TREE_OPERAND (arg, 1),
6243                                      typename_type,
6244                                      complain & tf_error);
6245       arg = orig_arg;
6246       is_type = 1;
6247     }
6248   if (is_type != requires_type)
6249     {
6250       if (in_decl)
6251         {
6252           if (complain & tf_error)
6253             {
6254               error ("type/value mismatch at argument %d in template "
6255                      "parameter list for %qD",
6256                      i + 1, in_decl);
6257               if (is_type)
6258                 error ("  expected a constant of type %qT, got %qT",
6259                        TREE_TYPE (parm),
6260                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6261               else if (requires_tmpl_type)
6262                 error ("  expected a class template, got %qE", orig_arg);
6263               else
6264                 error ("  expected a type, got %qE", orig_arg);
6265             }
6266         }
6267       return error_mark_node;
6268     }
6269   if (is_tmpl_type ^ requires_tmpl_type)
6270     {
6271       if (in_decl && (complain & tf_error))
6272         {
6273           error ("type/value mismatch at argument %d in template "
6274                  "parameter list for %qD",
6275                  i + 1, in_decl);
6276           if (is_tmpl_type)
6277             error ("  expected a type, got %qT", DECL_NAME (arg));
6278           else
6279             error ("  expected a class template, got %qT", orig_arg);
6280         }
6281       return error_mark_node;
6282     }
6283
6284   if (is_type)
6285     {
6286       if (requires_tmpl_type)
6287         {
6288           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6289             /* The number of argument required is not known yet.
6290                Just accept it for now.  */
6291             val = TREE_TYPE (arg);
6292           else
6293             {
6294               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6295               tree argparm;
6296
6297               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6298
6299               if (coerce_template_template_parms (parmparm, argparm,
6300                                                   complain, in_decl,
6301                                                   args))
6302                 {
6303                   val = arg;
6304
6305                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6306                      TEMPLATE_DECL.  */
6307                   if (val != error_mark_node)
6308                     {
6309                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6310                         val = TREE_TYPE (val);
6311                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6312                         val = make_pack_expansion (val);
6313                     }
6314                 }
6315               else
6316                 {
6317                   if (in_decl && (complain & tf_error))
6318                     {
6319                       error ("type/value mismatch at argument %d in "
6320                              "template parameter list for %qD",
6321                              i + 1, in_decl);
6322                       error ("  expected a template of type %qD, got %qT",
6323                              parm, orig_arg);
6324                     }
6325
6326                   val = error_mark_node;
6327                 }
6328             }
6329         }
6330       else
6331         val = orig_arg;
6332       /* We only form one instance of each template specialization.
6333          Therefore, if we use a non-canonical variant (i.e., a
6334          typedef), any future messages referring to the type will use
6335          the typedef, which is confusing if those future uses do not
6336          themselves also use the typedef.  */
6337       if (TYPE_P (val))
6338         val = canonicalize_type_argument (val, complain);
6339     }
6340   else
6341     {
6342       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6343
6344       if (invalid_nontype_parm_type_p (t, complain))
6345         return error_mark_node;
6346
6347       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6348         {
6349           if (same_type_p (t, TREE_TYPE (orig_arg)))
6350             val = orig_arg;
6351           else
6352             {
6353               /* Not sure if this is reachable, but it doesn't hurt
6354                  to be robust.  */
6355               error ("type mismatch in nontype parameter pack");
6356               val = error_mark_node;
6357             }
6358         }
6359       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6360         /* We used to call digest_init here.  However, digest_init
6361            will report errors, which we don't want when complain
6362            is zero.  More importantly, digest_init will try too
6363            hard to convert things: for example, `0' should not be
6364            converted to pointer type at this point according to
6365            the standard.  Accepting this is not merely an
6366            extension, since deciding whether or not these
6367            conversions can occur is part of determining which
6368            function template to call, or whether a given explicit
6369            argument specification is valid.  */
6370         val = convert_nontype_argument (t, orig_arg, complain);
6371       else
6372         val = orig_arg;
6373
6374       if (val == NULL_TREE)
6375         val = error_mark_node;
6376       else if (val == error_mark_node && (complain & tf_error))
6377         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6378
6379       if (TREE_CODE (val) == SCOPE_REF)
6380         {
6381           /* Strip typedefs from the SCOPE_REF.  */
6382           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6383           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6384                                                    complain);
6385           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6386                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6387         }
6388     }
6389
6390   return val;
6391 }
6392
6393 /* Coerces the remaining template arguments in INNER_ARGS (from
6394    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6395    Returns the coerced argument pack. PARM_IDX is the position of this
6396    parameter in the template parameter list. ARGS is the original
6397    template argument list.  */
6398 static tree
6399 coerce_template_parameter_pack (tree parms,
6400                                 int parm_idx,
6401                                 tree args,
6402                                 tree inner_args,
6403                                 int arg_idx,
6404                                 tree new_args,
6405                                 int* lost,
6406                                 tree in_decl,
6407                                 tsubst_flags_t complain)
6408 {
6409   tree parm = TREE_VEC_ELT (parms, parm_idx);
6410   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6411   tree packed_args;
6412   tree argument_pack;
6413   tree packed_types = NULL_TREE;
6414
6415   if (arg_idx > nargs)
6416     arg_idx = nargs;
6417
6418   packed_args = make_tree_vec (nargs - arg_idx);
6419
6420   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6421       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6422     {
6423       /* When the template parameter is a non-type template
6424          parameter pack whose type uses parameter packs, we need
6425          to look at each of the template arguments
6426          separately. Build a vector of the types for these
6427          non-type template parameters in PACKED_TYPES.  */
6428       tree expansion 
6429         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6430       packed_types = tsubst_pack_expansion (expansion, args,
6431                                             complain, in_decl);
6432
6433       if (packed_types == error_mark_node)
6434         return error_mark_node;
6435
6436       /* Check that we have the right number of arguments.  */
6437       if (arg_idx < nargs
6438           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6439           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6440         {
6441           int needed_parms 
6442             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6443           error ("wrong number of template arguments (%d, should be %d)",
6444                  nargs, needed_parms);
6445           return error_mark_node;
6446         }
6447
6448       /* If we aren't able to check the actual arguments now
6449          (because they haven't been expanded yet), we can at least
6450          verify that all of the types used for the non-type
6451          template parameter pack are, in fact, valid for non-type
6452          template parameters.  */
6453       if (arg_idx < nargs 
6454           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6455         {
6456           int j, len = TREE_VEC_LENGTH (packed_types);
6457           for (j = 0; j < len; ++j)
6458             {
6459               tree t = TREE_VEC_ELT (packed_types, j);
6460               if (invalid_nontype_parm_type_p (t, complain))
6461                 return error_mark_node;
6462             }
6463         }
6464     }
6465
6466   /* Convert the remaining arguments, which will be a part of the
6467      parameter pack "parm".  */
6468   for (; arg_idx < nargs; ++arg_idx)
6469     {
6470       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6471       tree actual_parm = TREE_VALUE (parm);
6472
6473       if (packed_types && !PACK_EXPANSION_P (arg))
6474         {
6475           /* When we have a vector of types (corresponding to the
6476              non-type template parameter pack that uses parameter
6477              packs in its type, as mention above), and the
6478              argument is not an expansion (which expands to a
6479              currently unknown number of arguments), clone the
6480              parm and give it the next type in PACKED_TYPES.  */
6481           actual_parm = copy_node (actual_parm);
6482           TREE_TYPE (actual_parm) = 
6483             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6484         }
6485
6486       if (arg != error_mark_node)
6487         arg = convert_template_argument (actual_parm, 
6488                                          arg, new_args, complain, parm_idx,
6489                                          in_decl);
6490       if (arg == error_mark_node)
6491         (*lost)++;
6492       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6493     }
6494
6495   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6496       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6497     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6498   else
6499     {
6500       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6501       TREE_TYPE (argument_pack) 
6502         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6503       TREE_CONSTANT (argument_pack) = 1;
6504     }
6505
6506   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6507 #ifdef ENABLE_CHECKING
6508   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6509                                        TREE_VEC_LENGTH (packed_args));
6510 #endif
6511   return argument_pack;
6512 }
6513
6514 /* Convert all template arguments to their appropriate types, and
6515    return a vector containing the innermost resulting template
6516    arguments.  If any error occurs, return error_mark_node. Error and
6517    warning messages are issued under control of COMPLAIN.
6518
6519    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6520    for arguments not specified in ARGS.  Otherwise, if
6521    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6522    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6523    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6524    ARGS.  */
6525
6526 static tree
6527 coerce_template_parms (tree parms,
6528                        tree args,
6529                        tree in_decl,
6530                        tsubst_flags_t complain,
6531                        bool require_all_args,
6532                        bool use_default_args)
6533 {
6534   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6535   tree inner_args;
6536   tree new_args;
6537   tree new_inner_args;
6538   int saved_unevaluated_operand;
6539   int saved_inhibit_evaluation_warnings;
6540
6541   /* When used as a boolean value, indicates whether this is a
6542      variadic template parameter list. Since it's an int, we can also
6543      subtract it from nparms to get the number of non-variadic
6544      parameters.  */
6545   int variadic_p = 0;
6546   int post_variadic_parms = 0;
6547
6548   if (args == error_mark_node)
6549     return error_mark_node;
6550
6551   nparms = TREE_VEC_LENGTH (parms);
6552
6553   /* Determine if there are any parameter packs.  */
6554   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6555     {
6556       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6557       if (variadic_p)
6558         ++post_variadic_parms;
6559       if (template_parameter_pack_p (tparm))
6560         ++variadic_p;
6561     }
6562
6563   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6564   /* If there are no parameters that follow a parameter pack, we need to
6565      expand any argument packs so that we can deduce a parameter pack from
6566      some non-packed args followed by an argument pack, as in variadic85.C.
6567      If there are such parameters, we need to leave argument packs intact
6568      so the arguments are assigned properly.  This can happen when dealing
6569      with a nested class inside a partial specialization of a class
6570      template, as in variadic92.C, or when deducing a template parameter pack
6571      from a sub-declarator, as in variadic114.C.  */
6572   if (!post_variadic_parms)
6573     inner_args = expand_template_argument_pack (inner_args);
6574
6575   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6576   if ((nargs > nparms && !variadic_p)
6577       || (nargs < nparms - variadic_p
6578           && require_all_args
6579           && (!use_default_args
6580               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6581                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6582     {
6583       if (complain & tf_error)
6584         {
6585           if (variadic_p)
6586             {
6587               nparms -= variadic_p;
6588               error ("wrong number of template arguments "
6589                      "(%d, should be %d or more)", nargs, nparms);
6590             }
6591           else
6592              error ("wrong number of template arguments "
6593                     "(%d, should be %d)", nargs, nparms);
6594
6595           if (in_decl)
6596             error ("provided for %q+D", in_decl);
6597         }
6598
6599       return error_mark_node;
6600     }
6601
6602   /* We need to evaluate the template arguments, even though this
6603      template-id may be nested within a "sizeof".  */
6604   saved_unevaluated_operand = cp_unevaluated_operand;
6605   cp_unevaluated_operand = 0;
6606   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6607   c_inhibit_evaluation_warnings = 0;
6608   new_inner_args = make_tree_vec (nparms);
6609   new_args = add_outermost_template_args (args, new_inner_args);
6610   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6611     {
6612       tree arg;
6613       tree parm;
6614
6615       /* Get the Ith template parameter.  */
6616       parm = TREE_VEC_ELT (parms, parm_idx);
6617  
6618       if (parm == error_mark_node)
6619       {
6620         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6621         continue;
6622       }
6623
6624       /* Calculate the next argument.  */
6625       if (arg_idx < nargs)
6626         arg = TREE_VEC_ELT (inner_args, arg_idx);
6627       else
6628         arg = NULL_TREE;
6629
6630       if (template_parameter_pack_p (TREE_VALUE (parm))
6631           && !(arg && ARGUMENT_PACK_P (arg)))
6632         {
6633           /* All remaining arguments will be placed in the
6634              template parameter pack PARM.  */
6635           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6636                                                 inner_args, arg_idx,
6637                                                 new_args, &lost,
6638                                                 in_decl, complain);
6639
6640           /* Store this argument.  */
6641           if (arg == error_mark_node)
6642             lost++;
6643           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6644
6645           /* We are done with all of the arguments.  */
6646           arg_idx = nargs;
6647           
6648           continue;
6649         }
6650       else if (arg)
6651         {
6652           if (PACK_EXPANSION_P (arg))
6653             {
6654               if (complain & tf_error)
6655                 {
6656                   /* FIXME this restriction was removed by N2555; see
6657                      bug 35722.  */
6658                   /* If ARG is a pack expansion, but PARM is not a
6659                      template parameter pack (if it were, we would have
6660                      handled it above), we're trying to expand into a
6661                      fixed-length argument list.  */
6662                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6663                     sorry ("cannot expand %<%E%> into a fixed-length "
6664                            "argument list", arg);
6665                   else
6666                     sorry ("cannot expand %<%T%> into a fixed-length "
6667                            "argument list", arg);
6668                 }
6669               ++lost;
6670             }
6671         }
6672       else if (require_all_args)
6673         {
6674           /* There must be a default arg in this case.  */
6675           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6676                                      complain, in_decl);
6677           /* The position of the first default template argument,
6678              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6679              Record that.  */
6680           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6681             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6682         }
6683       else
6684         break;
6685
6686       if (arg == error_mark_node)
6687         {
6688           if (complain & tf_error)
6689             error ("template argument %d is invalid", arg_idx + 1);
6690         }
6691       else if (!arg)
6692         /* This only occurs if there was an error in the template
6693            parameter list itself (which we would already have
6694            reported) that we are trying to recover from, e.g., a class
6695            template with a parameter list such as
6696            template<typename..., typename>.  */
6697         ++lost;
6698       else
6699         arg = convert_template_argument (TREE_VALUE (parm),
6700                                          arg, new_args, complain, 
6701                                          parm_idx, in_decl);
6702
6703       if (arg == error_mark_node)
6704         lost++;
6705       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6706     }
6707   cp_unevaluated_operand = saved_unevaluated_operand;
6708   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6709
6710   if (lost)
6711     return error_mark_node;
6712
6713 #ifdef ENABLE_CHECKING
6714   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6715     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6716                                          TREE_VEC_LENGTH (new_inner_args));
6717 #endif
6718
6719   return new_inner_args;
6720 }
6721
6722 /* Returns 1 if template args OT and NT are equivalent.  */
6723
6724 static int
6725 template_args_equal (tree ot, tree nt)
6726 {
6727   if (nt == ot)
6728     return 1;
6729   if (nt == NULL_TREE || ot == NULL_TREE)
6730     return false;
6731
6732   if (TREE_CODE (nt) == TREE_VEC)
6733     /* For member templates */
6734     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6735   else if (PACK_EXPANSION_P (ot))
6736     return PACK_EXPANSION_P (nt) 
6737       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6738                               PACK_EXPANSION_PATTERN (nt));
6739   else if (ARGUMENT_PACK_P (ot))
6740     {
6741       int i, len;
6742       tree opack, npack;
6743
6744       if (!ARGUMENT_PACK_P (nt))
6745         return 0;
6746
6747       opack = ARGUMENT_PACK_ARGS (ot);
6748       npack = ARGUMENT_PACK_ARGS (nt);
6749       len = TREE_VEC_LENGTH (opack);
6750       if (TREE_VEC_LENGTH (npack) != len)
6751         return 0;
6752       for (i = 0; i < len; ++i)
6753         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6754                                   TREE_VEC_ELT (npack, i)))
6755           return 0;
6756       return 1;
6757     }
6758   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6759     {
6760       /* We get here probably because we are in the middle of substituting
6761          into the pattern of a pack expansion. In that case the
6762          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6763          interested in. So we want to use the initial pack argument for
6764          the comparison.  */
6765       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6766       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6767         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6768       return template_args_equal (ot, nt);
6769     }
6770   else if (TYPE_P (nt))
6771     return TYPE_P (ot) && same_type_p (ot, nt);
6772   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6773     return 0;
6774   else
6775     return cp_tree_equal (ot, nt);
6776 }
6777
6778 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6779    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6780    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6781
6782 static int
6783 comp_template_args_with_info (tree oldargs, tree newargs,
6784                               tree *oldarg_ptr, tree *newarg_ptr)
6785 {
6786   int i;
6787
6788   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6789     return 0;
6790
6791   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6792     {
6793       tree nt = TREE_VEC_ELT (newargs, i);
6794       tree ot = TREE_VEC_ELT (oldargs, i);
6795
6796       if (! template_args_equal (ot, nt))
6797         {
6798           if (oldarg_ptr != NULL)
6799             *oldarg_ptr = ot;
6800           if (newarg_ptr != NULL)
6801             *newarg_ptr = nt;
6802           return 0;
6803         }
6804     }
6805   return 1;
6806 }
6807
6808 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6809    of template arguments.  Returns 0 otherwise.  */
6810
6811 int
6812 comp_template_args (tree oldargs, tree newargs)
6813 {
6814   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6815 }
6816
6817 static void
6818 add_pending_template (tree d)
6819 {
6820   tree ti = (TYPE_P (d)
6821              ? CLASSTYPE_TEMPLATE_INFO (d)
6822              : DECL_TEMPLATE_INFO (d));
6823   struct pending_template *pt;
6824   int level;
6825
6826   if (TI_PENDING_TEMPLATE_FLAG (ti))
6827     return;
6828
6829   /* We are called both from instantiate_decl, where we've already had a
6830      tinst_level pushed, and instantiate_template, where we haven't.
6831      Compensate.  */
6832   level = !current_tinst_level || current_tinst_level->decl != d;
6833
6834   if (level)
6835     push_tinst_level (d);
6836
6837   pt = ggc_alloc_pending_template ();
6838   pt->next = NULL;
6839   pt->tinst = current_tinst_level;
6840   if (last_pending_template)
6841     last_pending_template->next = pt;
6842   else
6843     pending_templates = pt;
6844
6845   last_pending_template = pt;
6846
6847   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6848
6849   if (level)
6850     pop_tinst_level ();
6851 }
6852
6853
6854 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6855    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6856    documentation for TEMPLATE_ID_EXPR.  */
6857
6858 tree
6859 lookup_template_function (tree fns, tree arglist)
6860 {
6861   tree type;
6862
6863   if (fns == error_mark_node || arglist == error_mark_node)
6864     return error_mark_node;
6865
6866   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6867
6868   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6869     {
6870       error ("%q#D is not a function template", fns);
6871       return error_mark_node;
6872     }
6873
6874   if (BASELINK_P (fns))
6875     {
6876       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6877                                          unknown_type_node,
6878                                          BASELINK_FUNCTIONS (fns),
6879                                          arglist);
6880       return fns;
6881     }
6882
6883   type = TREE_TYPE (fns);
6884   if (TREE_CODE (fns) == OVERLOAD || !type)
6885     type = unknown_type_node;
6886
6887   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6888 }
6889
6890 /* Within the scope of a template class S<T>, the name S gets bound
6891    (in build_self_reference) to a TYPE_DECL for the class, not a
6892    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6893    or one of its enclosing classes, and that type is a template,
6894    return the associated TEMPLATE_DECL.  Otherwise, the original
6895    DECL is returned.
6896
6897    Also handle the case when DECL is a TREE_LIST of ambiguous
6898    injected-class-names from different bases.  */
6899
6900 tree
6901 maybe_get_template_decl_from_type_decl (tree decl)
6902 {
6903   if (decl == NULL_TREE)
6904     return decl;
6905
6906   /* DR 176: A lookup that finds an injected-class-name (10.2
6907      [class.member.lookup]) can result in an ambiguity in certain cases
6908      (for example, if it is found in more than one base class). If all of
6909      the injected-class-names that are found refer to specializations of
6910      the same class template, and if the name is followed by a
6911      template-argument-list, the reference refers to the class template
6912      itself and not a specialization thereof, and is not ambiguous.  */
6913   if (TREE_CODE (decl) == TREE_LIST)
6914     {
6915       tree t, tmpl = NULL_TREE;
6916       for (t = decl; t; t = TREE_CHAIN (t))
6917         {
6918           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6919           if (!tmpl)
6920             tmpl = elt;
6921           else if (tmpl != elt)
6922             break;
6923         }
6924       if (tmpl && t == NULL_TREE)
6925         return tmpl;
6926       else
6927         return decl;
6928     }
6929
6930   return (decl != NULL_TREE
6931           && DECL_SELF_REFERENCE_P (decl)
6932           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6933     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6934 }
6935
6936 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6937    parameters, find the desired type.
6938
6939    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6940
6941    IN_DECL, if non-NULL, is the template declaration we are trying to
6942    instantiate.
6943
6944    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6945    the class we are looking up.
6946
6947    Issue error and warning messages under control of COMPLAIN.
6948
6949    If the template class is really a local class in a template
6950    function, then the FUNCTION_CONTEXT is the function in which it is
6951    being instantiated.
6952
6953    ??? Note that this function is currently called *twice* for each
6954    template-id: the first time from the parser, while creating the
6955    incomplete type (finish_template_type), and the second type during the
6956    real instantiation (instantiate_template_class). This is surely something
6957    that we want to avoid. It also causes some problems with argument
6958    coercion (see convert_nontype_argument for more information on this).  */
6959
6960 static tree
6961 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6962                          int entering_scope, tsubst_flags_t complain)
6963 {
6964   tree templ = NULL_TREE, parmlist;
6965   tree t;
6966   spec_entry **slot;
6967   spec_entry *entry;
6968   spec_entry elt;
6969   hashval_t hash;
6970
6971   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6972     {
6973       tree value = innermost_non_namespace_value (d1);
6974       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6975         templ = value;
6976       else
6977         {
6978           if (context)
6979             push_decl_namespace (context);
6980           templ = lookup_name (d1);
6981           templ = maybe_get_template_decl_from_type_decl (templ);
6982           if (context)
6983             pop_decl_namespace ();
6984         }
6985       if (templ)
6986         context = DECL_CONTEXT (templ);
6987     }
6988   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6989     {
6990       tree type = TREE_TYPE (d1);
6991
6992       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6993          an implicit typename for the second A.  Deal with it.  */
6994       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6995         type = TREE_TYPE (type);
6996
6997       if (CLASSTYPE_TEMPLATE_INFO (type))
6998         {
6999           templ = CLASSTYPE_TI_TEMPLATE (type);
7000           d1 = DECL_NAME (templ);
7001         }
7002     }
7003   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7004            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7005     {
7006       templ = TYPE_TI_TEMPLATE (d1);
7007       d1 = DECL_NAME (templ);
7008     }
7009   else if (TREE_CODE (d1) == TEMPLATE_DECL
7010            && DECL_TEMPLATE_RESULT (d1)
7011            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7012     {
7013       templ = d1;
7014       d1 = DECL_NAME (templ);
7015       context = DECL_CONTEXT (templ);
7016     }
7017
7018   /* Issue an error message if we didn't find a template.  */
7019   if (! templ)
7020     {
7021       if (complain & tf_error)
7022         error ("%qT is not a template", d1);
7023       return error_mark_node;
7024     }
7025
7026   if (TREE_CODE (templ) != TEMPLATE_DECL
7027          /* Make sure it's a user visible template, if it was named by
7028             the user.  */
7029       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7030           && !PRIMARY_TEMPLATE_P (templ)))
7031     {
7032       if (complain & tf_error)
7033         {
7034           error ("non-template type %qT used as a template", d1);
7035           if (in_decl)
7036             error ("for template declaration %q+D", in_decl);
7037         }
7038       return error_mark_node;
7039     }
7040
7041   complain &= ~tf_user;
7042
7043   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7044     {
7045       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7046          template arguments */
7047
7048       tree parm;
7049       tree arglist2;
7050       tree outer;
7051
7052       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7053
7054       /* Consider an example where a template template parameter declared as
7055
7056            template <class T, class U = std::allocator<T> > class TT
7057
7058          The template parameter level of T and U are one level larger than
7059          of TT.  To proper process the default argument of U, say when an
7060          instantiation `TT<int>' is seen, we need to build the full
7061          arguments containing {int} as the innermost level.  Outer levels,
7062          available when not appearing as default template argument, can be
7063          obtained from the arguments of the enclosing template.
7064
7065          Suppose that TT is later substituted with std::vector.  The above
7066          instantiation is `TT<int, std::allocator<T> >' with TT at
7067          level 1, and T at level 2, while the template arguments at level 1
7068          becomes {std::vector} and the inner level 2 is {int}.  */
7069
7070       outer = DECL_CONTEXT (templ);
7071       if (outer)
7072         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7073       else if (current_template_parms)
7074         /* This is an argument of the current template, so we haven't set
7075            DECL_CONTEXT yet.  */
7076         outer = current_template_args ();
7077
7078       if (outer)
7079         arglist = add_to_template_args (outer, arglist);
7080
7081       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7082                                         complain,
7083                                         /*require_all_args=*/true,
7084                                         /*use_default_args=*/true);
7085       if (arglist2 == error_mark_node
7086           || (!uses_template_parms (arglist2)
7087               && check_instantiated_args (templ, arglist2, complain)))
7088         return error_mark_node;
7089
7090       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7091       return parm;
7092     }
7093   else
7094     {
7095       tree template_type = TREE_TYPE (templ);
7096       tree gen_tmpl;
7097       tree type_decl;
7098       tree found = NULL_TREE;
7099       int arg_depth;
7100       int parm_depth;
7101       int is_dependent_type;
7102       int use_partial_inst_tmpl = false;
7103
7104       gen_tmpl = most_general_template (templ);
7105       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7106       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7107       arg_depth = TMPL_ARGS_DEPTH (arglist);
7108
7109       if (arg_depth == 1 && parm_depth > 1)
7110         {
7111           /* We've been given an incomplete set of template arguments.
7112              For example, given:
7113
7114                template <class T> struct S1 {
7115                  template <class U> struct S2 {};
7116                  template <class U> struct S2<U*> {};
7117                 };
7118
7119              we will be called with an ARGLIST of `U*', but the
7120              TEMPLATE will be `template <class T> template
7121              <class U> struct S1<T>::S2'.  We must fill in the missing
7122              arguments.  */
7123           arglist
7124             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7125                                            arglist);
7126           arg_depth = TMPL_ARGS_DEPTH (arglist);
7127         }
7128
7129       /* Now we should have enough arguments.  */
7130       gcc_assert (parm_depth == arg_depth);
7131
7132       /* From here on, we're only interested in the most general
7133          template.  */
7134
7135       /* Calculate the BOUND_ARGS.  These will be the args that are
7136          actually tsubst'd into the definition to create the
7137          instantiation.  */
7138       if (parm_depth > 1)
7139         {
7140           /* We have multiple levels of arguments to coerce, at once.  */
7141           int i;
7142           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7143
7144           tree bound_args = make_tree_vec (parm_depth);
7145
7146           for (i = saved_depth,
7147                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7148                i > 0 && t != NULL_TREE;
7149                --i, t = TREE_CHAIN (t))
7150             {
7151               tree a;
7152               if (i == saved_depth)
7153                 a = coerce_template_parms (TREE_VALUE (t),
7154                                            arglist, gen_tmpl,
7155                                            complain,
7156                                            /*require_all_args=*/true,
7157                                            /*use_default_args=*/true);
7158               else
7159                 /* Outer levels should have already been coerced.  */
7160                 a = TMPL_ARGS_LEVEL (arglist, i);
7161
7162               /* Don't process further if one of the levels fails.  */
7163               if (a == error_mark_node)
7164                 {
7165                   /* Restore the ARGLIST to its full size.  */
7166                   TREE_VEC_LENGTH (arglist) = saved_depth;
7167                   return error_mark_node;
7168                 }
7169
7170               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7171
7172               /* We temporarily reduce the length of the ARGLIST so
7173                  that coerce_template_parms will see only the arguments
7174                  corresponding to the template parameters it is
7175                  examining.  */
7176               TREE_VEC_LENGTH (arglist)--;
7177             }
7178
7179           /* Restore the ARGLIST to its full size.  */
7180           TREE_VEC_LENGTH (arglist) = saved_depth;
7181
7182           arglist = bound_args;
7183         }
7184       else
7185         arglist
7186           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7187                                    INNERMOST_TEMPLATE_ARGS (arglist),
7188                                    gen_tmpl,
7189                                    complain,
7190                                    /*require_all_args=*/true,
7191                                    /*use_default_args=*/true);
7192
7193       if (arglist == error_mark_node)
7194         /* We were unable to bind the arguments.  */
7195         return error_mark_node;
7196
7197       /* In the scope of a template class, explicit references to the
7198          template class refer to the type of the template, not any
7199          instantiation of it.  For example, in:
7200
7201            template <class T> class C { void f(C<T>); }
7202
7203          the `C<T>' is just the same as `C'.  Outside of the
7204          class, however, such a reference is an instantiation.  */
7205       if ((entering_scope
7206            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7207            || currently_open_class (template_type))
7208           /* comp_template_args is expensive, check it last.  */
7209           && comp_template_args (TYPE_TI_ARGS (template_type),
7210                                  arglist))
7211         return template_type;
7212
7213       /* If we already have this specialization, return it.  */
7214       elt.tmpl = gen_tmpl;
7215       elt.args = arglist;
7216       hash = hash_specialization (&elt);
7217       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7218                                                   &elt, hash);
7219
7220       if (entry)
7221         return entry->spec;
7222
7223       is_dependent_type = uses_template_parms (arglist);
7224
7225       /* If the deduced arguments are invalid, then the binding
7226          failed.  */
7227       if (!is_dependent_type
7228           && check_instantiated_args (gen_tmpl,
7229                                       INNERMOST_TEMPLATE_ARGS (arglist),
7230                                       complain))
7231         return error_mark_node;
7232
7233       if (!is_dependent_type
7234           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7235           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7236           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7237         {
7238           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7239                                       DECL_NAME (gen_tmpl),
7240                                       /*tag_scope=*/ts_global);
7241           return found;
7242         }
7243
7244       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7245                         complain, in_decl);
7246       if (!context)
7247         context = global_namespace;
7248
7249       /* Create the type.  */
7250       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7251         {
7252           if (!is_dependent_type)
7253             {
7254               set_current_access_from_decl (TYPE_NAME (template_type));
7255               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7256                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7257                                       arglist, complain, in_decl),
7258                               SCOPED_ENUM_P (template_type), NULL);
7259             }
7260           else
7261             {
7262               /* We don't want to call start_enum for this type, since
7263                  the values for the enumeration constants may involve
7264                  template parameters.  And, no one should be interested
7265                  in the enumeration constants for such a type.  */
7266               t = cxx_make_type (ENUMERAL_TYPE);
7267               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7268             }
7269           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7270           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7271             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7272         }
7273       else
7274         {
7275           t = make_class_type (TREE_CODE (template_type));
7276           CLASSTYPE_DECLARED_CLASS (t)
7277             = CLASSTYPE_DECLARED_CLASS (template_type);
7278           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7279           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7280
7281           /* A local class.  Make sure the decl gets registered properly.  */
7282           if (context == current_function_decl)
7283             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7284
7285           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7286             /* This instantiation is another name for the primary
7287                template type. Set the TYPE_CANONICAL field
7288                appropriately. */
7289             TYPE_CANONICAL (t) = template_type;
7290           else if (any_template_arguments_need_structural_equality_p (arglist))
7291             /* Some of the template arguments require structural
7292                equality testing, so this template class requires
7293                structural equality testing. */
7294             SET_TYPE_STRUCTURAL_EQUALITY (t);
7295         }
7296
7297       /* If we called start_enum or pushtag above, this information
7298          will already be set up.  */
7299       if (!TYPE_NAME (t))
7300         {
7301           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7302
7303           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7304           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7305           DECL_SOURCE_LOCATION (type_decl)
7306             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7307         }
7308       else
7309         type_decl = TYPE_NAME (t);
7310
7311       TREE_PRIVATE (type_decl)
7312         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7313       TREE_PROTECTED (type_decl)
7314         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7315       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7316         {
7317           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7318           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7319         }
7320
7321       /* Let's consider the explicit specialization of a member
7322          of a class template specialization that is implicitely instantiated,
7323          e.g.:
7324              template<class T>
7325              struct S
7326              {
7327                template<class U> struct M {}; //#0
7328              };
7329
7330              template<>
7331              template<>
7332              struct S<int>::M<char> //#1
7333              {
7334                int i;
7335              };
7336         [temp.expl.spec]/4 says this is valid.
7337
7338         In this case, when we write:
7339         S<int>::M<char> m;
7340
7341         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7342         the one of #0.
7343
7344         When we encounter #1, we want to store the partial instantiation
7345         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7346
7347         For all cases other than this "explicit specialization of member of a
7348         class template", we just want to store the most general template into
7349         the CLASSTYPE_TI_TEMPLATE of M.
7350
7351         This case of "explicit specialization of member of a class template"
7352         only happens when:
7353         1/ the enclosing class is an instantiation of, and therefore not
7354         the same as, the context of the most general template, and
7355         2/ we aren't looking at the partial instantiation itself, i.e.
7356         the innermost arguments are not the same as the innermost parms of
7357         the most general template.
7358
7359         So it's only when 1/ and 2/ happens that we want to use the partial
7360         instantiation of the member template in lieu of its most general
7361         template.  */
7362
7363       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7364           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7365           /* the enclosing class must be an instantiation...  */
7366           && CLASS_TYPE_P (context)
7367           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7368         {
7369           tree partial_inst_args;
7370           TREE_VEC_LENGTH (arglist)--;
7371           ++processing_template_decl;
7372           partial_inst_args =
7373             tsubst (INNERMOST_TEMPLATE_ARGS
7374                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7375                     arglist, complain, NULL_TREE);
7376           --processing_template_decl;
7377           TREE_VEC_LENGTH (arglist)++;
7378           use_partial_inst_tmpl =
7379             /*...and we must not be looking at the partial instantiation
7380              itself. */
7381             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7382                                  partial_inst_args);
7383         }
7384
7385       if (!use_partial_inst_tmpl)
7386         /* This case is easy; there are no member templates involved.  */
7387         found = gen_tmpl;
7388       else
7389         {
7390           /* This is a full instantiation of a member template.  Find
7391              the partial instantiation of which this is an instance.  */
7392
7393           /* Temporarily reduce by one the number of levels in the ARGLIST
7394              so as to avoid comparing the last set of arguments.  */
7395           TREE_VEC_LENGTH (arglist)--;
7396           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7397           TREE_VEC_LENGTH (arglist)++;
7398           found = CLASSTYPE_TI_TEMPLATE (found);
7399         }
7400
7401       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7402
7403       elt.spec = t;
7404       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7405                                                        &elt, hash, INSERT);
7406       *slot = ggc_alloc_spec_entry ();
7407       **slot = elt;
7408
7409       /* Note this use of the partial instantiation so we can check it
7410          later in maybe_process_partial_specialization.  */
7411       DECL_TEMPLATE_INSTANTIATIONS (templ)
7412         = tree_cons (arglist, t,
7413                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7414
7415       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7416         /* Now that the type has been registered on the instantiations
7417            list, we set up the enumerators.  Because the enumeration
7418            constants may involve the enumeration type itself, we make
7419            sure to register the type first, and then create the
7420            constants.  That way, doing tsubst_expr for the enumeration
7421            constants won't result in recursive calls here; we'll find
7422            the instantiation and exit above.  */
7423         tsubst_enum (template_type, t, arglist);
7424
7425       if (is_dependent_type)
7426         /* If the type makes use of template parameters, the
7427            code that generates debugging information will crash.  */
7428         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7429
7430       /* Possibly limit visibility based on template args.  */
7431       TREE_PUBLIC (type_decl) = 1;
7432       determine_visibility (type_decl);
7433
7434       return t;
7435     }
7436 }
7437
7438 /* Wrapper for lookup_template_class_1.  */
7439
7440 tree
7441 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7442                        int entering_scope, tsubst_flags_t complain)
7443 {
7444   tree ret;
7445   timevar_push (TV_TEMPLATE_INST);
7446   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7447                                  entering_scope, complain);
7448   timevar_pop (TV_TEMPLATE_INST);
7449   return ret;
7450 }
7451 \f
7452 struct pair_fn_data
7453 {
7454   tree_fn_t fn;
7455   void *data;
7456   /* True when we should also visit template parameters that occur in
7457      non-deduced contexts.  */
7458   bool include_nondeduced_p;
7459   struct pointer_set_t *visited;
7460 };
7461
7462 /* Called from for_each_template_parm via walk_tree.  */
7463
7464 static tree
7465 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7466 {
7467   tree t = *tp;
7468   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7469   tree_fn_t fn = pfd->fn;
7470   void *data = pfd->data;
7471
7472   if (TYPE_P (t)
7473       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7474       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7475                                  pfd->include_nondeduced_p))
7476     return error_mark_node;
7477
7478   switch (TREE_CODE (t))
7479     {
7480     case RECORD_TYPE:
7481       if (TYPE_PTRMEMFUNC_P (t))
7482         break;
7483       /* Fall through.  */
7484
7485     case UNION_TYPE:
7486     case ENUMERAL_TYPE:
7487       if (!TYPE_TEMPLATE_INFO (t))
7488         *walk_subtrees = 0;
7489       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7490                                        fn, data, pfd->visited, 
7491                                        pfd->include_nondeduced_p))
7492         return error_mark_node;
7493       break;
7494
7495     case INTEGER_TYPE:
7496       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7497                                   fn, data, pfd->visited, 
7498                                   pfd->include_nondeduced_p)
7499           || for_each_template_parm (TYPE_MAX_VALUE (t),
7500                                      fn, data, pfd->visited,
7501                                      pfd->include_nondeduced_p))
7502         return error_mark_node;
7503       break;
7504
7505     case METHOD_TYPE:
7506       /* Since we're not going to walk subtrees, we have to do this
7507          explicitly here.  */
7508       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7509                                   pfd->visited, pfd->include_nondeduced_p))
7510         return error_mark_node;
7511       /* Fall through.  */
7512
7513     case FUNCTION_TYPE:
7514       /* Check the return type.  */
7515       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7516                                   pfd->include_nondeduced_p))
7517         return error_mark_node;
7518
7519       /* Check the parameter types.  Since default arguments are not
7520          instantiated until they are needed, the TYPE_ARG_TYPES may
7521          contain expressions that involve template parameters.  But,
7522          no-one should be looking at them yet.  And, once they're
7523          instantiated, they don't contain template parameters, so
7524          there's no point in looking at them then, either.  */
7525       {
7526         tree parm;
7527
7528         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7529           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7530                                       pfd->visited, pfd->include_nondeduced_p))
7531             return error_mark_node;
7532
7533         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7534            want walk_tree walking into them itself.  */
7535         *walk_subtrees = 0;
7536       }
7537       break;
7538
7539     case TYPEOF_TYPE:
7540     case UNDERLYING_TYPE:
7541       if (pfd->include_nondeduced_p
7542           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7543                                      pfd->visited, 
7544                                      pfd->include_nondeduced_p))
7545         return error_mark_node;
7546       break;
7547
7548     case FUNCTION_DECL:
7549     case VAR_DECL:
7550       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7551           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7552                                      pfd->visited, pfd->include_nondeduced_p))
7553         return error_mark_node;
7554       /* Fall through.  */
7555
7556     case PARM_DECL:
7557     case CONST_DECL:
7558       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7559           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7560                                      pfd->visited, pfd->include_nondeduced_p))
7561         return error_mark_node;
7562       if (DECL_CONTEXT (t)
7563           && pfd->include_nondeduced_p
7564           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7565                                      pfd->visited, pfd->include_nondeduced_p))
7566         return error_mark_node;
7567       break;
7568
7569     case BOUND_TEMPLATE_TEMPLATE_PARM:
7570       /* Record template parameters such as `T' inside `TT<T>'.  */
7571       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7572                                   pfd->include_nondeduced_p))
7573         return error_mark_node;
7574       /* Fall through.  */
7575
7576     case TEMPLATE_TEMPLATE_PARM:
7577     case TEMPLATE_TYPE_PARM:
7578     case TEMPLATE_PARM_INDEX:
7579       if (fn && (*fn)(t, data))
7580         return error_mark_node;
7581       else if (!fn)
7582         return error_mark_node;
7583       break;
7584
7585     case TEMPLATE_DECL:
7586       /* A template template parameter is encountered.  */
7587       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7588           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7589                                      pfd->include_nondeduced_p))
7590         return error_mark_node;
7591
7592       /* Already substituted template template parameter */
7593       *walk_subtrees = 0;
7594       break;
7595
7596     case TYPENAME_TYPE:
7597       if (!fn
7598           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7599                                      data, pfd->visited, 
7600                                      pfd->include_nondeduced_p))
7601         return error_mark_node;
7602       break;
7603
7604     case CONSTRUCTOR:
7605       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7606           && pfd->include_nondeduced_p
7607           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7608                                      (TREE_TYPE (t)), fn, data,
7609                                      pfd->visited, pfd->include_nondeduced_p))
7610         return error_mark_node;
7611       break;
7612
7613     case INDIRECT_REF:
7614     case COMPONENT_REF:
7615       /* If there's no type, then this thing must be some expression
7616          involving template parameters.  */
7617       if (!fn && !TREE_TYPE (t))
7618         return error_mark_node;
7619       break;
7620
7621     case MODOP_EXPR:
7622     case CAST_EXPR:
7623     case REINTERPRET_CAST_EXPR:
7624     case CONST_CAST_EXPR:
7625     case STATIC_CAST_EXPR:
7626     case DYNAMIC_CAST_EXPR:
7627     case ARROW_EXPR:
7628     case DOTSTAR_EXPR:
7629     case TYPEID_EXPR:
7630     case PSEUDO_DTOR_EXPR:
7631       if (!fn)
7632         return error_mark_node;
7633       break;
7634
7635     default:
7636       break;
7637     }
7638
7639   /* We didn't find any template parameters we liked.  */
7640   return NULL_TREE;
7641 }
7642
7643 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7644    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7645    call FN with the parameter and the DATA.
7646    If FN returns nonzero, the iteration is terminated, and
7647    for_each_template_parm returns 1.  Otherwise, the iteration
7648    continues.  If FN never returns a nonzero value, the value
7649    returned by for_each_template_parm is 0.  If FN is NULL, it is
7650    considered to be the function which always returns 1.
7651
7652    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7653    parameters that occur in non-deduced contexts.  When false, only
7654    visits those template parameters that can be deduced.  */
7655
7656 static int
7657 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7658                         struct pointer_set_t *visited,
7659                         bool include_nondeduced_p)
7660 {
7661   struct pair_fn_data pfd;
7662   int result;
7663
7664   /* Set up.  */
7665   pfd.fn = fn;
7666   pfd.data = data;
7667   pfd.include_nondeduced_p = include_nondeduced_p;
7668
7669   /* Walk the tree.  (Conceptually, we would like to walk without
7670      duplicates, but for_each_template_parm_r recursively calls
7671      for_each_template_parm, so we would need to reorganize a fair
7672      bit to use walk_tree_without_duplicates, so we keep our own
7673      visited list.)  */
7674   if (visited)
7675     pfd.visited = visited;
7676   else
7677     pfd.visited = pointer_set_create ();
7678   result = cp_walk_tree (&t,
7679                          for_each_template_parm_r,
7680                          &pfd,
7681                          pfd.visited) != NULL_TREE;
7682
7683   /* Clean up.  */
7684   if (!visited)
7685     {
7686       pointer_set_destroy (pfd.visited);
7687       pfd.visited = 0;
7688     }
7689
7690   return result;
7691 }
7692
7693 /* Returns true if T depends on any template parameter.  */
7694
7695 int
7696 uses_template_parms (tree t)
7697 {
7698   bool dependent_p;
7699   int saved_processing_template_decl;
7700
7701   saved_processing_template_decl = processing_template_decl;
7702   if (!saved_processing_template_decl)
7703     processing_template_decl = 1;
7704   if (TYPE_P (t))
7705     dependent_p = dependent_type_p (t);
7706   else if (TREE_CODE (t) == TREE_VEC)
7707     dependent_p = any_dependent_template_arguments_p (t);
7708   else if (TREE_CODE (t) == TREE_LIST)
7709     dependent_p = (uses_template_parms (TREE_VALUE (t))
7710                    || uses_template_parms (TREE_CHAIN (t)));
7711   else if (TREE_CODE (t) == TYPE_DECL)
7712     dependent_p = dependent_type_p (TREE_TYPE (t));
7713   else if (DECL_P (t)
7714            || EXPR_P (t)
7715            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7716            || TREE_CODE (t) == OVERLOAD
7717            || TREE_CODE (t) == BASELINK
7718            || TREE_CODE (t) == IDENTIFIER_NODE
7719            || TREE_CODE (t) == TRAIT_EXPR
7720            || TREE_CODE (t) == CONSTRUCTOR
7721            || CONSTANT_CLASS_P (t))
7722     dependent_p = (type_dependent_expression_p (t)
7723                    || value_dependent_expression_p (t));
7724   else
7725     {
7726       gcc_assert (t == error_mark_node);
7727       dependent_p = false;
7728     }
7729
7730   processing_template_decl = saved_processing_template_decl;
7731
7732   return dependent_p;
7733 }
7734
7735 /* Returns true if T depends on any template parameter with level LEVEL.  */
7736
7737 int
7738 uses_template_parms_level (tree t, int level)
7739 {
7740   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7741                                  /*include_nondeduced_p=*/true);
7742 }
7743
7744 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7745    ill-formed translation unit, i.e. a variable or function that isn't
7746    usable in a constant expression.  */
7747
7748 static inline bool
7749 neglectable_inst_p (tree d)
7750 {
7751   return (DECL_P (d)
7752           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7753                : decl_maybe_constant_var_p (d)));
7754 }
7755
7756 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7757    neglectable and instantiated from within an erroneous instantiation.  */
7758
7759 static bool
7760 limit_bad_template_recursion (tree decl)
7761 {
7762   struct tinst_level *lev = current_tinst_level;
7763   int errs = errorcount + sorrycount;
7764   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7765     return false;
7766
7767   for (; lev; lev = lev->next)
7768     if (neglectable_inst_p (lev->decl))
7769       break;
7770
7771   return (lev && errs > lev->errors);
7772 }
7773
7774 static int tinst_depth;
7775 extern int max_tinst_depth;
7776 #ifdef GATHER_STATISTICS
7777 int depth_reached;
7778 #endif
7779 static GTY(()) struct tinst_level *last_error_tinst_level;
7780
7781 /* We're starting to instantiate D; record the template instantiation context
7782    for diagnostics and to restore it later.  */
7783
7784 int
7785 push_tinst_level (tree d)
7786 {
7787   struct tinst_level *new_level;
7788
7789   if (tinst_depth >= max_tinst_depth)
7790     {
7791       last_error_tinst_level = current_tinst_level;
7792       if (TREE_CODE (d) == TREE_LIST)
7793         error ("template instantiation depth exceeds maximum of %d (use "
7794                "-ftemplate-depth= to increase the maximum) substituting %qS",
7795                max_tinst_depth, d);
7796       else
7797         error ("template instantiation depth exceeds maximum of %d (use "
7798                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7799                max_tinst_depth, d);
7800
7801       print_instantiation_context ();
7802
7803       return 0;
7804     }
7805
7806   /* If the current instantiation caused problems, don't let it instantiate
7807      anything else.  Do allow deduction substitution and decls usable in
7808      constant expressions.  */
7809   if (limit_bad_template_recursion (d))
7810     return 0;
7811
7812   new_level = ggc_alloc_tinst_level ();
7813   new_level->decl = d;
7814   new_level->locus = input_location;
7815   new_level->errors = errorcount+sorrycount;
7816   new_level->in_system_header_p = in_system_header;
7817   new_level->next = current_tinst_level;
7818   current_tinst_level = new_level;
7819
7820   ++tinst_depth;
7821 #ifdef GATHER_STATISTICS
7822   if (tinst_depth > depth_reached)
7823     depth_reached = tinst_depth;
7824 #endif
7825
7826   return 1;
7827 }
7828
7829 /* We're done instantiating this template; return to the instantiation
7830    context.  */
7831
7832 void
7833 pop_tinst_level (void)
7834 {
7835   /* Restore the filename and line number stashed away when we started
7836      this instantiation.  */
7837   input_location = current_tinst_level->locus;
7838   current_tinst_level = current_tinst_level->next;
7839   --tinst_depth;
7840 }
7841
7842 /* We're instantiating a deferred template; restore the template
7843    instantiation context in which the instantiation was requested, which
7844    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7845
7846 static tree
7847 reopen_tinst_level (struct tinst_level *level)
7848 {
7849   struct tinst_level *t;
7850
7851   tinst_depth = 0;
7852   for (t = level; t; t = t->next)
7853     ++tinst_depth;
7854
7855   current_tinst_level = level;
7856   pop_tinst_level ();
7857   if (current_tinst_level)
7858     current_tinst_level->errors = errorcount+sorrycount;
7859   return level->decl;
7860 }
7861
7862 /* Returns the TINST_LEVEL which gives the original instantiation
7863    context.  */
7864
7865 struct tinst_level *
7866 outermost_tinst_level (void)
7867 {
7868   struct tinst_level *level = current_tinst_level;
7869   if (level)
7870     while (level->next)
7871       level = level->next;
7872   return level;
7873 }
7874
7875 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7876
7877 bool
7878 parameter_of_template_p (tree parm, tree templ)
7879 {
7880   tree parms;
7881   int i;
7882
7883   if (!parm || !templ)
7884     return false;
7885
7886   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7887   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7888
7889   parms = DECL_TEMPLATE_PARMS (templ);
7890   parms = INNERMOST_TEMPLATE_PARMS (parms);
7891
7892   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7893     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7894       return true;
7895
7896   return false;
7897 }
7898
7899 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7900    vector of template arguments, as for tsubst.
7901
7902    Returns an appropriate tsubst'd friend declaration.  */
7903
7904 static tree
7905 tsubst_friend_function (tree decl, tree args)
7906 {
7907   tree new_friend;
7908
7909   if (TREE_CODE (decl) == FUNCTION_DECL
7910       && DECL_TEMPLATE_INSTANTIATION (decl)
7911       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7912     /* This was a friend declared with an explicit template
7913        argument list, e.g.:
7914
7915        friend void f<>(T);
7916
7917        to indicate that f was a template instantiation, not a new
7918        function declaration.  Now, we have to figure out what
7919        instantiation of what template.  */
7920     {
7921       tree template_id, arglist, fns;
7922       tree new_args;
7923       tree tmpl;
7924       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7925
7926       /* Friend functions are looked up in the containing namespace scope.
7927          We must enter that scope, to avoid finding member functions of the
7928          current class with same name.  */
7929       push_nested_namespace (ns);
7930       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7931                          tf_warning_or_error, NULL_TREE,
7932                          /*integral_constant_expression_p=*/false);
7933       pop_nested_namespace (ns);
7934       arglist = tsubst (DECL_TI_ARGS (decl), args,
7935                         tf_warning_or_error, NULL_TREE);
7936       template_id = lookup_template_function (fns, arglist);
7937
7938       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7939       tmpl = determine_specialization (template_id, new_friend,
7940                                        &new_args,
7941                                        /*need_member_template=*/0,
7942                                        TREE_VEC_LENGTH (args),
7943                                        tsk_none);
7944       return instantiate_template (tmpl, new_args, tf_error);
7945     }
7946
7947   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7948
7949   /* The NEW_FRIEND will look like an instantiation, to the
7950      compiler, but is not an instantiation from the point of view of
7951      the language.  For example, we might have had:
7952
7953      template <class T> struct S {
7954        template <class U> friend void f(T, U);
7955      };
7956
7957      Then, in S<int>, template <class U> void f(int, U) is not an
7958      instantiation of anything.  */
7959   if (new_friend == error_mark_node)
7960     return error_mark_node;
7961
7962   DECL_USE_TEMPLATE (new_friend) = 0;
7963   if (TREE_CODE (decl) == TEMPLATE_DECL)
7964     {
7965       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7966       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7967         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7968     }
7969
7970   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7971      is not a template instantiation and should not be mangled like
7972      one.  Therefore, we forget the mangling here; we'll recompute it
7973      later if we need it.  */
7974   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7975     {
7976       SET_DECL_RTL (new_friend, NULL);
7977       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7978     }
7979
7980   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7981     {
7982       tree old_decl;
7983       tree new_friend_template_info;
7984       tree new_friend_result_template_info;
7985       tree ns;
7986       int  new_friend_is_defn;
7987
7988       /* We must save some information from NEW_FRIEND before calling
7989          duplicate decls since that function will free NEW_FRIEND if
7990          possible.  */
7991       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7992       new_friend_is_defn =
7993             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7994                            (template_for_substitution (new_friend)))
7995              != NULL_TREE);
7996       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7997         {
7998           /* This declaration is a `primary' template.  */
7999           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8000
8001           new_friend_result_template_info
8002             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8003         }
8004       else
8005         new_friend_result_template_info = NULL_TREE;
8006
8007       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8008       if (new_friend_is_defn)
8009         DECL_INITIAL (new_friend) = error_mark_node;
8010
8011       /* Inside pushdecl_namespace_level, we will push into the
8012          current namespace. However, the friend function should go
8013          into the namespace of the template.  */
8014       ns = decl_namespace_context (new_friend);
8015       push_nested_namespace (ns);
8016       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8017       pop_nested_namespace (ns);
8018
8019       if (old_decl == error_mark_node)
8020         return error_mark_node;
8021
8022       if (old_decl != new_friend)
8023         {
8024           /* This new friend declaration matched an existing
8025              declaration.  For example, given:
8026
8027                template <class T> void f(T);
8028                template <class U> class C {
8029                  template <class T> friend void f(T) {}
8030                };
8031
8032              the friend declaration actually provides the definition
8033              of `f', once C has been instantiated for some type.  So,
8034              old_decl will be the out-of-class template declaration,
8035              while new_friend is the in-class definition.
8036
8037              But, if `f' was called before this point, the
8038              instantiation of `f' will have DECL_TI_ARGS corresponding
8039              to `T' but not to `U', references to which might appear
8040              in the definition of `f'.  Previously, the most general
8041              template for an instantiation of `f' was the out-of-class
8042              version; now it is the in-class version.  Therefore, we
8043              run through all specialization of `f', adding to their
8044              DECL_TI_ARGS appropriately.  In particular, they need a
8045              new set of outer arguments, corresponding to the
8046              arguments for this class instantiation.
8047
8048              The same situation can arise with something like this:
8049
8050                friend void f(int);
8051                template <class T> class C {
8052                  friend void f(T) {}
8053                };
8054
8055              when `C<int>' is instantiated.  Now, `f(int)' is defined
8056              in the class.  */
8057
8058           if (!new_friend_is_defn)
8059             /* On the other hand, if the in-class declaration does
8060                *not* provide a definition, then we don't want to alter
8061                existing definitions.  We can just leave everything
8062                alone.  */
8063             ;
8064           else
8065             {
8066               tree new_template = TI_TEMPLATE (new_friend_template_info);
8067               tree new_args = TI_ARGS (new_friend_template_info);
8068
8069               /* Overwrite whatever template info was there before, if
8070                  any, with the new template information pertaining to
8071                  the declaration.  */
8072               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8073
8074               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8075                 {
8076                   /* We should have called reregister_specialization in
8077                      duplicate_decls.  */
8078                   gcc_assert (retrieve_specialization (new_template,
8079                                                        new_args, 0)
8080                               == old_decl);
8081
8082                   /* Instantiate it if the global has already been used.  */
8083                   if (DECL_ODR_USED (old_decl))
8084                     instantiate_decl (old_decl, /*defer_ok=*/true,
8085                                       /*expl_inst_class_mem_p=*/false);
8086                 }
8087               else
8088                 {
8089                   tree t;
8090
8091                   /* Indicate that the old function template is a partial
8092                      instantiation.  */
8093                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8094                     = new_friend_result_template_info;
8095
8096                   gcc_assert (new_template
8097                               == most_general_template (new_template));
8098                   gcc_assert (new_template != old_decl);
8099
8100                   /* Reassign any specializations already in the hash table
8101                      to the new more general template, and add the
8102                      additional template args.  */
8103                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8104                        t != NULL_TREE;
8105                        t = TREE_CHAIN (t))
8106                     {
8107                       tree spec = TREE_VALUE (t);
8108                       spec_entry elt;
8109
8110                       elt.tmpl = old_decl;
8111                       elt.args = DECL_TI_ARGS (spec);
8112                       elt.spec = NULL_TREE;
8113
8114                       htab_remove_elt (decl_specializations, &elt);
8115
8116                       DECL_TI_ARGS (spec)
8117                         = add_outermost_template_args (new_args,
8118                                                        DECL_TI_ARGS (spec));
8119
8120                       register_specialization
8121                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8122
8123                     }
8124                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8125                 }
8126             }
8127
8128           /* The information from NEW_FRIEND has been merged into OLD_DECL
8129              by duplicate_decls.  */
8130           new_friend = old_decl;
8131         }
8132     }
8133   else
8134     {
8135       tree context = DECL_CONTEXT (new_friend);
8136       bool dependent_p;
8137
8138       /* In the code
8139            template <class T> class C {
8140              template <class U> friend void C1<U>::f (); // case 1
8141              friend void C2<T>::f ();                    // case 2
8142            };
8143          we only need to make sure CONTEXT is a complete type for
8144          case 2.  To distinguish between the two cases, we note that
8145          CONTEXT of case 1 remains dependent type after tsubst while
8146          this isn't true for case 2.  */
8147       ++processing_template_decl;
8148       dependent_p = dependent_type_p (context);
8149       --processing_template_decl;
8150
8151       if (!dependent_p
8152           && !complete_type_or_else (context, NULL_TREE))
8153         return error_mark_node;
8154
8155       if (COMPLETE_TYPE_P (context))
8156         {
8157           /* Check to see that the declaration is really present, and,
8158              possibly obtain an improved declaration.  */
8159           tree fn = check_classfn (context,
8160                                    new_friend, NULL_TREE);
8161
8162           if (fn)
8163             new_friend = fn;
8164         }
8165     }
8166
8167   return new_friend;
8168 }
8169
8170 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8171    template arguments, as for tsubst.
8172
8173    Returns an appropriate tsubst'd friend type or error_mark_node on
8174    failure.  */
8175
8176 static tree
8177 tsubst_friend_class (tree friend_tmpl, tree args)
8178 {
8179   tree friend_type;
8180   tree tmpl;
8181   tree context;
8182
8183   context = CP_DECL_CONTEXT (friend_tmpl);
8184
8185   if (context != global_namespace)
8186     {
8187       if (TREE_CODE (context) == NAMESPACE_DECL)
8188         push_nested_namespace (context);
8189       else
8190         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8191     }
8192
8193   /* Look for a class template declaration.  We look for hidden names
8194      because two friend declarations of the same template are the
8195      same.  For example, in:
8196
8197        struct A { 
8198          template <typename> friend class F;
8199        };
8200        template <typename> struct B { 
8201          template <typename> friend class F;
8202        };
8203
8204      both F templates are the same.  */
8205   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8206                            /*block_p=*/true, 0, 
8207                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8208
8209   /* But, if we don't find one, it might be because we're in a
8210      situation like this:
8211
8212        template <class T>
8213        struct S {
8214          template <class U>
8215          friend struct S;
8216        };
8217
8218      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8219      for `S<int>', not the TEMPLATE_DECL.  */
8220   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8221     {
8222       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8223       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8224     }
8225
8226   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8227     {
8228       /* The friend template has already been declared.  Just
8229          check to see that the declarations match, and install any new
8230          default parameters.  We must tsubst the default parameters,
8231          of course.  We only need the innermost template parameters
8232          because that is all that redeclare_class_template will look
8233          at.  */
8234       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8235           > TMPL_ARGS_DEPTH (args))
8236         {
8237           tree parms;
8238           location_t saved_input_location;
8239           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8240                                          args, tf_warning_or_error);
8241
8242           saved_input_location = input_location;
8243           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8244           redeclare_class_template (TREE_TYPE (tmpl), parms);
8245           input_location = saved_input_location;
8246           
8247         }
8248
8249       friend_type = TREE_TYPE (tmpl);
8250     }
8251   else
8252     {
8253       /* The friend template has not already been declared.  In this
8254          case, the instantiation of the template class will cause the
8255          injection of this template into the global scope.  */
8256       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8257       if (tmpl == error_mark_node)
8258         return error_mark_node;
8259
8260       /* The new TMPL is not an instantiation of anything, so we
8261          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8262          the new type because that is supposed to be the corresponding
8263          template decl, i.e., TMPL.  */
8264       DECL_USE_TEMPLATE (tmpl) = 0;
8265       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8266       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8267       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8268         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8269
8270       /* Inject this template into the global scope.  */
8271       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8272     }
8273
8274   if (context != global_namespace)
8275     {
8276       if (TREE_CODE (context) == NAMESPACE_DECL)
8277         pop_nested_namespace (context);
8278       else
8279         pop_nested_class ();
8280     }
8281
8282   return friend_type;
8283 }
8284
8285 /* Returns zero if TYPE cannot be completed later due to circularity.
8286    Otherwise returns one.  */
8287
8288 static int
8289 can_complete_type_without_circularity (tree type)
8290 {
8291   if (type == NULL_TREE || type == error_mark_node)
8292     return 0;
8293   else if (COMPLETE_TYPE_P (type))
8294     return 1;
8295   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8296     return can_complete_type_without_circularity (TREE_TYPE (type));
8297   else if (CLASS_TYPE_P (type)
8298            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8299     return 0;
8300   else
8301     return 1;
8302 }
8303
8304 /* Apply any attributes which had to be deferred until instantiation
8305    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8306    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8307
8308 static void
8309 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8310                                 tree args, tsubst_flags_t complain, tree in_decl)
8311 {
8312   tree last_dep = NULL_TREE;
8313   tree t;
8314   tree *p;
8315
8316   for (t = attributes; t; t = TREE_CHAIN (t))
8317     if (ATTR_IS_DEPENDENT (t))
8318       {
8319         last_dep = t;
8320         attributes = copy_list (attributes);
8321         break;
8322       }
8323
8324   if (DECL_P (*decl_p))
8325     {
8326       if (TREE_TYPE (*decl_p) == error_mark_node)
8327         return;
8328       p = &DECL_ATTRIBUTES (*decl_p);
8329     }
8330   else
8331     p = &TYPE_ATTRIBUTES (*decl_p);
8332
8333   if (last_dep)
8334     {
8335       tree late_attrs = NULL_TREE;
8336       tree *q = &late_attrs;
8337
8338       for (*p = attributes; *p; )
8339         {
8340           t = *p;
8341           if (ATTR_IS_DEPENDENT (t))
8342             {
8343               *p = TREE_CHAIN (t);
8344               TREE_CHAIN (t) = NULL_TREE;
8345               /* If the first attribute argument is an identifier, don't
8346                  pass it through tsubst.  Attributes like mode, format,
8347                  cleanup and several target specific attributes expect it
8348                  unmodified.  */
8349               if (TREE_VALUE (t)
8350                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8351                   && TREE_VALUE (TREE_VALUE (t))
8352                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8353                       == IDENTIFIER_NODE))
8354                 {
8355                   tree chain
8356                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8357                                    in_decl,
8358                                    /*integral_constant_expression_p=*/false);
8359                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8360                     TREE_VALUE (t)
8361                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8362                                    chain);
8363                 }
8364               else
8365                 TREE_VALUE (t)
8366                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8367                                  /*integral_constant_expression_p=*/false);
8368               *q = t;
8369               q = &TREE_CHAIN (t);
8370             }
8371           else
8372             p = &TREE_CHAIN (t);
8373         }
8374
8375       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8376     }
8377 }
8378
8379 /* Perform (or defer) access check for typedefs that were referenced
8380    from within the template TMPL code.
8381    This is a subroutine of instantiate_template and instantiate_class_template.
8382    TMPL is the template to consider and TARGS is the list of arguments of
8383    that template.  */
8384
8385 static void
8386 perform_typedefs_access_check (tree tmpl, tree targs)
8387 {
8388   location_t saved_location;
8389   int i;
8390   qualified_typedef_usage_t *iter;
8391
8392   if (!tmpl
8393       || (!CLASS_TYPE_P (tmpl)
8394           && TREE_CODE (tmpl) != FUNCTION_DECL))
8395     return;
8396
8397   saved_location = input_location;
8398   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8399                     get_types_needing_access_check (tmpl),
8400                     i, iter)
8401     {
8402       tree type_decl = iter->typedef_decl;
8403       tree type_scope = iter->context;
8404
8405       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8406         continue;
8407
8408       if (uses_template_parms (type_decl))
8409         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8410       if (uses_template_parms (type_scope))
8411         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8412
8413       /* Make access check error messages point to the location
8414          of the use of the typedef.  */
8415       input_location = iter->locus;
8416       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8417                                      type_decl, type_decl);
8418     }
8419     input_location = saved_location;
8420 }
8421
8422 static tree
8423 instantiate_class_template_1 (tree type)
8424 {
8425   tree templ, args, pattern, t, member;
8426   tree typedecl;
8427   tree pbinfo;
8428   tree base_list;
8429   unsigned int saved_maximum_field_alignment;
8430
8431   if (type == error_mark_node)
8432     return error_mark_node;
8433
8434   if (COMPLETE_OR_OPEN_TYPE_P (type)
8435       || uses_template_parms (type))
8436     return type;
8437
8438   /* Figure out which template is being instantiated.  */
8439   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8440   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8441
8442   /* Determine what specialization of the original template to
8443      instantiate.  */
8444   t = most_specialized_class (type, templ, tf_warning_or_error);
8445   if (t == error_mark_node)
8446     {
8447       TYPE_BEING_DEFINED (type) = 1;
8448       return error_mark_node;
8449     }
8450   else if (t)
8451     {
8452       /* This TYPE is actually an instantiation of a partial
8453          specialization.  We replace the innermost set of ARGS with
8454          the arguments appropriate for substitution.  For example,
8455          given:
8456
8457            template <class T> struct S {};
8458            template <class T> struct S<T*> {};
8459
8460          and supposing that we are instantiating S<int*>, ARGS will
8461          presently be {int*} -- but we need {int}.  */
8462       pattern = TREE_TYPE (t);
8463       args = TREE_PURPOSE (t);
8464     }
8465   else
8466     {
8467       pattern = TREE_TYPE (templ);
8468       args = CLASSTYPE_TI_ARGS (type);
8469     }
8470
8471   /* If the template we're instantiating is incomplete, then clearly
8472      there's nothing we can do.  */
8473   if (!COMPLETE_TYPE_P (pattern))
8474     return type;
8475
8476   /* If we've recursively instantiated too many templates, stop.  */
8477   if (! push_tinst_level (type))
8478     return type;
8479
8480   /* Now we're really doing the instantiation.  Mark the type as in
8481      the process of being defined.  */
8482   TYPE_BEING_DEFINED (type) = 1;
8483
8484   /* We may be in the middle of deferred access check.  Disable
8485      it now.  */
8486   push_deferring_access_checks (dk_no_deferred);
8487
8488   push_to_top_level ();
8489   /* Use #pragma pack from the template context.  */
8490   saved_maximum_field_alignment = maximum_field_alignment;
8491   maximum_field_alignment = TYPE_PRECISION (pattern);
8492
8493   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8494
8495   /* Set the input location to the most specialized template definition.
8496      This is needed if tsubsting causes an error.  */
8497   typedecl = TYPE_MAIN_DECL (pattern);
8498   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8499     DECL_SOURCE_LOCATION (typedecl);
8500
8501   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8502   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8503   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8504   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8505   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8506   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8507   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8508   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8509   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8510   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8511   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8512   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8513   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8514   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8515   if (ANON_AGGR_TYPE_P (pattern))
8516     SET_ANON_AGGR_TYPE_P (type);
8517   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8518     {
8519       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8520       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8521     }
8522   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8523
8524   pbinfo = TYPE_BINFO (pattern);
8525
8526   /* We should never instantiate a nested class before its enclosing
8527      class; we need to look up the nested class by name before we can
8528      instantiate it, and that lookup should instantiate the enclosing
8529      class.  */
8530   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8531               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8532
8533   base_list = NULL_TREE;
8534   if (BINFO_N_BASE_BINFOS (pbinfo))
8535     {
8536       tree pbase_binfo;
8537       tree pushed_scope;
8538       int i;
8539
8540       /* We must enter the scope containing the type, as that is where
8541          the accessibility of types named in dependent bases are
8542          looked up from.  */
8543       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8544
8545       /* Substitute into each of the bases to determine the actual
8546          basetypes.  */
8547       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8548         {
8549           tree base;
8550           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8551           tree expanded_bases = NULL_TREE;
8552           int idx, len = 1;
8553
8554           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8555             {
8556               expanded_bases = 
8557                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8558                                        args, tf_error, NULL_TREE);
8559               if (expanded_bases == error_mark_node)
8560                 continue;
8561
8562               len = TREE_VEC_LENGTH (expanded_bases);
8563             }
8564
8565           for (idx = 0; idx < len; idx++)
8566             {
8567               if (expanded_bases)
8568                 /* Extract the already-expanded base class.  */
8569                 base = TREE_VEC_ELT (expanded_bases, idx);
8570               else
8571                 /* Substitute to figure out the base class.  */
8572                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8573                                NULL_TREE);
8574
8575               if (base == error_mark_node)
8576                 continue;
8577
8578               base_list = tree_cons (access, base, base_list);
8579               if (BINFO_VIRTUAL_P (pbase_binfo))
8580                 TREE_TYPE (base_list) = integer_type_node;
8581             }
8582         }
8583
8584       /* The list is now in reverse order; correct that.  */
8585       base_list = nreverse (base_list);
8586
8587       if (pushed_scope)
8588         pop_scope (pushed_scope);
8589     }
8590   /* Now call xref_basetypes to set up all the base-class
8591      information.  */
8592   xref_basetypes (type, base_list);
8593
8594   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8595                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8596                                   args, tf_error, NULL_TREE);
8597   fixup_attribute_variants (type);
8598
8599   /* Now that our base classes are set up, enter the scope of the
8600      class, so that name lookups into base classes, etc. will work
8601      correctly.  This is precisely analogous to what we do in
8602      begin_class_definition when defining an ordinary non-template
8603      class, except we also need to push the enclosing classes.  */
8604   push_nested_class (type);
8605
8606   /* Now members are processed in the order of declaration.  */
8607   for (member = CLASSTYPE_DECL_LIST (pattern);
8608        member; member = TREE_CHAIN (member))
8609     {
8610       tree t = TREE_VALUE (member);
8611
8612       if (TREE_PURPOSE (member))
8613         {
8614           if (TYPE_P (t))
8615             {
8616               /* Build new CLASSTYPE_NESTED_UTDS.  */
8617
8618               tree newtag;
8619               bool class_template_p;
8620
8621               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8622                                   && TYPE_LANG_SPECIFIC (t)
8623                                   && CLASSTYPE_IS_TEMPLATE (t));
8624               /* If the member is a class template, then -- even after
8625                  substitution -- there may be dependent types in the
8626                  template argument list for the class.  We increment
8627                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8628                  that function will assume that no types are dependent
8629                  when outside of a template.  */
8630               if (class_template_p)
8631                 ++processing_template_decl;
8632               newtag = tsubst (t, args, tf_error, NULL_TREE);
8633               if (class_template_p)
8634                 --processing_template_decl;
8635               if (newtag == error_mark_node)
8636                 continue;
8637
8638               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8639                 {
8640                   tree name = TYPE_IDENTIFIER (t);
8641
8642                   if (class_template_p)
8643                     /* Unfortunately, lookup_template_class sets
8644                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8645                        instantiation (i.e., for the type of a member
8646                        template class nested within a template class.)
8647                        This behavior is required for
8648                        maybe_process_partial_specialization to work
8649                        correctly, but is not accurate in this case;
8650                        the TAG is not an instantiation of anything.
8651                        (The corresponding TEMPLATE_DECL is an
8652                        instantiation, but the TYPE is not.) */
8653                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8654
8655                   /* Now, we call pushtag to put this NEWTAG into the scope of
8656                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8657                      pushtag calling push_template_decl.  We don't have to do
8658                      this for enums because it will already have been done in
8659                      tsubst_enum.  */
8660                   if (name)
8661                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8662                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8663                 }
8664             }
8665           else if (TREE_CODE (t) == FUNCTION_DECL
8666                    || DECL_FUNCTION_TEMPLATE_P (t))
8667             {
8668               /* Build new TYPE_METHODS.  */
8669               tree r;
8670
8671               if (TREE_CODE (t) == TEMPLATE_DECL)
8672                 ++processing_template_decl;
8673               r = tsubst (t, args, tf_error, NULL_TREE);
8674               if (TREE_CODE (t) == TEMPLATE_DECL)
8675                 --processing_template_decl;
8676               set_current_access_from_decl (r);
8677               finish_member_declaration (r);
8678               /* Instantiate members marked with attribute used.  */
8679               if (r != error_mark_node && DECL_PRESERVE_P (r))
8680                 mark_used (r);
8681             }
8682           else
8683             {
8684               /* Build new TYPE_FIELDS.  */
8685               if (TREE_CODE (t) == STATIC_ASSERT)
8686                 {
8687                   tree condition = 
8688                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8689                                  tf_warning_or_error, NULL_TREE,
8690                                  /*integral_constant_expression_p=*/true);
8691                   finish_static_assert (condition,
8692                                         STATIC_ASSERT_MESSAGE (t), 
8693                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8694                                         /*member_p=*/true);
8695                 }
8696               else if (TREE_CODE (t) != CONST_DECL)
8697                 {
8698                   tree r;
8699
8700                   /* The file and line for this declaration, to
8701                      assist in error message reporting.  Since we
8702                      called push_tinst_level above, we don't need to
8703                      restore these.  */
8704                   input_location = DECL_SOURCE_LOCATION (t);
8705
8706                   if (TREE_CODE (t) == TEMPLATE_DECL)
8707                     ++processing_template_decl;
8708                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8709                   if (TREE_CODE (t) == TEMPLATE_DECL)
8710                     --processing_template_decl;
8711                   if (TREE_CODE (r) == VAR_DECL)
8712                     {
8713                       /* In [temp.inst]:
8714
8715                            [t]he initialization (and any associated
8716                            side-effects) of a static data member does
8717                            not occur unless the static data member is
8718                            itself used in a way that requires the
8719                            definition of the static data member to
8720                            exist.
8721
8722                          Therefore, we do not substitute into the
8723                          initialized for the static data member here.  */
8724                       finish_static_data_member_decl
8725                         (r,
8726                          /*init=*/NULL_TREE,
8727                          /*init_const_expr_p=*/false,
8728                          /*asmspec_tree=*/NULL_TREE,
8729                          /*flags=*/0);
8730                       /* Instantiate members marked with attribute used.  */
8731                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8732                         mark_used (r);
8733                     }
8734                   else if (TREE_CODE (r) == FIELD_DECL)
8735                     {
8736                       /* Determine whether R has a valid type and can be
8737                          completed later.  If R is invalid, then it is
8738                          replaced by error_mark_node so that it will not be
8739                          added to TYPE_FIELDS.  */
8740                       tree rtype = TREE_TYPE (r);
8741                       if (can_complete_type_without_circularity (rtype))
8742                         complete_type (rtype);
8743
8744                       if (!COMPLETE_TYPE_P (rtype))
8745                         {
8746                           cxx_incomplete_type_error (r, rtype);
8747                           r = error_mark_node;
8748                         }
8749                     }
8750
8751                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8752                      such a thing will already have been added to the field
8753                      list by tsubst_enum in finish_member_declaration in the
8754                      CLASSTYPE_NESTED_UTDS case above.  */
8755                   if (!(TREE_CODE (r) == TYPE_DECL
8756                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8757                         && DECL_ARTIFICIAL (r)))
8758                     {
8759                       set_current_access_from_decl (r);
8760                       finish_member_declaration (r);
8761                     }
8762                 }
8763             }
8764         }
8765       else
8766         {
8767           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8768             {
8769               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8770
8771               tree friend_type = t;
8772               bool adjust_processing_template_decl = false;
8773
8774               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8775                 {
8776                   /* template <class T> friend class C;  */
8777                   friend_type = tsubst_friend_class (friend_type, args);
8778                   adjust_processing_template_decl = true;
8779                 }
8780               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8781                 {
8782                   /* template <class T> friend class C::D;  */
8783                   friend_type = tsubst (friend_type, args,
8784                                         tf_warning_or_error, NULL_TREE);
8785                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8786                     friend_type = TREE_TYPE (friend_type);
8787                   adjust_processing_template_decl = true;
8788                 }
8789               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8790                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8791                 {
8792                   /* This could be either
8793
8794                        friend class T::C;
8795
8796                      when dependent_type_p is false or
8797
8798                        template <class U> friend class T::C;
8799
8800                      otherwise.  */
8801                   friend_type = tsubst (friend_type, args,
8802                                         tf_warning_or_error, NULL_TREE);
8803                   /* Bump processing_template_decl for correct
8804                      dependent_type_p calculation.  */
8805                   ++processing_template_decl;
8806                   if (dependent_type_p (friend_type))
8807                     adjust_processing_template_decl = true;
8808                   --processing_template_decl;
8809                 }
8810               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8811                        && hidden_name_p (TYPE_NAME (friend_type)))
8812                 {
8813                   /* friend class C;
8814
8815                      where C hasn't been declared yet.  Let's lookup name
8816                      from namespace scope directly, bypassing any name that
8817                      come from dependent base class.  */
8818                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8819
8820                   /* The call to xref_tag_from_type does injection for friend
8821                      classes.  */
8822                   push_nested_namespace (ns);
8823                   friend_type =
8824                     xref_tag_from_type (friend_type, NULL_TREE,
8825                                         /*tag_scope=*/ts_current);
8826                   pop_nested_namespace (ns);
8827                 }
8828               else if (uses_template_parms (friend_type))
8829                 /* friend class C<T>;  */
8830                 friend_type = tsubst (friend_type, args,
8831                                       tf_warning_or_error, NULL_TREE);
8832               /* Otherwise it's
8833
8834                    friend class C;
8835
8836                  where C is already declared or
8837
8838                    friend class C<int>;
8839
8840                  We don't have to do anything in these cases.  */
8841
8842               if (adjust_processing_template_decl)
8843                 /* Trick make_friend_class into realizing that the friend
8844                    we're adding is a template, not an ordinary class.  It's
8845                    important that we use make_friend_class since it will
8846                    perform some error-checking and output cross-reference
8847                    information.  */
8848                 ++processing_template_decl;
8849
8850               if (friend_type != error_mark_node)
8851                 make_friend_class (type, friend_type, /*complain=*/false);
8852
8853               if (adjust_processing_template_decl)
8854                 --processing_template_decl;
8855             }
8856           else
8857             {
8858               /* Build new DECL_FRIENDLIST.  */
8859               tree r;
8860
8861               /* The file and line for this declaration, to
8862                  assist in error message reporting.  Since we
8863                  called push_tinst_level above, we don't need to
8864                  restore these.  */
8865               input_location = DECL_SOURCE_LOCATION (t);
8866
8867               if (TREE_CODE (t) == TEMPLATE_DECL)
8868                 {
8869                   ++processing_template_decl;
8870                   push_deferring_access_checks (dk_no_check);
8871                 }
8872
8873               r = tsubst_friend_function (t, args);
8874               add_friend (type, r, /*complain=*/false);
8875               if (TREE_CODE (t) == TEMPLATE_DECL)
8876                 {
8877                   pop_deferring_access_checks ();
8878                   --processing_template_decl;
8879                 }
8880             }
8881         }
8882     }
8883
8884   if (CLASSTYPE_LAMBDA_EXPR (type))
8885     maybe_add_lambda_conv_op (type);
8886
8887   /* Set the file and line number information to whatever is given for
8888      the class itself.  This puts error messages involving generated
8889      implicit functions at a predictable point, and the same point
8890      that would be used for non-template classes.  */
8891   input_location = DECL_SOURCE_LOCATION (typedecl);
8892
8893   unreverse_member_declarations (type);
8894   finish_struct_1 (type);
8895   TYPE_BEING_DEFINED (type) = 0;
8896
8897   /* We don't instantiate default arguments for member functions.  14.7.1:
8898
8899      The implicit instantiation of a class template specialization causes
8900      the implicit instantiation of the declarations, but not of the
8901      definitions or default arguments, of the class member functions,
8902      member classes, static data members and member templates....  */
8903
8904   /* Some typedefs referenced from within the template code need to be access
8905      checked at template instantiation time, i.e now. These types were
8906      added to the template at parsing time. Let's get those and perform
8907      the access checks then.  */
8908   perform_typedefs_access_check (pattern, args);
8909   perform_deferred_access_checks ();
8910   pop_nested_class ();
8911   maximum_field_alignment = saved_maximum_field_alignment;
8912   pop_from_top_level ();
8913   pop_deferring_access_checks ();
8914   pop_tinst_level ();
8915
8916   /* The vtable for a template class can be emitted in any translation
8917      unit in which the class is instantiated.  When there is no key
8918      method, however, finish_struct_1 will already have added TYPE to
8919      the keyed_classes list.  */
8920   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8921     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8922
8923   return type;
8924 }
8925
8926 /* Wrapper for instantiate_class_template_1.  */
8927
8928 tree
8929 instantiate_class_template (tree type)
8930 {
8931   tree ret;
8932   timevar_push (TV_TEMPLATE_INST);
8933   ret = instantiate_class_template_1 (type);
8934   timevar_pop (TV_TEMPLATE_INST);
8935   return ret;
8936 }
8937
8938 static tree
8939 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8940 {
8941   tree r;
8942
8943   if (!t)
8944     r = t;
8945   else if (TYPE_P (t))
8946     r = tsubst (t, args, complain, in_decl);
8947   else
8948     {
8949       if (!(complain & tf_warning))
8950         ++c_inhibit_evaluation_warnings;
8951       r = tsubst_expr (t, args, complain, in_decl,
8952                        /*integral_constant_expression_p=*/true);
8953       if (!(complain & tf_warning))
8954         --c_inhibit_evaluation_warnings;
8955       /* Preserve the raw-reference nature of T.  */
8956       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
8957           && REFERENCE_REF_P (r))
8958         r = TREE_OPERAND (r, 0);
8959     }
8960   return r;
8961 }
8962
8963 /* Given a function parameter pack TMPL_PARM and some function parameters
8964    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
8965    and set *SPEC_P to point at the next point in the list.  */
8966
8967 static tree
8968 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
8969 {
8970   /* Collect all of the extra "packed" parameters into an
8971      argument pack.  */
8972   tree parmvec;
8973   tree parmtypevec;
8974   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8975   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8976   tree spec_parm = *spec_p;
8977   int i, len;
8978
8979   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
8980     if (tmpl_parm
8981         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
8982       break;
8983
8984   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8985   parmvec = make_tree_vec (len);
8986   parmtypevec = make_tree_vec (len);
8987   spec_parm = *spec_p;
8988   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8989     {
8990       TREE_VEC_ELT (parmvec, i) = spec_parm;
8991       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8992     }
8993
8994   /* Build the argument packs.  */
8995   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8996   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8997   TREE_TYPE (argpack) = argtypepack;
8998   *spec_p = spec_parm;
8999
9000   return argpack;
9001 }
9002
9003 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9004    NONTYPE_ARGUMENT_PACK.  */
9005
9006 static tree
9007 make_fnparm_pack (tree spec_parm)
9008 {
9009   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9010 }
9011
9012 /* Substitute ARGS into T, which is an pack expansion
9013    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9014    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9015    (if only a partial substitution could be performed) or
9016    ERROR_MARK_NODE if there was an error.  */
9017 tree
9018 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9019                        tree in_decl)
9020 {
9021   tree pattern;
9022   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
9023   int i, len = -1;
9024   tree result;
9025   int incomplete = 0;
9026   htab_t saved_local_specializations = NULL;
9027
9028   gcc_assert (PACK_EXPANSION_P (t));
9029   pattern = PACK_EXPANSION_PATTERN (t);
9030
9031   /* Determine the argument packs that will instantiate the parameter
9032      packs used in the expansion expression. While we're at it,
9033      compute the number of arguments to be expanded and make sure it
9034      is consistent.  */
9035   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9036        pack = TREE_CHAIN (pack))
9037     {
9038       tree parm_pack = TREE_VALUE (pack);
9039       tree arg_pack = NULL_TREE;
9040       tree orig_arg = NULL_TREE;
9041
9042       if (TREE_CODE (parm_pack) == PARM_DECL)
9043         {
9044           if (!cp_unevaluated_operand)
9045             arg_pack = retrieve_local_specialization (parm_pack);
9046           else
9047             {
9048               /* We can't rely on local_specializations for a parameter
9049                  name used later in a function declaration (such as in a
9050                  late-specified return type).  Even if it exists, it might
9051                  have the wrong value for a recursive call.  Just make a
9052                  dummy decl, since it's only used for its type.  */
9053               arg_pack = tsubst_decl (parm_pack, args, complain);
9054               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9055                 /* Partial instantiation of the parm_pack, we can't build
9056                    up an argument pack yet.  */
9057                 arg_pack = NULL_TREE;
9058               else
9059                 arg_pack = make_fnparm_pack (arg_pack);
9060             }
9061         }
9062       else
9063         {
9064           int level, idx, levels;
9065           template_parm_level_and_index (parm_pack, &level, &idx);
9066
9067           levels = TMPL_ARGS_DEPTH (args);
9068           if (level <= levels)
9069             arg_pack = TMPL_ARG (args, level, idx);
9070         }
9071
9072       orig_arg = arg_pack;
9073       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9074         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9075       
9076       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9077         /* This can only happen if we forget to expand an argument
9078            pack somewhere else. Just return an error, silently.  */
9079         {
9080           result = make_tree_vec (1);
9081           TREE_VEC_ELT (result, 0) = error_mark_node;
9082           return result;
9083         }
9084
9085       /* For clarity in the comments below let's use the
9086          representation 'argument_pack<elements>' to denote an
9087          argument pack and its elements.
9088
9089          In the 'if' block below, we want to detect cases where
9090          ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
9091          check if ARG_PACK is an argument pack which sole element is
9092          the expansion of PARM_PACK.  That argument pack is typically
9093          created by template_parm_to_arg when passed a parameter
9094          pack.  */
9095       if (arg_pack
9096           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
9097           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
9098         {
9099           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
9100           tree pattern = PACK_EXPANSION_PATTERN (expansion);
9101           /* So we have an argument_pack<P...>.  We want to test if P
9102              is actually PARM_PACK.  We will not use cp_tree_equal to
9103              test P and PARM_PACK because during type fixup (by
9104              fixup_template_parm) P can be a pre-fixup version of a
9105              type and PARM_PACK be its post-fixup version.
9106              cp_tree_equal would consider them as different even
9107              though we would want to consider them compatible for our
9108              precise purpose here.
9109
9110              Thus we are going to consider that P and PARM_PACK are
9111              compatible if they have the same DECL.  */
9112           if ((/* If ARG_PACK is a type parameter pack named by the
9113                   same DECL as parm_pack ...  */
9114                (TYPE_P (pattern)
9115                 && TYPE_P (parm_pack)
9116                 && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
9117                /* ... or if ARG_PACK is a non-type parameter
9118                   named by the same DECL as parm_pack ...  */
9119                || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
9120                    && TREE_CODE (parm_pack) == PARM_DECL
9121                    && TEMPLATE_PARM_DECL (pattern)
9122                    == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
9123               && template_parameter_pack_p (pattern))
9124             /* ... then the argument pack that the parameter maps to
9125                is just an expansion of the parameter itself, such as
9126                one would find in the implicit typedef of a class
9127                inside the class itself.  Consider this parameter
9128                "unsubstituted", so that we will maintain the outer
9129                pack expansion.  */
9130             arg_pack = NULL_TREE;
9131         }
9132           
9133       if (arg_pack)
9134         {
9135           int my_len = 
9136             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9137
9138           /* It's all-or-nothing with incomplete argument packs.  */
9139           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9140             return error_mark_node;
9141           
9142           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9143             incomplete = 1;
9144
9145           if (len < 0)
9146             len = my_len;
9147           else if (len != my_len)
9148             {
9149               if (incomplete)
9150                 /* We got explicit args for some packs but not others;
9151                    do nothing now and try again after deduction.  */
9152                 return t;
9153               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9154                 error ("mismatched argument pack lengths while expanding "
9155                        "%<%T%>",
9156                        pattern);
9157               else
9158                 error ("mismatched argument pack lengths while expanding "
9159                        "%<%E%>",
9160                        pattern);
9161               return error_mark_node;
9162             }
9163
9164           /* Keep track of the parameter packs and their corresponding
9165              argument packs.  */
9166           packs = tree_cons (parm_pack, arg_pack, packs);
9167           TREE_TYPE (packs) = orig_arg;
9168         }
9169       else
9170         /* We can't substitute for this parameter pack.  */
9171         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
9172                                          TREE_VALUE (pack),
9173                                          unsubstituted_packs);
9174     }
9175
9176   /* We cannot expand this expansion expression, because we don't have
9177      all of the argument packs we need. Substitute into the pattern
9178      and return a PACK_EXPANSION_*. The caller will need to deal with
9179      that.  */
9180   if (unsubstituted_packs)
9181     {
9182       tree new_pat;
9183       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9184         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9185                                /*integral_constant_expression_p=*/false);
9186       else
9187         new_pat = tsubst (pattern, args, complain, in_decl);
9188       return make_pack_expansion (new_pat);
9189     }
9190
9191   /* We could not find any argument packs that work.  */
9192   if (len < 0)
9193     return error_mark_node;
9194
9195   if (cp_unevaluated_operand)
9196     {
9197       /* We're in a late-specified return type, so create our own local
9198          specializations table; the current table is either NULL or (in the
9199          case of recursive unification) might have bindings that we don't
9200          want to use or alter.  */
9201       saved_local_specializations = local_specializations;
9202       local_specializations = htab_create (37,
9203                                            hash_local_specialization,
9204                                            eq_local_specializations,
9205                                            NULL);
9206     }
9207
9208   /* For each argument in each argument pack, substitute into the
9209      pattern.  */
9210   result = make_tree_vec (len + incomplete);
9211   for (i = 0; i < len + incomplete; ++i)
9212     {
9213       /* For parameter pack, change the substitution of the parameter
9214          pack to the ith argument in its argument pack, then expand
9215          the pattern.  */
9216       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9217         {
9218           tree parm = TREE_PURPOSE (pack);
9219
9220           if (TREE_CODE (parm) == PARM_DECL)
9221             {
9222               /* Select the Ith argument from the pack.  */
9223               tree arg = make_node (ARGUMENT_PACK_SELECT);
9224               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9225               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9226               mark_used (parm);
9227               register_local_specialization (arg, parm);
9228             }
9229           else
9230             {
9231               tree value = parm;
9232               int idx, level;
9233               template_parm_level_and_index (parm, &level, &idx);
9234               
9235               if (i < len) 
9236                 {
9237                   /* Select the Ith argument from the pack. */
9238                   value = make_node (ARGUMENT_PACK_SELECT);
9239                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
9240                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
9241                 }
9242
9243               /* Update the corresponding argument.  */
9244               TMPL_ARG (args, level, idx) = value;
9245             }
9246         }
9247
9248       /* Substitute into the PATTERN with the altered arguments.  */
9249       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9250         TREE_VEC_ELT (result, i) = 
9251           tsubst_expr (pattern, args, complain, in_decl,
9252                        /*integral_constant_expression_p=*/false);
9253       else
9254         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9255
9256       if (i == len)
9257         /* When we have incomplete argument packs, the last "expanded"
9258            result is itself a pack expansion, which allows us
9259            to deduce more arguments.  */
9260         TREE_VEC_ELT (result, i) = 
9261           make_pack_expansion (TREE_VEC_ELT (result, i));
9262
9263       if (TREE_VEC_ELT (result, i) == error_mark_node)
9264         {
9265           result = error_mark_node;
9266           break;
9267         }
9268     }
9269
9270   /* Update ARGS to restore the substitution from parameter packs to
9271      their argument packs.  */
9272   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9273     {
9274       tree parm = TREE_PURPOSE (pack);
9275
9276       if (TREE_CODE (parm) == PARM_DECL)
9277         register_local_specialization (TREE_TYPE (pack), parm);
9278       else
9279         {
9280           int idx, level;
9281           template_parm_level_and_index (parm, &level, &idx);
9282           
9283           /* Update the corresponding argument.  */
9284           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9285             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9286               TREE_TYPE (pack);
9287           else
9288             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9289         }
9290     }
9291
9292   if (saved_local_specializations)
9293     {
9294       htab_delete (local_specializations);
9295       local_specializations = saved_local_specializations;
9296     }
9297   
9298   return result;
9299 }
9300
9301 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9302    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9303    parameter packs; all parms generated from a function parameter pack will
9304    have the same DECL_PARM_INDEX.  */
9305
9306 tree
9307 get_pattern_parm (tree parm, tree tmpl)
9308 {
9309   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9310   tree patparm;
9311
9312   if (DECL_ARTIFICIAL (parm))
9313     {
9314       for (patparm = DECL_ARGUMENTS (pattern);
9315            patparm; patparm = DECL_CHAIN (patparm))
9316         if (DECL_ARTIFICIAL (patparm)
9317             && DECL_NAME (parm) == DECL_NAME (patparm))
9318           break;
9319     }
9320   else
9321     {
9322       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9323       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9324       gcc_assert (DECL_PARM_INDEX (patparm)
9325                   == DECL_PARM_INDEX (parm));
9326     }
9327
9328   return patparm;
9329 }
9330
9331 /* Substitute ARGS into the vector or list of template arguments T.  */
9332
9333 static tree
9334 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9335 {
9336   tree orig_t = t;
9337   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9338   tree *elts;
9339
9340   if (t == error_mark_node)
9341     return error_mark_node;
9342
9343   len = TREE_VEC_LENGTH (t);
9344   elts = XALLOCAVEC (tree, len);
9345
9346   for (i = 0; i < len; i++)
9347     {
9348       tree orig_arg = TREE_VEC_ELT (t, i);
9349       tree new_arg;
9350
9351       if (TREE_CODE (orig_arg) == TREE_VEC)
9352         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9353       else if (PACK_EXPANSION_P (orig_arg))
9354         {
9355           /* Substitute into an expansion expression.  */
9356           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9357
9358           if (TREE_CODE (new_arg) == TREE_VEC)
9359             /* Add to the expanded length adjustment the number of
9360                expanded arguments. We subtract one from this
9361                measurement, because the argument pack expression
9362                itself is already counted as 1 in
9363                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9364                the argument pack is empty.  */
9365             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9366         }
9367       else if (ARGUMENT_PACK_P (orig_arg))
9368         {
9369           /* Substitute into each of the arguments.  */
9370           new_arg = TYPE_P (orig_arg)
9371             ? cxx_make_type (TREE_CODE (orig_arg))
9372             : make_node (TREE_CODE (orig_arg));
9373           
9374           SET_ARGUMENT_PACK_ARGS (
9375             new_arg,
9376             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9377                                   args, complain, in_decl));
9378
9379           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9380             new_arg = error_mark_node;
9381
9382           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9383             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9384                                           complain, in_decl);
9385             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9386
9387             if (TREE_TYPE (new_arg) == error_mark_node)
9388               new_arg = error_mark_node;
9389           }
9390         }
9391       else
9392         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9393
9394       if (new_arg == error_mark_node)
9395         return error_mark_node;
9396
9397       elts[i] = new_arg;
9398       if (new_arg != orig_arg)
9399         need_new = 1;
9400     }
9401
9402   if (!need_new)
9403     return t;
9404
9405   /* Make space for the expanded arguments coming from template
9406      argument packs.  */
9407   t = make_tree_vec (len + expanded_len_adjust);
9408   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9409      arguments for a member template.
9410      In that case each TREE_VEC in ORIG_T represents a level of template
9411      arguments, and ORIG_T won't carry any non defaulted argument count.
9412      It will rather be the nested TREE_VECs that will carry one.
9413      In other words, ORIG_T carries a non defaulted argument count only
9414      if it doesn't contain any nested TREE_VEC.  */
9415   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9416     {
9417       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9418       count += expanded_len_adjust;
9419       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9420     }
9421   for (i = 0, out = 0; i < len; i++)
9422     {
9423       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9424            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9425           && TREE_CODE (elts[i]) == TREE_VEC)
9426         {
9427           int idx;
9428
9429           /* Now expand the template argument pack "in place".  */
9430           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9431             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9432         }
9433       else
9434         {
9435           TREE_VEC_ELT (t, out) = elts[i];
9436           out++;
9437         }
9438     }
9439
9440   return t;
9441 }
9442
9443 /* Return the result of substituting ARGS into the template parameters
9444    given by PARMS.  If there are m levels of ARGS and m + n levels of
9445    PARMS, then the result will contain n levels of PARMS.  For
9446    example, if PARMS is `template <class T> template <class U>
9447    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9448    result will be `template <int*, double, class V>'.  */
9449
9450 static tree
9451 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9452 {
9453   tree r = NULL_TREE;
9454   tree* new_parms;
9455
9456   /* When substituting into a template, we must set
9457      PROCESSING_TEMPLATE_DECL as the template parameters may be
9458      dependent if they are based on one-another, and the dependency
9459      predicates are short-circuit outside of templates.  */
9460   ++processing_template_decl;
9461
9462   for (new_parms = &r;
9463        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9464        new_parms = &(TREE_CHAIN (*new_parms)),
9465          parms = TREE_CHAIN (parms))
9466     {
9467       tree new_vec =
9468         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9469       int i;
9470
9471       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9472         {
9473           tree tuple;
9474
9475           if (parms == error_mark_node)
9476             continue;
9477
9478           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9479
9480           if (tuple == error_mark_node)
9481             continue;
9482
9483           TREE_VEC_ELT (new_vec, i) =
9484             tsubst_template_parm (tuple, args, complain);
9485         }
9486
9487       *new_parms =
9488         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9489                              - TMPL_ARGS_DEPTH (args)),
9490                    new_vec, NULL_TREE);
9491     }
9492
9493   --processing_template_decl;
9494
9495   return r;
9496 }
9497
9498 /* Return the result of substituting ARGS into one template parameter
9499    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9500    parameter and which TREE_PURPOSE is the default argument of the
9501    template parameter.  */
9502
9503 static tree
9504 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9505 {
9506   tree default_value, parm_decl;
9507
9508   if (args == NULL_TREE
9509       || t == NULL_TREE
9510       || t == error_mark_node)
9511     return t;
9512
9513   gcc_assert (TREE_CODE (t) == TREE_LIST);
9514
9515   default_value = TREE_PURPOSE (t);
9516   parm_decl = TREE_VALUE (t);
9517
9518   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9519   if (TREE_CODE (parm_decl) == PARM_DECL
9520       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9521     parm_decl = error_mark_node;
9522   default_value = tsubst_template_arg (default_value, args,
9523                                        complain, NULL_TREE);
9524
9525   return build_tree_list (default_value, parm_decl);
9526 }
9527
9528 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9529    type T.  If T is not an aggregate or enumeration type, it is
9530    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9531    ENTERING_SCOPE is nonzero, T is the context for a template which
9532    we are presently tsubst'ing.  Return the substituted value.  */
9533
9534 static tree
9535 tsubst_aggr_type (tree t,
9536                   tree args,
9537                   tsubst_flags_t complain,
9538                   tree in_decl,
9539                   int entering_scope)
9540 {
9541   if (t == NULL_TREE)
9542     return NULL_TREE;
9543
9544   switch (TREE_CODE (t))
9545     {
9546     case RECORD_TYPE:
9547       if (TYPE_PTRMEMFUNC_P (t))
9548         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9549
9550       /* Else fall through.  */
9551     case ENUMERAL_TYPE:
9552     case UNION_TYPE:
9553       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9554         {
9555           tree argvec;
9556           tree context;
9557           tree r;
9558           int saved_unevaluated_operand;
9559           int saved_inhibit_evaluation_warnings;
9560
9561           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9562           saved_unevaluated_operand = cp_unevaluated_operand;
9563           cp_unevaluated_operand = 0;
9564           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9565           c_inhibit_evaluation_warnings = 0;
9566
9567           /* First, determine the context for the type we are looking
9568              up.  */
9569           context = TYPE_CONTEXT (t);
9570           if (context)
9571             {
9572               context = tsubst_aggr_type (context, args, complain,
9573                                           in_decl, /*entering_scope=*/1);
9574               /* If context is a nested class inside a class template,
9575                  it may still need to be instantiated (c++/33959).  */
9576               if (TYPE_P (context))
9577                 context = complete_type (context);
9578             }
9579
9580           /* Then, figure out what arguments are appropriate for the
9581              type we are trying to find.  For example, given:
9582
9583                template <class T> struct S;
9584                template <class T, class U> void f(T, U) { S<U> su; }
9585
9586              and supposing that we are instantiating f<int, double>,
9587              then our ARGS will be {int, double}, but, when looking up
9588              S we only want {double}.  */
9589           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9590                                          complain, in_decl);
9591           if (argvec == error_mark_node)
9592             r = error_mark_node;
9593           else
9594             {
9595               r = lookup_template_class (t, argvec, in_decl, context,
9596                                          entering_scope, complain);
9597               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9598             }
9599
9600           cp_unevaluated_operand = saved_unevaluated_operand;
9601           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9602
9603           return r;
9604         }
9605       else
9606         /* This is not a template type, so there's nothing to do.  */
9607         return t;
9608
9609     default:
9610       return tsubst (t, args, complain, in_decl);
9611     }
9612 }
9613
9614 /* Substitute into the default argument ARG (a default argument for
9615    FN), which has the indicated TYPE.  */
9616
9617 tree
9618 tsubst_default_argument (tree fn, tree type, tree arg)
9619 {
9620   tree saved_class_ptr = NULL_TREE;
9621   tree saved_class_ref = NULL_TREE;
9622
9623   /* This can happen in invalid code.  */
9624   if (TREE_CODE (arg) == DEFAULT_ARG)
9625     return arg;
9626
9627   /* This default argument came from a template.  Instantiate the
9628      default argument here, not in tsubst.  In the case of
9629      something like:
9630
9631        template <class T>
9632        struct S {
9633          static T t();
9634          void f(T = t());
9635        };
9636
9637      we must be careful to do name lookup in the scope of S<T>,
9638      rather than in the current class.  */
9639   push_access_scope (fn);
9640   /* The "this" pointer is not valid in a default argument.  */
9641   if (cfun)
9642     {
9643       saved_class_ptr = current_class_ptr;
9644       cp_function_chain->x_current_class_ptr = NULL_TREE;
9645       saved_class_ref = current_class_ref;
9646       cp_function_chain->x_current_class_ref = NULL_TREE;
9647     }
9648
9649   push_deferring_access_checks(dk_no_deferred);
9650   /* The default argument expression may cause implicitly defined
9651      member functions to be synthesized, which will result in garbage
9652      collection.  We must treat this situation as if we were within
9653      the body of function so as to avoid collecting live data on the
9654      stack.  */
9655   ++function_depth;
9656   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9657                      tf_warning_or_error, NULL_TREE,
9658                      /*integral_constant_expression_p=*/false);
9659   --function_depth;
9660   pop_deferring_access_checks();
9661
9662   /* Restore the "this" pointer.  */
9663   if (cfun)
9664     {
9665       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9666       cp_function_chain->x_current_class_ref = saved_class_ref;
9667     }
9668
9669   /* Make sure the default argument is reasonable.  */
9670   arg = check_default_argument (type, arg);
9671
9672   pop_access_scope (fn);
9673
9674   return arg;
9675 }
9676
9677 /* Substitute into all the default arguments for FN.  */
9678
9679 static void
9680 tsubst_default_arguments (tree fn)
9681 {
9682   tree arg;
9683   tree tmpl_args;
9684
9685   tmpl_args = DECL_TI_ARGS (fn);
9686
9687   /* If this function is not yet instantiated, we certainly don't need
9688      its default arguments.  */
9689   if (uses_template_parms (tmpl_args))
9690     return;
9691   /* Don't do this again for clones.  */
9692   if (DECL_CLONED_FUNCTION_P (fn))
9693     return;
9694
9695   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9696        arg;
9697        arg = TREE_CHAIN (arg))
9698     if (TREE_PURPOSE (arg))
9699       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9700                                                     TREE_VALUE (arg),
9701                                                     TREE_PURPOSE (arg));
9702 }
9703
9704 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9705    result of the substitution.  Issue error and warning messages under
9706    control of COMPLAIN.  */
9707
9708 static tree
9709 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9710 {
9711 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9712   location_t saved_loc;
9713   tree r = NULL_TREE;
9714   tree in_decl = t;
9715   hashval_t hash = 0;
9716
9717   /* Set the filename and linenumber to improve error-reporting.  */
9718   saved_loc = input_location;
9719   input_location = DECL_SOURCE_LOCATION (t);
9720
9721   switch (TREE_CODE (t))
9722     {
9723     case TEMPLATE_DECL:
9724       {
9725         /* We can get here when processing a member function template,
9726            member class template, or template template parameter.  */
9727         tree decl = DECL_TEMPLATE_RESULT (t);
9728         tree spec;
9729         tree tmpl_args;
9730         tree full_args;
9731
9732         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9733           {
9734             /* Template template parameter is treated here.  */
9735             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9736             if (new_type == error_mark_node)
9737               RETURN (error_mark_node);
9738
9739             r = copy_decl (t);
9740             DECL_CHAIN (r) = NULL_TREE;
9741             TREE_TYPE (r) = new_type;
9742             DECL_TEMPLATE_RESULT (r)
9743               = build_decl (DECL_SOURCE_LOCATION (decl),
9744                             TYPE_DECL, DECL_NAME (decl), new_type);
9745             DECL_TEMPLATE_PARMS (r)
9746               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9747                                        complain);
9748             TYPE_NAME (new_type) = r;
9749             break;
9750           }
9751
9752         /* We might already have an instance of this template.
9753            The ARGS are for the surrounding class type, so the
9754            full args contain the tsubst'd args for the context,
9755            plus the innermost args from the template decl.  */
9756         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9757           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9758           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9759         /* Because this is a template, the arguments will still be
9760            dependent, even after substitution.  If
9761            PROCESSING_TEMPLATE_DECL is not set, the dependency
9762            predicates will short-circuit.  */
9763         ++processing_template_decl;
9764         full_args = tsubst_template_args (tmpl_args, args,
9765                                           complain, in_decl);
9766         --processing_template_decl;
9767         if (full_args == error_mark_node)
9768           RETURN (error_mark_node);
9769
9770         /* If this is a default template template argument,
9771            tsubst might not have changed anything.  */
9772         if (full_args == tmpl_args)
9773           RETURN (t);
9774
9775         hash = hash_tmpl_and_args (t, full_args);
9776         spec = retrieve_specialization (t, full_args, hash);
9777         if (spec != NULL_TREE)
9778           {
9779             r = spec;
9780             break;
9781           }
9782
9783         /* Make a new template decl.  It will be similar to the
9784            original, but will record the current template arguments.
9785            We also create a new function declaration, which is just
9786            like the old one, but points to this new template, rather
9787            than the old one.  */
9788         r = copy_decl (t);
9789         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9790         DECL_CHAIN (r) = NULL_TREE;
9791
9792         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9793
9794         if (TREE_CODE (decl) == TYPE_DECL)
9795           {
9796             tree new_type;
9797             ++processing_template_decl;
9798             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9799             --processing_template_decl;
9800             if (new_type == error_mark_node)
9801               RETURN (error_mark_node);
9802
9803             TREE_TYPE (r) = new_type;
9804             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9805             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9806             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9807             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9808           }
9809         else
9810           {
9811             tree new_decl;
9812             ++processing_template_decl;
9813             new_decl = tsubst (decl, args, complain, in_decl);
9814             --processing_template_decl;
9815             if (new_decl == error_mark_node)
9816               RETURN (error_mark_node);
9817
9818             DECL_TEMPLATE_RESULT (r) = new_decl;
9819             DECL_TI_TEMPLATE (new_decl) = r;
9820             TREE_TYPE (r) = TREE_TYPE (new_decl);
9821             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9822             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9823           }
9824
9825         SET_DECL_IMPLICIT_INSTANTIATION (r);
9826         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9827         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9828
9829         /* The template parameters for this new template are all the
9830            template parameters for the old template, except the
9831            outermost level of parameters.  */
9832         DECL_TEMPLATE_PARMS (r)
9833           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9834                                    complain);
9835
9836         if (PRIMARY_TEMPLATE_P (t))
9837           DECL_PRIMARY_TEMPLATE (r) = r;
9838
9839         if (TREE_CODE (decl) != TYPE_DECL)
9840           /* Record this non-type partial instantiation.  */
9841           register_specialization (r, t,
9842                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9843                                    false, hash);
9844       }
9845       break;
9846
9847     case FUNCTION_DECL:
9848       {
9849         tree ctx;
9850         tree argvec = NULL_TREE;
9851         tree *friends;
9852         tree gen_tmpl;
9853         tree type;
9854         int member;
9855         int args_depth;
9856         int parms_depth;
9857
9858         /* Nobody should be tsubst'ing into non-template functions.  */
9859         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9860
9861         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9862           {
9863             tree spec;
9864             bool dependent_p;
9865
9866             /* If T is not dependent, just return it.  We have to
9867                increment PROCESSING_TEMPLATE_DECL because
9868                value_dependent_expression_p assumes that nothing is
9869                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9870             ++processing_template_decl;
9871             dependent_p = value_dependent_expression_p (t);
9872             --processing_template_decl;
9873             if (!dependent_p)
9874               RETURN (t);
9875
9876             /* Calculate the most general template of which R is a
9877                specialization, and the complete set of arguments used to
9878                specialize R.  */
9879             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9880             argvec = tsubst_template_args (DECL_TI_ARGS
9881                                           (DECL_TEMPLATE_RESULT
9882                                                  (DECL_TI_TEMPLATE (t))),
9883                                            args, complain, in_decl);
9884             if (argvec == error_mark_node)
9885               RETURN (error_mark_node);
9886
9887             /* Check to see if we already have this specialization.  */
9888             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9889             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9890
9891             if (spec)
9892               {
9893                 r = spec;
9894                 break;
9895               }
9896
9897             /* We can see more levels of arguments than parameters if
9898                there was a specialization of a member template, like
9899                this:
9900
9901                  template <class T> struct S { template <class U> void f(); }
9902                  template <> template <class U> void S<int>::f(U);
9903
9904                Here, we'll be substituting into the specialization,
9905                because that's where we can find the code we actually
9906                want to generate, but we'll have enough arguments for
9907                the most general template.
9908
9909                We also deal with the peculiar case:
9910
9911                  template <class T> struct S {
9912                    template <class U> friend void f();
9913                  };
9914                  template <class U> void f() {}
9915                  template S<int>;
9916                  template void f<double>();
9917
9918                Here, the ARGS for the instantiation of will be {int,
9919                double}.  But, we only need as many ARGS as there are
9920                levels of template parameters in CODE_PATTERN.  We are
9921                careful not to get fooled into reducing the ARGS in
9922                situations like:
9923
9924                  template <class T> struct S { template <class U> void f(U); }
9925                  template <class T> template <> void S<T>::f(int) {}
9926
9927                which we can spot because the pattern will be a
9928                specialization in this case.  */
9929             args_depth = TMPL_ARGS_DEPTH (args);
9930             parms_depth =
9931               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9932             if (args_depth > parms_depth
9933                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9934               args = get_innermost_template_args (args, parms_depth);
9935           }
9936         else
9937           {
9938             /* This special case arises when we have something like this:
9939
9940                  template <class T> struct S {
9941                    friend void f<int>(int, double);
9942                  };
9943
9944                Here, the DECL_TI_TEMPLATE for the friend declaration
9945                will be an IDENTIFIER_NODE.  We are being called from
9946                tsubst_friend_function, and we want only to create a
9947                new decl (R) with appropriate types so that we can call
9948                determine_specialization.  */
9949             gen_tmpl = NULL_TREE;
9950           }
9951
9952         if (DECL_CLASS_SCOPE_P (t))
9953           {
9954             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9955               member = 2;
9956             else
9957               member = 1;
9958             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9959                                     complain, t, /*entering_scope=*/1);
9960           }
9961         else
9962           {
9963             member = 0;
9964             ctx = DECL_CONTEXT (t);
9965           }
9966         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9967         if (type == error_mark_node)
9968           RETURN (error_mark_node);
9969
9970         /* We do NOT check for matching decls pushed separately at this
9971            point, as they may not represent instantiations of this
9972            template, and in any case are considered separate under the
9973            discrete model.  */
9974         r = copy_decl (t);
9975         DECL_USE_TEMPLATE (r) = 0;
9976         TREE_TYPE (r) = type;
9977         /* Clear out the mangled name and RTL for the instantiation.  */
9978         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9979         SET_DECL_RTL (r, NULL);
9980         /* Leave DECL_INITIAL set on deleted instantiations.  */
9981         if (!DECL_DELETED_FN (r))
9982           DECL_INITIAL (r) = NULL_TREE;
9983         DECL_CONTEXT (r) = ctx;
9984
9985         if (member && DECL_CONV_FN_P (r))
9986           /* Type-conversion operator.  Reconstruct the name, in
9987              case it's the name of one of the template's parameters.  */
9988           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9989
9990         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9991                                      complain, t);
9992         DECL_RESULT (r) = NULL_TREE;
9993
9994         TREE_STATIC (r) = 0;
9995         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9996         DECL_EXTERNAL (r) = 1;
9997         /* If this is an instantiation of a function with internal
9998            linkage, we already know what object file linkage will be
9999            assigned to the instantiation.  */
10000         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10001         DECL_DEFER_OUTPUT (r) = 0;
10002         DECL_CHAIN (r) = NULL_TREE;
10003         DECL_PENDING_INLINE_INFO (r) = 0;
10004         DECL_PENDING_INLINE_P (r) = 0;
10005         DECL_SAVED_TREE (r) = NULL_TREE;
10006         DECL_STRUCT_FUNCTION (r) = NULL;
10007         TREE_USED (r) = 0;
10008         /* We'll re-clone as appropriate in instantiate_template.  */
10009         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10010
10011         /* If we aren't complaining now, return on error before we register
10012            the specialization so that we'll complain eventually.  */
10013         if ((complain & tf_error) == 0
10014             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10015             && !grok_op_properties (r, /*complain=*/false))
10016           RETURN (error_mark_node);
10017
10018         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10019            this in the special friend case mentioned above where
10020            GEN_TMPL is NULL.  */
10021         if (gen_tmpl)
10022           {
10023             DECL_TEMPLATE_INFO (r)
10024               = build_template_info (gen_tmpl, argvec);
10025             SET_DECL_IMPLICIT_INSTANTIATION (r);
10026             register_specialization (r, gen_tmpl, argvec, false, hash);
10027
10028             /* We're not supposed to instantiate default arguments
10029                until they are called, for a template.  But, for a
10030                declaration like:
10031
10032                  template <class T> void f ()
10033                  { extern void g(int i = T()); }
10034
10035                we should do the substitution when the template is
10036                instantiated.  We handle the member function case in
10037                instantiate_class_template since the default arguments
10038                might refer to other members of the class.  */
10039             if (!member
10040                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10041                 && !uses_template_parms (argvec))
10042               tsubst_default_arguments (r);
10043           }
10044         else
10045           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10046
10047         /* Copy the list of befriending classes.  */
10048         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10049              *friends;
10050              friends = &TREE_CHAIN (*friends))
10051           {
10052             *friends = copy_node (*friends);
10053             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10054                                             args, complain,
10055                                             in_decl);
10056           }
10057
10058         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10059           {
10060             maybe_retrofit_in_chrg (r);
10061             if (DECL_CONSTRUCTOR_P (r))
10062               grok_ctor_properties (ctx, r);
10063             /* If this is an instantiation of a member template, clone it.
10064                If it isn't, that'll be handled by
10065                clone_constructors_and_destructors.  */
10066             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10067               clone_function_decl (r, /*update_method_vec_p=*/0);
10068           }
10069         else if ((complain & tf_error) != 0
10070                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10071                  && !grok_op_properties (r, /*complain=*/true))
10072           RETURN (error_mark_node);
10073
10074         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10075           SET_DECL_FRIEND_CONTEXT (r,
10076                                    tsubst (DECL_FRIEND_CONTEXT (t),
10077                                             args, complain, in_decl));
10078
10079         /* Possibly limit visibility based on template args.  */
10080         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10081         if (DECL_VISIBILITY_SPECIFIED (t))
10082           {
10083             DECL_VISIBILITY_SPECIFIED (r) = 0;
10084             DECL_ATTRIBUTES (r)
10085               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10086           }
10087         determine_visibility (r);
10088         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10089             && !processing_template_decl)
10090           defaulted_late_check (r);
10091
10092         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10093                                         args, complain, in_decl);
10094       }
10095       break;
10096
10097     case PARM_DECL:
10098       {
10099         tree type = NULL_TREE;
10100         int i, len = 1;
10101         tree expanded_types = NULL_TREE;
10102         tree prev_r = NULL_TREE;
10103         tree first_r = NULL_TREE;
10104
10105         if (FUNCTION_PARAMETER_PACK_P (t))
10106           {
10107             /* If there is a local specialization that isn't a
10108                parameter pack, it means that we're doing a "simple"
10109                substitution from inside tsubst_pack_expansion. Just
10110                return the local specialization (which will be a single
10111                parm).  */
10112             tree spec = retrieve_local_specialization (t);
10113             if (spec 
10114                 && TREE_CODE (spec) == PARM_DECL
10115                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10116               RETURN (spec);
10117
10118             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10119                the parameters in this function parameter pack.  */
10120             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10121                                                     complain, in_decl);
10122             if (TREE_CODE (expanded_types) == TREE_VEC)
10123               {
10124                 len = TREE_VEC_LENGTH (expanded_types);
10125
10126                 /* Zero-length parameter packs are boring. Just substitute
10127                    into the chain.  */
10128                 if (len == 0)
10129                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10130                                   TREE_CHAIN (t)));
10131               }
10132             else
10133               {
10134                 /* All we did was update the type. Make a note of that.  */
10135                 type = expanded_types;
10136                 expanded_types = NULL_TREE;
10137               }
10138           }
10139
10140         /* Loop through all of the parameter's we'll build. When T is
10141            a function parameter pack, LEN is the number of expanded
10142            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10143         r = NULL_TREE;
10144         for (i = 0; i < len; ++i)
10145           {
10146             prev_r = r;
10147             r = copy_node (t);
10148             if (DECL_TEMPLATE_PARM_P (t))
10149               SET_DECL_TEMPLATE_PARM_P (r);
10150
10151             if (expanded_types)
10152               /* We're on the Ith parameter of the function parameter
10153                  pack.  */
10154               {
10155                 /* An argument of a function parameter pack is not a parameter
10156                    pack.  */
10157                 FUNCTION_PARAMETER_PACK_P (r) = false;
10158
10159                 /* Get the Ith type.  */
10160                 type = TREE_VEC_ELT (expanded_types, i);
10161
10162                 if (DECL_NAME (r))
10163                   /* Rename the parameter to include the index.  */
10164                   DECL_NAME (r) =
10165                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10166               }
10167             else if (!type)
10168               /* We're dealing with a normal parameter.  */
10169               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10170
10171             type = type_decays_to (type);
10172             TREE_TYPE (r) = type;
10173             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10174
10175             if (DECL_INITIAL (r))
10176               {
10177                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10178                   DECL_INITIAL (r) = TREE_TYPE (r);
10179                 else
10180                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10181                                              complain, in_decl);
10182               }
10183
10184             DECL_CONTEXT (r) = NULL_TREE;
10185
10186             if (!DECL_TEMPLATE_PARM_P (r))
10187               DECL_ARG_TYPE (r) = type_passed_as (type);
10188
10189             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10190                                             args, complain, in_decl);
10191
10192             /* Keep track of the first new parameter we
10193                generate. That's what will be returned to the
10194                caller.  */
10195             if (!first_r)
10196               first_r = r;
10197
10198             /* Build a proper chain of parameters when substituting
10199                into a function parameter pack.  */
10200             if (prev_r)
10201               DECL_CHAIN (prev_r) = r;
10202           }
10203
10204         if (DECL_CHAIN (t))
10205           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10206                                    complain, DECL_CHAIN (t));
10207
10208         /* FIRST_R contains the start of the chain we've built.  */
10209         r = first_r;
10210       }
10211       break;
10212
10213     case FIELD_DECL:
10214       {
10215         tree type;
10216
10217         r = copy_decl (t);
10218         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10219         if (type == error_mark_node)
10220           RETURN (error_mark_node);
10221         TREE_TYPE (r) = type;
10222         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10223
10224         /* DECL_INITIAL gives the number of bits in a bit-field.  */
10225         DECL_INITIAL (r)
10226           = tsubst_expr (DECL_INITIAL (t), args,
10227                          complain, in_decl,
10228                          /*integral_constant_expression_p=*/true);
10229         /* We don't have to set DECL_CONTEXT here; it is set by
10230            finish_member_declaration.  */
10231         DECL_CHAIN (r) = NULL_TREE;
10232         if (VOID_TYPE_P (type))
10233           error ("instantiation of %q+D as type %qT", r, type);
10234
10235         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10236                                         args, complain, in_decl);
10237       }
10238       break;
10239
10240     case USING_DECL:
10241       /* We reach here only for member using decls.  */
10242       if (DECL_DEPENDENT_P (t))
10243         {
10244           r = do_class_using_decl
10245             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10246              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10247           if (!r)
10248             r = error_mark_node;
10249           else
10250             {
10251               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10252               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10253             }
10254         }
10255       else
10256         {
10257           r = copy_node (t);
10258           DECL_CHAIN (r) = NULL_TREE;
10259         }
10260       break;
10261
10262     case TYPE_DECL:
10263     case VAR_DECL:
10264       {
10265         tree argvec = NULL_TREE;
10266         tree gen_tmpl = NULL_TREE;
10267         tree spec;
10268         tree tmpl = NULL_TREE;
10269         tree ctx;
10270         tree type = NULL_TREE;
10271         bool local_p;
10272
10273         if (TREE_CODE (t) == TYPE_DECL
10274             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10275           {
10276             /* If this is the canonical decl, we don't have to
10277                mess with instantiations, and often we can't (for
10278                typename, template type parms and such).  Note that
10279                TYPE_NAME is not correct for the above test if
10280                we've copied the type for a typedef.  */
10281             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10282             if (type == error_mark_node)
10283               RETURN (error_mark_node);
10284             r = TYPE_NAME (type);
10285             break;
10286           }
10287
10288         /* Check to see if we already have the specialization we
10289            need.  */
10290         spec = NULL_TREE;
10291         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10292           {
10293             /* T is a static data member or namespace-scope entity.
10294                We have to substitute into namespace-scope variables
10295                (even though such entities are never templates) because
10296                of cases like:
10297                
10298                  template <class T> void f() { extern T t; }
10299
10300                where the entity referenced is not known until
10301                instantiation time.  */
10302             local_p = false;
10303             ctx = DECL_CONTEXT (t);
10304             if (DECL_CLASS_SCOPE_P (t))
10305               {
10306                 ctx = tsubst_aggr_type (ctx, args,
10307                                         complain,
10308                                         in_decl, /*entering_scope=*/1);
10309                 /* If CTX is unchanged, then T is in fact the
10310                    specialization we want.  That situation occurs when
10311                    referencing a static data member within in its own
10312                    class.  We can use pointer equality, rather than
10313                    same_type_p, because DECL_CONTEXT is always
10314                    canonical.  */
10315                 if (ctx == DECL_CONTEXT (t))
10316                   spec = t;
10317               }
10318
10319             if (!spec)
10320               {
10321                 tmpl = DECL_TI_TEMPLATE (t);
10322                 gen_tmpl = most_general_template (tmpl);
10323                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10324                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10325                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10326               }
10327           }
10328         else
10329           {
10330             /* A local variable.  */
10331             local_p = true;
10332             /* Subsequent calls to pushdecl will fill this in.  */
10333             ctx = NULL_TREE;
10334             spec = retrieve_local_specialization (t);
10335           }
10336         /* If we already have the specialization we need, there is
10337            nothing more to do.  */ 
10338         if (spec)
10339           {
10340             r = spec;
10341             break;
10342           }
10343
10344         /* Create a new node for the specialization we need.  */
10345         r = copy_decl (t);
10346         if (type == NULL_TREE)
10347           {
10348             if (is_typedef_decl (t))
10349               type = DECL_ORIGINAL_TYPE (t);
10350             else
10351               type = TREE_TYPE (t);
10352             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10353               type = strip_array_domain (type);
10354             type = tsubst (type, args, complain, in_decl);
10355           }
10356         if (TREE_CODE (r) == VAR_DECL)
10357           {
10358             /* Even if the original location is out of scope, the
10359                newly substituted one is not.  */
10360             DECL_DEAD_FOR_LOCAL (r) = 0;
10361             DECL_INITIALIZED_P (r) = 0;
10362             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10363             if (type == error_mark_node)
10364               RETURN (error_mark_node);
10365             if (TREE_CODE (type) == FUNCTION_TYPE)
10366               {
10367                 /* It may seem that this case cannot occur, since:
10368
10369                      typedef void f();
10370                      void g() { f x; }
10371
10372                    declares a function, not a variable.  However:
10373       
10374                      typedef void f();
10375                      template <typename T> void g() { T t; }
10376                      template void g<f>();
10377
10378                    is an attempt to declare a variable with function
10379                    type.  */
10380                 error ("variable %qD has function type",
10381                        /* R is not yet sufficiently initialized, so we
10382                           just use its name.  */
10383                        DECL_NAME (r));
10384                 RETURN (error_mark_node);
10385               }
10386             type = complete_type (type);
10387             /* Wait until cp_finish_decl to set this again, to handle
10388                circular dependency (template/instantiate6.C). */
10389             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10390             type = check_var_type (DECL_NAME (r), type);
10391
10392             if (DECL_HAS_VALUE_EXPR_P (t))
10393               {
10394                 tree ve = DECL_VALUE_EXPR (t);
10395                 ve = tsubst_expr (ve, args, complain, in_decl,
10396                                   /*constant_expression_p=*/false);
10397                 if (REFERENCE_REF_P (ve))
10398                   {
10399                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10400                     ve = TREE_OPERAND (ve, 0);
10401                   }
10402                 SET_DECL_VALUE_EXPR (r, ve);
10403               }
10404           }
10405         else if (DECL_SELF_REFERENCE_P (t))
10406           SET_DECL_SELF_REFERENCE_P (r);
10407         TREE_TYPE (r) = type;
10408         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10409         DECL_CONTEXT (r) = ctx;
10410         /* Clear out the mangled name and RTL for the instantiation.  */
10411         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10412         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10413           SET_DECL_RTL (r, NULL);
10414         /* The initializer must not be expanded until it is required;
10415            see [temp.inst].  */
10416         DECL_INITIAL (r) = NULL_TREE;
10417         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10418           SET_DECL_RTL (r, NULL);
10419         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10420         if (TREE_CODE (r) == VAR_DECL)
10421           {
10422             /* Possibly limit visibility based on template args.  */
10423             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10424             if (DECL_VISIBILITY_SPECIFIED (t))
10425               {
10426                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10427                 DECL_ATTRIBUTES (r)
10428                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10429               }
10430             determine_visibility (r);
10431           }
10432
10433         if (!local_p)
10434           {
10435             /* A static data member declaration is always marked
10436                external when it is declared in-class, even if an
10437                initializer is present.  We mimic the non-template
10438                processing here.  */
10439             DECL_EXTERNAL (r) = 1;
10440
10441             register_specialization (r, gen_tmpl, argvec, false, hash);
10442             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10443             SET_DECL_IMPLICIT_INSTANTIATION (r);
10444           }
10445         else if (cp_unevaluated_operand)
10446           {
10447             /* We're substituting this var in a decltype outside of its
10448                scope, such as for a lambda return type.  Don't add it to
10449                local_specializations, do perform auto deduction.  */
10450             tree auto_node = type_uses_auto (type);
10451             if (auto_node)
10452               {
10453                 tree init
10454                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10455                                  /*constant_expression_p=*/false);
10456                 init = resolve_nondeduced_context (init);
10457                 TREE_TYPE (r) = type
10458                   = do_auto_deduction (type, init, auto_node);
10459               }
10460           }
10461         else
10462           register_local_specialization (r, t);
10463
10464         DECL_CHAIN (r) = NULL_TREE;
10465
10466         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10467                                         /*flags=*/0,
10468                                         args, complain, in_decl);
10469
10470         /* Preserve a typedef that names a type.  */
10471         if (is_typedef_decl (r))
10472           {
10473             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10474             set_underlying_type (r);
10475           }
10476
10477         layout_decl (r, 0);
10478       }
10479       break;
10480
10481     default:
10482       gcc_unreachable ();
10483     }
10484 #undef RETURN
10485
10486  out:
10487   /* Restore the file and line information.  */
10488   input_location = saved_loc;
10489
10490   return r;
10491 }
10492
10493 /* Substitute into the ARG_TYPES of a function type.  */
10494
10495 static tree
10496 tsubst_arg_types (tree arg_types,
10497                   tree args,
10498                   tsubst_flags_t complain,
10499                   tree in_decl)
10500 {
10501   tree remaining_arg_types;
10502   tree type = NULL_TREE;
10503   int i = 1;
10504   tree expanded_args = NULL_TREE;
10505   tree default_arg;
10506
10507   if (!arg_types || arg_types == void_list_node)
10508     return arg_types;
10509
10510   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10511                                           args, complain, in_decl);
10512   if (remaining_arg_types == error_mark_node)
10513     return error_mark_node;
10514
10515   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10516     {
10517       /* For a pack expansion, perform substitution on the
10518          entire expression. Later on, we'll handle the arguments
10519          one-by-one.  */
10520       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10521                                             args, complain, in_decl);
10522
10523       if (TREE_CODE (expanded_args) == TREE_VEC)
10524         /* So that we'll spin through the parameters, one by one.  */
10525         i = TREE_VEC_LENGTH (expanded_args);
10526       else
10527         {
10528           /* We only partially substituted into the parameter
10529              pack. Our type is TYPE_PACK_EXPANSION.  */
10530           type = expanded_args;
10531           expanded_args = NULL_TREE;
10532         }
10533     }
10534
10535   while (i > 0) {
10536     --i;
10537     
10538     if (expanded_args)
10539       type = TREE_VEC_ELT (expanded_args, i);
10540     else if (!type)
10541       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10542
10543     if (type == error_mark_node)
10544       return error_mark_node;
10545     if (VOID_TYPE_P (type))
10546       {
10547         if (complain & tf_error)
10548           {
10549             error ("invalid parameter type %qT", type);
10550             if (in_decl)
10551               error ("in declaration %q+D", in_decl);
10552           }
10553         return error_mark_node;
10554     }
10555     
10556     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10557        top-level qualifiers as required.  */
10558     type = cv_unqualified (type_decays_to (type));
10559
10560     /* We do not substitute into default arguments here.  The standard
10561        mandates that they be instantiated only when needed, which is
10562        done in build_over_call.  */
10563     default_arg = TREE_PURPOSE (arg_types);
10564
10565     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10566       {
10567         /* We've instantiated a template before its default arguments
10568            have been parsed.  This can happen for a nested template
10569            class, and is not an error unless we require the default
10570            argument in a call of this function.  */
10571         remaining_arg_types = 
10572           tree_cons (default_arg, type, remaining_arg_types);
10573         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10574                        remaining_arg_types);
10575       }
10576     else
10577       remaining_arg_types = 
10578         hash_tree_cons (default_arg, type, remaining_arg_types);
10579   }
10580         
10581   return remaining_arg_types;
10582 }
10583
10584 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10585    *not* handle the exception-specification for FNTYPE, because the
10586    initial substitution of explicitly provided template parameters
10587    during argument deduction forbids substitution into the
10588    exception-specification:
10589
10590      [temp.deduct]
10591
10592      All references in the function type of the function template to  the
10593      corresponding template parameters are replaced by the specified tem-
10594      plate argument values.  If a substitution in a template parameter or
10595      in  the function type of the function template results in an invalid
10596      type, type deduction fails.  [Note: The equivalent  substitution  in
10597      exception specifications is done only when the function is instanti-
10598      ated, at which point a program is  ill-formed  if  the  substitution
10599      results in an invalid type.]  */
10600
10601 static tree
10602 tsubst_function_type (tree t,
10603                       tree args,
10604                       tsubst_flags_t complain,
10605                       tree in_decl)
10606 {
10607   tree return_type;
10608   tree arg_types;
10609   tree fntype;
10610
10611   /* The TYPE_CONTEXT is not used for function/method types.  */
10612   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10613
10614   /* Substitute the return type.  */
10615   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10616   if (return_type == error_mark_node)
10617     return error_mark_node;
10618   /* The standard does not presently indicate that creation of a
10619      function type with an invalid return type is a deduction failure.
10620      However, that is clearly analogous to creating an array of "void"
10621      or a reference to a reference.  This is core issue #486.  */
10622   if (TREE_CODE (return_type) == ARRAY_TYPE
10623       || TREE_CODE (return_type) == FUNCTION_TYPE)
10624     {
10625       if (complain & tf_error)
10626         {
10627           if (TREE_CODE (return_type) == ARRAY_TYPE)
10628             error ("function returning an array");
10629           else
10630             error ("function returning a function");
10631         }
10632       return error_mark_node;
10633     }
10634
10635   /* Substitute the argument types.  */
10636   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10637                                 complain, in_decl);
10638   if (arg_types == error_mark_node)
10639     return error_mark_node;
10640
10641   /* Construct a new type node and return it.  */
10642   if (TREE_CODE (t) == FUNCTION_TYPE)
10643     {
10644       fntype = build_function_type (return_type, arg_types);
10645       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10646     }
10647   else
10648     {
10649       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10650       if (! MAYBE_CLASS_TYPE_P (r))
10651         {
10652           /* [temp.deduct]
10653
10654              Type deduction may fail for any of the following
10655              reasons:
10656
10657              -- Attempting to create "pointer to member of T" when T
10658              is not a class type.  */
10659           if (complain & tf_error)
10660             error ("creating pointer to member function of non-class type %qT",
10661                       r);
10662           return error_mark_node;
10663         }
10664
10665       fntype = build_method_type_directly (r, return_type,
10666                                            TREE_CHAIN (arg_types));
10667     }
10668   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10669
10670   return fntype;
10671 }
10672
10673 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10674    ARGS into that specification, and return the substituted
10675    specification.  If there is no specification, return NULL_TREE.  */
10676
10677 static tree
10678 tsubst_exception_specification (tree fntype,
10679                                 tree args,
10680                                 tsubst_flags_t complain,
10681                                 tree in_decl,
10682                                 bool defer_ok)
10683 {
10684   tree specs;
10685   tree new_specs;
10686
10687   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10688   new_specs = NULL_TREE;
10689   if (specs && TREE_PURPOSE (specs))
10690     {
10691       /* A noexcept-specifier.  */
10692       tree expr = TREE_PURPOSE (specs);
10693       if (expr == boolean_true_node || expr == boolean_false_node)
10694         new_specs = expr;
10695       else if (defer_ok)
10696         {
10697           /* Defer instantiation of noexcept-specifiers to avoid
10698              excessive instantiations (c++/49107).  */
10699           new_specs = make_node (DEFERRED_NOEXCEPT);
10700           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10701             {
10702               /* We already partially instantiated this member template,
10703                  so combine the new args with the old.  */
10704               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10705                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10706               DEFERRED_NOEXCEPT_ARGS (new_specs)
10707                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10708             }
10709           else
10710             {
10711               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10712               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10713             }
10714         }
10715       else
10716         new_specs = tsubst_copy_and_build
10717           (expr, args, complain, in_decl, /*function_p=*/false,
10718            /*integral_constant_expression_p=*/true);
10719       new_specs = build_noexcept_spec (new_specs, complain);
10720     }
10721   else if (specs)
10722     {
10723       if (! TREE_VALUE (specs))
10724         new_specs = specs;
10725       else
10726         while (specs)
10727           {
10728             tree spec;
10729             int i, len = 1;
10730             tree expanded_specs = NULL_TREE;
10731
10732             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10733               {
10734                 /* Expand the pack expansion type.  */
10735                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10736                                                        args, complain,
10737                                                        in_decl);
10738
10739                 if (expanded_specs == error_mark_node)
10740                   return error_mark_node;
10741                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10742                   len = TREE_VEC_LENGTH (expanded_specs);
10743                 else
10744                   {
10745                     /* We're substituting into a member template, so
10746                        we got a TYPE_PACK_EXPANSION back.  Add that
10747                        expansion and move on.  */
10748                     gcc_assert (TREE_CODE (expanded_specs) 
10749                                 == TYPE_PACK_EXPANSION);
10750                     new_specs = add_exception_specifier (new_specs,
10751                                                          expanded_specs,
10752                                                          complain);
10753                     specs = TREE_CHAIN (specs);
10754                     continue;
10755                   }
10756               }
10757
10758             for (i = 0; i < len; ++i)
10759               {
10760                 if (expanded_specs)
10761                   spec = TREE_VEC_ELT (expanded_specs, i);
10762                 else
10763                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10764                 if (spec == error_mark_node)
10765                   return spec;
10766                 new_specs = add_exception_specifier (new_specs, spec, 
10767                                                      complain);
10768               }
10769
10770             specs = TREE_CHAIN (specs);
10771           }
10772     }
10773   return new_specs;
10774 }
10775
10776 /* Take the tree structure T and replace template parameters used
10777    therein with the argument vector ARGS.  IN_DECL is an associated
10778    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10779    Issue error and warning messages under control of COMPLAIN.  Note
10780    that we must be relatively non-tolerant of extensions here, in
10781    order to preserve conformance; if we allow substitutions that
10782    should not be allowed, we may allow argument deductions that should
10783    not succeed, and therefore report ambiguous overload situations
10784    where there are none.  In theory, we could allow the substitution,
10785    but indicate that it should have failed, and allow our caller to
10786    make sure that the right thing happens, but we don't try to do this
10787    yet.
10788
10789    This function is used for dealing with types, decls and the like;
10790    for expressions, use tsubst_expr or tsubst_copy.  */
10791
10792 tree
10793 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10794 {
10795   enum tree_code code;
10796   tree type, r;
10797
10798   if (t == NULL_TREE || t == error_mark_node
10799       || t == integer_type_node
10800       || t == void_type_node
10801       || t == char_type_node
10802       || t == unknown_type_node
10803       || TREE_CODE (t) == NAMESPACE_DECL
10804       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10805     return t;
10806
10807   if (DECL_P (t))
10808     return tsubst_decl (t, args, complain);
10809
10810   if (args == NULL_TREE)
10811     return t;
10812
10813   code = TREE_CODE (t);
10814
10815   if (code == IDENTIFIER_NODE)
10816     type = IDENTIFIER_TYPE_VALUE (t);
10817   else
10818     type = TREE_TYPE (t);
10819
10820   gcc_assert (type != unknown_type_node);
10821
10822   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10823      such as attribute aligned.  */
10824   if (TYPE_P (t)
10825       && typedef_variant_p (t))
10826     {
10827       tree decl = TYPE_NAME (t);
10828       
10829       if (DECL_CLASS_SCOPE_P (decl)
10830           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10831           && uses_template_parms (DECL_CONTEXT (decl)))
10832         {
10833           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10834           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10835           r = retrieve_specialization (tmpl, gen_args, 0);
10836         }
10837       else if (DECL_FUNCTION_SCOPE_P (decl)
10838                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10839                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10840         r = retrieve_local_specialization (decl);
10841       else
10842         /* The typedef is from a non-template context.  */
10843         return t;
10844
10845       if (r)
10846         {
10847           r = TREE_TYPE (r);
10848           r = cp_build_qualified_type_real
10849             (r, cp_type_quals (t) | cp_type_quals (r),
10850              complain | tf_ignore_bad_quals);
10851           return r;
10852         }
10853       /* Else we must be instantiating the typedef, so fall through.  */
10854     }
10855
10856   if (type
10857       && code != TYPENAME_TYPE
10858       && code != TEMPLATE_TYPE_PARM
10859       && code != IDENTIFIER_NODE
10860       && code != FUNCTION_TYPE
10861       && code != METHOD_TYPE)
10862     type = tsubst (type, args, complain, in_decl);
10863   if (type == error_mark_node)
10864     return error_mark_node;
10865
10866   switch (code)
10867     {
10868     case RECORD_TYPE:
10869     case UNION_TYPE:
10870     case ENUMERAL_TYPE:
10871       return tsubst_aggr_type (t, args, complain, in_decl,
10872                                /*entering_scope=*/0);
10873
10874     case ERROR_MARK:
10875     case IDENTIFIER_NODE:
10876     case VOID_TYPE:
10877     case REAL_TYPE:
10878     case COMPLEX_TYPE:
10879     case VECTOR_TYPE:
10880     case BOOLEAN_TYPE:
10881     case NULLPTR_TYPE:
10882     case LANG_TYPE:
10883       return t;
10884
10885     case INTEGER_TYPE:
10886       if (t == integer_type_node)
10887         return t;
10888
10889       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10890           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10891         return t;
10892
10893       {
10894         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10895
10896         max = tsubst_expr (omax, args, complain, in_decl,
10897                            /*integral_constant_expression_p=*/false);
10898
10899         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10900            needed.  */
10901         if (TREE_CODE (max) == NOP_EXPR
10902             && TREE_SIDE_EFFECTS (omax)
10903             && !TREE_TYPE (max))
10904           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10905
10906         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10907            with TREE_SIDE_EFFECTS that indicates this is not an integral
10908            constant expression.  */
10909         if (processing_template_decl
10910             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10911           {
10912             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10913             TREE_SIDE_EFFECTS (max) = 1;
10914           }
10915
10916         return compute_array_index_type (NULL_TREE, max, complain);
10917       }
10918
10919     case TEMPLATE_TYPE_PARM:
10920     case TEMPLATE_TEMPLATE_PARM:
10921     case BOUND_TEMPLATE_TEMPLATE_PARM:
10922     case TEMPLATE_PARM_INDEX:
10923       {
10924         int idx;
10925         int level;
10926         int levels;
10927         tree arg = NULL_TREE;
10928
10929         r = NULL_TREE;
10930
10931         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10932         template_parm_level_and_index (t, &level, &idx); 
10933
10934         levels = TMPL_ARGS_DEPTH (args);
10935         if (level <= levels)
10936           {
10937             arg = TMPL_ARG (args, level, idx);
10938
10939             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10940               /* See through ARGUMENT_PACK_SELECT arguments. */
10941               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10942           }
10943
10944         if (arg == error_mark_node)
10945           return error_mark_node;
10946         else if (arg != NULL_TREE)
10947           {
10948             if (ARGUMENT_PACK_P (arg))
10949               /* If ARG is an argument pack, we don't actually want to
10950                  perform a substitution here, because substitutions
10951                  for argument packs are only done
10952                  element-by-element. We can get to this point when
10953                  substituting the type of a non-type template
10954                  parameter pack, when that type actually contains
10955                  template parameter packs from an outer template, e.g.,
10956
10957                  template<typename... Types> struct A {
10958                    template<Types... Values> struct B { };
10959                  };  */
10960               return t;
10961
10962             if (code == TEMPLATE_TYPE_PARM)
10963               {
10964                 int quals;
10965                 gcc_assert (TYPE_P (arg));
10966
10967                 quals = cp_type_quals (arg) | cp_type_quals (t);
10968                   
10969                 return cp_build_qualified_type_real
10970                   (arg, quals, complain | tf_ignore_bad_quals);
10971               }
10972             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10973               {
10974                 /* We are processing a type constructed from a
10975                    template template parameter.  */
10976                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10977                                       args, complain, in_decl);
10978                 if (argvec == error_mark_node)
10979                   return error_mark_node;
10980
10981                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10982                    are resolving nested-types in the signature of a
10983                    member function templates.  Otherwise ARG is a
10984                    TEMPLATE_DECL and is the real template to be
10985                    instantiated.  */
10986                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10987                   arg = TYPE_NAME (arg);
10988
10989                 r = lookup_template_class (arg,
10990                                            argvec, in_decl,
10991                                            DECL_CONTEXT (arg),
10992                                             /*entering_scope=*/0,
10993                                            complain);
10994                 return cp_build_qualified_type_real
10995                   (r, cp_type_quals (t), complain);
10996               }
10997             else
10998               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10999               return convert_from_reference (unshare_expr (arg));
11000           }
11001
11002         if (level == 1)
11003           /* This can happen during the attempted tsubst'ing in
11004              unify.  This means that we don't yet have any information
11005              about the template parameter in question.  */
11006           return t;
11007
11008         /* If we get here, we must have been looking at a parm for a
11009            more deeply nested template.  Make a new version of this
11010            template parameter, but with a lower level.  */
11011         switch (code)
11012           {
11013           case TEMPLATE_TYPE_PARM:
11014           case TEMPLATE_TEMPLATE_PARM:
11015           case BOUND_TEMPLATE_TEMPLATE_PARM:
11016             if (cp_type_quals (t))
11017               {
11018                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11019                 r = cp_build_qualified_type_real
11020                   (r, cp_type_quals (t),
11021                    complain | (code == TEMPLATE_TYPE_PARM
11022                                ? tf_ignore_bad_quals : 0));
11023               }
11024             else
11025               {
11026                 r = copy_type (t);
11027                 TEMPLATE_TYPE_PARM_INDEX (r)
11028                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11029                                                 r, levels, args, complain);
11030                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11031                 TYPE_MAIN_VARIANT (r) = r;
11032                 TYPE_POINTER_TO (r) = NULL_TREE;
11033                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11034
11035                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11036                   /* We have reduced the level of the template
11037                      template parameter, but not the levels of its
11038                      template parameters, so canonical_type_parameter
11039                      will not be able to find the canonical template
11040                      template parameter for this level. Thus, we
11041                      require structural equality checking to compare
11042                      TEMPLATE_TEMPLATE_PARMs. */
11043                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11044                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11045                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11046                 else
11047                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11048
11049                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11050                   {
11051                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11052                                           complain, in_decl);
11053                     if (argvec == error_mark_node)
11054                       return error_mark_node;
11055
11056                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11057                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11058                   }
11059               }
11060             break;
11061
11062           case TEMPLATE_PARM_INDEX:
11063             r = reduce_template_parm_level (t, type, levels, args, complain);
11064             break;
11065
11066           default:
11067             gcc_unreachable ();
11068           }
11069
11070         return r;
11071       }
11072
11073     case TREE_LIST:
11074       {
11075         tree purpose, value, chain;
11076
11077         if (t == void_list_node)
11078           return t;
11079
11080         purpose = TREE_PURPOSE (t);
11081         if (purpose)
11082           {
11083             purpose = tsubst (purpose, args, complain, in_decl);
11084             if (purpose == error_mark_node)
11085               return error_mark_node;
11086           }
11087         value = TREE_VALUE (t);
11088         if (value)
11089           {
11090             value = tsubst (value, args, complain, in_decl);
11091             if (value == error_mark_node)
11092               return error_mark_node;
11093           }
11094         chain = TREE_CHAIN (t);
11095         if (chain && chain != void_type_node)
11096           {
11097             chain = tsubst (chain, args, complain, in_decl);
11098             if (chain == error_mark_node)
11099               return error_mark_node;
11100           }
11101         if (purpose == TREE_PURPOSE (t)
11102             && value == TREE_VALUE (t)
11103             && chain == TREE_CHAIN (t))
11104           return t;
11105         return hash_tree_cons (purpose, value, chain);
11106       }
11107
11108     case TREE_BINFO:
11109       /* We should never be tsubsting a binfo.  */
11110       gcc_unreachable ();
11111
11112     case TREE_VEC:
11113       /* A vector of template arguments.  */
11114       gcc_assert (!type);
11115       return tsubst_template_args (t, args, complain, in_decl);
11116
11117     case POINTER_TYPE:
11118     case REFERENCE_TYPE:
11119       {
11120         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11121           return t;
11122
11123         /* [temp.deduct]
11124
11125            Type deduction may fail for any of the following
11126            reasons:
11127
11128            -- Attempting to create a pointer to reference type.
11129            -- Attempting to create a reference to a reference type or
11130               a reference to void.
11131
11132           Core issue 106 says that creating a reference to a reference
11133           during instantiation is no longer a cause for failure. We
11134           only enforce this check in strict C++98 mode.  */
11135         if ((TREE_CODE (type) == REFERENCE_TYPE
11136              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11137             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11138           {
11139             static location_t last_loc;
11140
11141             /* We keep track of the last time we issued this error
11142                message to avoid spewing a ton of messages during a
11143                single bad template instantiation.  */
11144             if (complain & tf_error
11145                 && last_loc != input_location)
11146               {
11147                 if (TREE_CODE (type) == VOID_TYPE)
11148                   error ("forming reference to void");
11149                else if (code == POINTER_TYPE)
11150                  error ("forming pointer to reference type %qT", type);
11151                else
11152                   error ("forming reference to reference type %qT", type);
11153                 last_loc = input_location;
11154               }
11155
11156             return error_mark_node;
11157           }
11158         else if (code == POINTER_TYPE)
11159           {
11160             r = build_pointer_type (type);
11161             if (TREE_CODE (type) == METHOD_TYPE)
11162               r = build_ptrmemfunc_type (r);
11163           }
11164         else if (TREE_CODE (type) == REFERENCE_TYPE)
11165           /* In C++0x, during template argument substitution, when there is an
11166              attempt to create a reference to a reference type, reference
11167              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11168
11169              "If a template-argument for a template-parameter T names a type
11170              that is a reference to a type A, an attempt to create the type
11171              'lvalue reference to cv T' creates the type 'lvalue reference to
11172              A,' while an attempt to create the type type rvalue reference to
11173              cv T' creates the type T"
11174           */
11175           r = cp_build_reference_type
11176               (TREE_TYPE (type),
11177                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11178         else
11179           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11180         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11181
11182         if (r != error_mark_node)
11183           /* Will this ever be needed for TYPE_..._TO values?  */
11184           layout_type (r);
11185
11186         return r;
11187       }
11188     case OFFSET_TYPE:
11189       {
11190         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11191         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11192           {
11193             /* [temp.deduct]
11194
11195                Type deduction may fail for any of the following
11196                reasons:
11197
11198                -- Attempting to create "pointer to member of T" when T
11199                   is not a class type.  */
11200             if (complain & tf_error)
11201               error ("creating pointer to member of non-class type %qT", r);
11202             return error_mark_node;
11203           }
11204         if (TREE_CODE (type) == REFERENCE_TYPE)
11205           {
11206             if (complain & tf_error)
11207               error ("creating pointer to member reference type %qT", type);
11208             return error_mark_node;
11209           }
11210         if (TREE_CODE (type) == VOID_TYPE)
11211           {
11212             if (complain & tf_error)
11213               error ("creating pointer to member of type void");
11214             return error_mark_node;
11215           }
11216         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11217         if (TREE_CODE (type) == FUNCTION_TYPE)
11218           {
11219             /* The type of the implicit object parameter gets its
11220                cv-qualifiers from the FUNCTION_TYPE. */
11221             tree memptr;
11222             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11223             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11224             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11225                                                  complain);
11226           }
11227         else
11228           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11229                                                cp_type_quals (t),
11230                                                complain);
11231       }
11232     case FUNCTION_TYPE:
11233     case METHOD_TYPE:
11234       {
11235         tree fntype;
11236         tree specs;
11237         fntype = tsubst_function_type (t, args, complain, in_decl);
11238         if (fntype == error_mark_node)
11239           return error_mark_node;
11240
11241         /* Substitute the exception specification.  */
11242         specs = tsubst_exception_specification (t, args, complain,
11243                                                 in_decl, /*defer_ok*/true);
11244         if (specs == error_mark_node)
11245           return error_mark_node;
11246         if (specs)
11247           fntype = build_exception_variant (fntype, specs);
11248         return fntype;
11249       }
11250     case ARRAY_TYPE:
11251       {
11252         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11253         if (domain == error_mark_node)
11254           return error_mark_node;
11255
11256         /* As an optimization, we avoid regenerating the array type if
11257            it will obviously be the same as T.  */
11258         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11259           return t;
11260
11261         /* These checks should match the ones in grokdeclarator.
11262
11263            [temp.deduct]
11264
11265            The deduction may fail for any of the following reasons:
11266
11267            -- Attempting to create an array with an element type that
11268               is void, a function type, or a reference type, or [DR337]
11269               an abstract class type.  */
11270         if (TREE_CODE (type) == VOID_TYPE
11271             || TREE_CODE (type) == FUNCTION_TYPE
11272             || TREE_CODE (type) == REFERENCE_TYPE)
11273           {
11274             if (complain & tf_error)
11275               error ("creating array of %qT", type);
11276             return error_mark_node;
11277           }
11278         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11279           {
11280             if (complain & tf_error)
11281               error ("creating array of %qT, which is an abstract class type",
11282                      type);
11283             return error_mark_node;
11284           }
11285
11286         r = build_cplus_array_type (type, domain);
11287
11288         if (TYPE_USER_ALIGN (t))
11289           {
11290             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11291             TYPE_USER_ALIGN (r) = 1;
11292           }
11293
11294         return r;
11295       }
11296
11297     case TYPENAME_TYPE:
11298       {
11299         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11300                                      in_decl, /*entering_scope=*/1);
11301         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11302                               complain, in_decl);
11303
11304         if (ctx == error_mark_node || f == error_mark_node)
11305           return error_mark_node;
11306
11307         if (!MAYBE_CLASS_TYPE_P (ctx))
11308           {
11309             if (complain & tf_error)
11310               error ("%qT is not a class, struct, or union type", ctx);
11311             return error_mark_node;
11312           }
11313         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11314           {
11315             /* Normally, make_typename_type does not require that the CTX
11316                have complete type in order to allow things like:
11317
11318                  template <class T> struct S { typename S<T>::X Y; };
11319
11320                But, such constructs have already been resolved by this
11321                point, so here CTX really should have complete type, unless
11322                it's a partial instantiation.  */
11323             ctx = complete_type (ctx);
11324             if (!COMPLETE_TYPE_P (ctx))
11325               {
11326                 if (complain & tf_error)
11327                   cxx_incomplete_type_error (NULL_TREE, ctx);
11328                 return error_mark_node;
11329               }
11330           }
11331
11332         f = make_typename_type (ctx, f, typename_type,
11333                                 (complain & tf_error) | tf_keep_type_decl);
11334         if (f == error_mark_node)
11335           return f;
11336         if (TREE_CODE (f) == TYPE_DECL)
11337           {
11338             complain |= tf_ignore_bad_quals;
11339             f = TREE_TYPE (f);
11340           }
11341
11342         if (TREE_CODE (f) != TYPENAME_TYPE)
11343           {
11344             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11345               {
11346                 if (complain & tf_error)
11347                   error ("%qT resolves to %qT, which is not an enumeration type",
11348                          t, f);
11349                 else
11350                   return error_mark_node;
11351               }
11352             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11353               {
11354                 if (complain & tf_error)
11355                   error ("%qT resolves to %qT, which is is not a class type",
11356                          t, f);
11357                 else
11358                   return error_mark_node;
11359               }
11360           }
11361
11362         return cp_build_qualified_type_real
11363           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11364       }
11365
11366     case UNBOUND_CLASS_TEMPLATE:
11367       {
11368         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11369                                      in_decl, /*entering_scope=*/1);
11370         tree name = TYPE_IDENTIFIER (t);
11371         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11372
11373         if (ctx == error_mark_node || name == error_mark_node)
11374           return error_mark_node;
11375
11376         if (parm_list)
11377           parm_list = tsubst_template_parms (parm_list, args, complain);
11378         return make_unbound_class_template (ctx, name, parm_list, complain);
11379       }
11380
11381     case TYPEOF_TYPE:
11382       {
11383         tree type;
11384
11385         ++cp_unevaluated_operand;
11386         ++c_inhibit_evaluation_warnings;
11387
11388         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11389                             complain, in_decl,
11390                             /*integral_constant_expression_p=*/false);
11391
11392         --cp_unevaluated_operand;
11393         --c_inhibit_evaluation_warnings;
11394
11395         type = finish_typeof (type);
11396         return cp_build_qualified_type_real (type,
11397                                              cp_type_quals (t)
11398                                              | cp_type_quals (type),
11399                                              complain);
11400       }
11401
11402     case DECLTYPE_TYPE:
11403       {
11404         tree type;
11405
11406         ++cp_unevaluated_operand;
11407         ++c_inhibit_evaluation_warnings;
11408
11409         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11410                             complain, in_decl,
11411                             /*integral_constant_expression_p=*/false);
11412
11413         --cp_unevaluated_operand;
11414         --c_inhibit_evaluation_warnings;
11415
11416         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11417           type = lambda_capture_field_type (type);
11418         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
11419           type = lambda_return_type (type);
11420         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11421           type = lambda_proxy_type (type);
11422         else
11423           type = finish_decltype_type
11424             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11425         return cp_build_qualified_type_real (type,
11426                                              cp_type_quals (t)
11427                                              | cp_type_quals (type),
11428                                              complain);
11429       }
11430
11431     case UNDERLYING_TYPE:
11432       {
11433         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11434                             complain, in_decl);
11435         return finish_underlying_type (type);
11436       }
11437
11438     case TYPE_ARGUMENT_PACK:
11439     case NONTYPE_ARGUMENT_PACK:
11440       {
11441         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11442         tree packed_out = 
11443           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11444                                 args,
11445                                 complain,
11446                                 in_decl);
11447         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11448
11449         /* For template nontype argument packs, also substitute into
11450            the type.  */
11451         if (code == NONTYPE_ARGUMENT_PACK)
11452           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11453
11454         return r;
11455       }
11456       break;
11457
11458     case INTEGER_CST:
11459     case REAL_CST:
11460     case STRING_CST:
11461     case PLUS_EXPR:
11462     case MINUS_EXPR:
11463     case NEGATE_EXPR:
11464     case NOP_EXPR:
11465     case INDIRECT_REF:
11466     case ADDR_EXPR:
11467     case CALL_EXPR:
11468     case ARRAY_REF:
11469     case SCOPE_REF:
11470       /* We should use one of the expression tsubsts for these codes.  */
11471       gcc_unreachable ();
11472
11473     default:
11474       sorry ("use of %qs in template", tree_code_name [(int) code]);
11475       return error_mark_node;
11476     }
11477 }
11478
11479 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11480    type of the expression on the left-hand side of the "." or "->"
11481    operator.  */
11482
11483 static tree
11484 tsubst_baselink (tree baselink, tree object_type,
11485                  tree args, tsubst_flags_t complain, tree in_decl)
11486 {
11487     tree name;
11488     tree qualifying_scope;
11489     tree fns;
11490     tree optype;
11491     tree template_args = 0;
11492     bool template_id_p = false;
11493
11494     /* A baselink indicates a function from a base class.  Both the
11495        BASELINK_ACCESS_BINFO and the base class referenced may
11496        indicate bases of the template class, rather than the
11497        instantiated class.  In addition, lookups that were not
11498        ambiguous before may be ambiguous now.  Therefore, we perform
11499        the lookup again.  */
11500     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11501     qualifying_scope = tsubst (qualifying_scope, args,
11502                                complain, in_decl);
11503     fns = BASELINK_FUNCTIONS (baselink);
11504     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11505     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11506       {
11507         template_id_p = true;
11508         template_args = TREE_OPERAND (fns, 1);
11509         fns = TREE_OPERAND (fns, 0);
11510         if (template_args)
11511           template_args = tsubst_template_args (template_args, args,
11512                                                 complain, in_decl);
11513       }
11514     name = DECL_NAME (get_first_fn (fns));
11515     if (IDENTIFIER_TYPENAME_P (name))
11516       name = mangle_conv_op_name_for_type (optype);
11517     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11518     if (!baselink)
11519       return error_mark_node;
11520
11521     /* If lookup found a single function, mark it as used at this
11522        point.  (If it lookup found multiple functions the one selected
11523        later by overload resolution will be marked as used at that
11524        point.)  */
11525     if (BASELINK_P (baselink))
11526       fns = BASELINK_FUNCTIONS (baselink);
11527     if (!template_id_p && !really_overloaded_fn (fns))
11528       mark_used (OVL_CURRENT (fns));
11529
11530     /* Add back the template arguments, if present.  */
11531     if (BASELINK_P (baselink) && template_id_p)
11532       BASELINK_FUNCTIONS (baselink)
11533         = build_nt (TEMPLATE_ID_EXPR,
11534                     BASELINK_FUNCTIONS (baselink),
11535                     template_args);
11536     /* Update the conversion operator type.  */
11537     BASELINK_OPTYPE (baselink) = optype;
11538
11539     if (!object_type)
11540       object_type = current_class_type;
11541     return adjust_result_of_qualified_name_lookup (baselink,
11542                                                    qualifying_scope,
11543                                                    object_type);
11544 }
11545
11546 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11547    true if the qualified-id will be a postfix-expression in-and-of
11548    itself; false if more of the postfix-expression follows the
11549    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11550    of "&".  */
11551
11552 static tree
11553 tsubst_qualified_id (tree qualified_id, tree args,
11554                      tsubst_flags_t complain, tree in_decl,
11555                      bool done, bool address_p)
11556 {
11557   tree expr;
11558   tree scope;
11559   tree name;
11560   bool is_template;
11561   tree template_args;
11562
11563   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11564
11565   /* Figure out what name to look up.  */
11566   name = TREE_OPERAND (qualified_id, 1);
11567   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11568     {
11569       is_template = true;
11570       template_args = TREE_OPERAND (name, 1);
11571       if (template_args)
11572         template_args = tsubst_template_args (template_args, args,
11573                                               complain, in_decl);
11574       name = TREE_OPERAND (name, 0);
11575     }
11576   else
11577     {
11578       is_template = false;
11579       template_args = NULL_TREE;
11580     }
11581
11582   /* Substitute into the qualifying scope.  When there are no ARGS, we
11583      are just trying to simplify a non-dependent expression.  In that
11584      case the qualifying scope may be dependent, and, in any case,
11585      substituting will not help.  */
11586   scope = TREE_OPERAND (qualified_id, 0);
11587   if (args)
11588     {
11589       scope = tsubst (scope, args, complain, in_decl);
11590       expr = tsubst_copy (name, args, complain, in_decl);
11591     }
11592   else
11593     expr = name;
11594
11595   if (dependent_scope_p (scope))
11596     {
11597       if (is_template)
11598         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11599       return build_qualified_name (NULL_TREE, scope, expr,
11600                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11601     }
11602
11603   if (!BASELINK_P (name) && !DECL_P (expr))
11604     {
11605       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11606         {
11607           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11608           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11609             {
11610               error ("qualifying type %qT does not match destructor name ~%qT",
11611                      scope, TREE_OPERAND (expr, 0));
11612               expr = error_mark_node;
11613             }
11614           else
11615             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11616                                           /*is_type_p=*/0, false);
11617         }
11618       else
11619         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11620       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11621                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11622         {
11623           if (complain & tf_error)
11624             {
11625               error ("dependent-name %qE is parsed as a non-type, but "
11626                      "instantiation yields a type", qualified_id);
11627               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11628             }
11629           return error_mark_node;
11630         }
11631     }
11632
11633   if (DECL_P (expr))
11634     {
11635       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11636                                            scope);
11637       /* Remember that there was a reference to this entity.  */
11638       mark_used (expr);
11639     }
11640
11641   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11642     {
11643       if (complain & tf_error)
11644         qualified_name_lookup_error (scope,
11645                                      TREE_OPERAND (qualified_id, 1),
11646                                      expr, input_location);
11647       return error_mark_node;
11648     }
11649
11650   if (is_template)
11651     expr = lookup_template_function (expr, template_args);
11652
11653   if (expr == error_mark_node && complain & tf_error)
11654     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11655                                  expr, input_location);
11656   else if (TYPE_P (scope))
11657     {
11658       expr = (adjust_result_of_qualified_name_lookup
11659               (expr, scope, current_class_type));
11660       expr = (finish_qualified_id_expr
11661               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11662                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11663                /*template_arg_p=*/false));
11664     }
11665
11666   /* Expressions do not generally have reference type.  */
11667   if (TREE_CODE (expr) != SCOPE_REF
11668       /* However, if we're about to form a pointer-to-member, we just
11669          want the referenced member referenced.  */
11670       && TREE_CODE (expr) != OFFSET_REF)
11671     expr = convert_from_reference (expr);
11672
11673   return expr;
11674 }
11675
11676 /* Like tsubst, but deals with expressions.  This function just replaces
11677    template parms; to finish processing the resultant expression, use
11678    tsubst_expr.  */
11679
11680 static tree
11681 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11682 {
11683   enum tree_code code;
11684   tree r;
11685
11686   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11687     return t;
11688
11689   code = TREE_CODE (t);
11690
11691   switch (code)
11692     {
11693     case PARM_DECL:
11694       r = retrieve_local_specialization (t);
11695
11696       if (r == NULL)
11697         {
11698           tree c;
11699           /* This can happen for a parameter name used later in a function
11700              declaration (such as in a late-specified return type).  Just
11701              make a dummy decl, since it's only used for its type.  */
11702           gcc_assert (cp_unevaluated_operand != 0);
11703           /* We copy T because want to tsubst the PARM_DECL only,
11704              not the following PARM_DECLs that are chained to T.  */
11705           c = copy_node (t);
11706           r = tsubst_decl (c, args, complain);
11707           /* Give it the template pattern as its context; its true context
11708              hasn't been instantiated yet and this is good enough for
11709              mangling.  */
11710           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11711         }
11712       
11713       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11714         r = ARGUMENT_PACK_SELECT_ARG (r);
11715       mark_used (r);
11716       return r;
11717
11718     case CONST_DECL:
11719       {
11720         tree enum_type;
11721         tree v;
11722
11723         if (DECL_TEMPLATE_PARM_P (t))
11724           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11725         /* There is no need to substitute into namespace-scope
11726            enumerators.  */
11727         if (DECL_NAMESPACE_SCOPE_P (t))
11728           return t;
11729         /* If ARGS is NULL, then T is known to be non-dependent.  */
11730         if (args == NULL_TREE)
11731           return integral_constant_value (t);
11732
11733         /* Unfortunately, we cannot just call lookup_name here.
11734            Consider:
11735
11736              template <int I> int f() {
11737              enum E { a = I };
11738              struct S { void g() { E e = a; } };
11739              };
11740
11741            When we instantiate f<7>::S::g(), say, lookup_name is not
11742            clever enough to find f<7>::a.  */
11743         enum_type
11744           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11745                               /*entering_scope=*/0);
11746
11747         for (v = TYPE_VALUES (enum_type);
11748              v != NULL_TREE;
11749              v = TREE_CHAIN (v))
11750           if (TREE_PURPOSE (v) == DECL_NAME (t))
11751             return TREE_VALUE (v);
11752
11753           /* We didn't find the name.  That should never happen; if
11754              name-lookup found it during preliminary parsing, we
11755              should find it again here during instantiation.  */
11756         gcc_unreachable ();
11757       }
11758       return t;
11759
11760     case FIELD_DECL:
11761       if (DECL_CONTEXT (t))
11762         {
11763           tree ctx;
11764
11765           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11766                                   /*entering_scope=*/1);
11767           if (ctx != DECL_CONTEXT (t))
11768             {
11769               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11770               if (!r)
11771                 {
11772                   if (complain & tf_error)
11773                     error ("using invalid field %qD", t);
11774                   return error_mark_node;
11775                 }
11776               return r;
11777             }
11778         }
11779
11780       return t;
11781
11782     case VAR_DECL:
11783     case FUNCTION_DECL:
11784       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11785           || local_variable_p (t))
11786         t = tsubst (t, args, complain, in_decl);
11787       mark_used (t);
11788       return t;
11789
11790     case OVERLOAD:
11791       /* An OVERLOAD will always be a non-dependent overload set; an
11792          overload set from function scope will just be represented with an
11793          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11794       gcc_assert (!uses_template_parms (t));
11795       return t;
11796
11797     case BASELINK:
11798       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11799
11800     case TEMPLATE_DECL:
11801       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11802         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11803                        args, complain, in_decl);
11804       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11805         return tsubst (t, args, complain, in_decl);
11806       else if (DECL_CLASS_SCOPE_P (t)
11807                && uses_template_parms (DECL_CONTEXT (t)))
11808         {
11809           /* Template template argument like the following example need
11810              special treatment:
11811
11812                template <template <class> class TT> struct C {};
11813                template <class T> struct D {
11814                  template <class U> struct E {};
11815                  C<E> c;                                // #1
11816                };
11817                D<int> d;                                // #2
11818
11819              We are processing the template argument `E' in #1 for
11820              the template instantiation #2.  Originally, `E' is a
11821              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11822              have to substitute this with one having context `D<int>'.  */
11823
11824           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11825           return lookup_field (context, DECL_NAME(t), 0, false);
11826         }
11827       else
11828         /* Ordinary template template argument.  */
11829         return t;
11830
11831     case CAST_EXPR:
11832     case REINTERPRET_CAST_EXPR:
11833     case CONST_CAST_EXPR:
11834     case STATIC_CAST_EXPR:
11835     case DYNAMIC_CAST_EXPR:
11836     case NOP_EXPR:
11837       return build1
11838         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11839          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11840
11841     case SIZEOF_EXPR:
11842       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11843         {
11844
11845           tree expanded;
11846           int len = 0;
11847
11848           ++cp_unevaluated_operand;
11849           ++c_inhibit_evaluation_warnings;
11850           /* We only want to compute the number of arguments.  */
11851           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11852                                             complain, in_decl);
11853           --cp_unevaluated_operand;
11854           --c_inhibit_evaluation_warnings;
11855
11856           if (TREE_CODE (expanded) == TREE_VEC)
11857             len = TREE_VEC_LENGTH (expanded);
11858
11859           if (expanded == error_mark_node)
11860             return error_mark_node;
11861           else if (PACK_EXPANSION_P (expanded)
11862                    || (TREE_CODE (expanded) == TREE_VEC
11863                        && len > 0
11864                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11865             {
11866               if (TREE_CODE (expanded) == TREE_VEC)
11867                 expanded = TREE_VEC_ELT (expanded, len - 1);
11868
11869               if (TYPE_P (expanded))
11870                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11871                                                    complain & tf_error);
11872               else
11873                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11874                                                    complain & tf_error);
11875             }
11876           else
11877             return build_int_cst (size_type_node, len);
11878         }
11879       /* Fall through */
11880
11881     case INDIRECT_REF:
11882     case NEGATE_EXPR:
11883     case TRUTH_NOT_EXPR:
11884     case BIT_NOT_EXPR:
11885     case ADDR_EXPR:
11886     case UNARY_PLUS_EXPR:      /* Unary + */
11887     case ALIGNOF_EXPR:
11888     case AT_ENCODE_EXPR:
11889     case ARROW_EXPR:
11890     case THROW_EXPR:
11891     case TYPEID_EXPR:
11892     case REALPART_EXPR:
11893     case IMAGPART_EXPR:
11894       return build1
11895         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11896          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11897
11898     case COMPONENT_REF:
11899       {
11900         tree object;
11901         tree name;
11902
11903         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11904         name = TREE_OPERAND (t, 1);
11905         if (TREE_CODE (name) == BIT_NOT_EXPR)
11906           {
11907             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11908                                 complain, in_decl);
11909             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11910           }
11911         else if (TREE_CODE (name) == SCOPE_REF
11912                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11913           {
11914             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11915                                      complain, in_decl);
11916             name = TREE_OPERAND (name, 1);
11917             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11918                                 complain, in_decl);
11919             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11920             name = build_qualified_name (/*type=*/NULL_TREE,
11921                                          base, name,
11922                                          /*template_p=*/false);
11923           }
11924         else if (TREE_CODE (name) == BASELINK)
11925           name = tsubst_baselink (name,
11926                                   non_reference (TREE_TYPE (object)),
11927                                   args, complain,
11928                                   in_decl);
11929         else
11930           name = tsubst_copy (name, args, complain, in_decl);
11931         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11932       }
11933
11934     case PLUS_EXPR:
11935     case MINUS_EXPR:
11936     case MULT_EXPR:
11937     case TRUNC_DIV_EXPR:
11938     case CEIL_DIV_EXPR:
11939     case FLOOR_DIV_EXPR:
11940     case ROUND_DIV_EXPR:
11941     case EXACT_DIV_EXPR:
11942     case BIT_AND_EXPR:
11943     case BIT_IOR_EXPR:
11944     case BIT_XOR_EXPR:
11945     case TRUNC_MOD_EXPR:
11946     case FLOOR_MOD_EXPR:
11947     case TRUTH_ANDIF_EXPR:
11948     case TRUTH_ORIF_EXPR:
11949     case TRUTH_AND_EXPR:
11950     case TRUTH_OR_EXPR:
11951     case RSHIFT_EXPR:
11952     case LSHIFT_EXPR:
11953     case RROTATE_EXPR:
11954     case LROTATE_EXPR:
11955     case EQ_EXPR:
11956     case NE_EXPR:
11957     case MAX_EXPR:
11958     case MIN_EXPR:
11959     case LE_EXPR:
11960     case GE_EXPR:
11961     case LT_EXPR:
11962     case GT_EXPR:
11963     case COMPOUND_EXPR:
11964     case DOTSTAR_EXPR:
11965     case MEMBER_REF:
11966     case PREDECREMENT_EXPR:
11967     case PREINCREMENT_EXPR:
11968     case POSTDECREMENT_EXPR:
11969     case POSTINCREMENT_EXPR:
11970       return build_nt
11971         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11972          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11973
11974     case SCOPE_REF:
11975       return build_qualified_name (/*type=*/NULL_TREE,
11976                                    tsubst_copy (TREE_OPERAND (t, 0),
11977                                                 args, complain, in_decl),
11978                                    tsubst_copy (TREE_OPERAND (t, 1),
11979                                                 args, complain, in_decl),
11980                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11981
11982     case ARRAY_REF:
11983       return build_nt
11984         (ARRAY_REF,
11985          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11986          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11987          NULL_TREE, NULL_TREE);
11988
11989     case CALL_EXPR:
11990       {
11991         int n = VL_EXP_OPERAND_LENGTH (t);
11992         tree result = build_vl_exp (CALL_EXPR, n);
11993         int i;
11994         for (i = 0; i < n; i++)
11995           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11996                                              complain, in_decl);
11997         return result;
11998       }
11999
12000     case COND_EXPR:
12001     case MODOP_EXPR:
12002     case PSEUDO_DTOR_EXPR:
12003       {
12004         r = build_nt
12005           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12006            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12007            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12008         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12009         return r;
12010       }
12011
12012     case NEW_EXPR:
12013       {
12014         r = build_nt
12015         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12016          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12017          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12018         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12019         return r;
12020       }
12021
12022     case DELETE_EXPR:
12023       {
12024         r = build_nt
12025         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12026          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12027         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12028         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12029         return r;
12030       }
12031
12032     case TEMPLATE_ID_EXPR:
12033       {
12034         /* Substituted template arguments */
12035         tree fn = TREE_OPERAND (t, 0);
12036         tree targs = TREE_OPERAND (t, 1);
12037
12038         fn = tsubst_copy (fn, args, complain, in_decl);
12039         if (targs)
12040           targs = tsubst_template_args (targs, args, complain, in_decl);
12041
12042         return lookup_template_function (fn, targs);
12043       }
12044
12045     case TREE_LIST:
12046       {
12047         tree purpose, value, chain;
12048
12049         if (t == void_list_node)
12050           return t;
12051
12052         purpose = TREE_PURPOSE (t);
12053         if (purpose)
12054           purpose = tsubst_copy (purpose, args, complain, in_decl);
12055         value = TREE_VALUE (t);
12056         if (value)
12057           value = tsubst_copy (value, args, complain, in_decl);
12058         chain = TREE_CHAIN (t);
12059         if (chain && chain != void_type_node)
12060           chain = tsubst_copy (chain, args, complain, in_decl);
12061         if (purpose == TREE_PURPOSE (t)
12062             && value == TREE_VALUE (t)
12063             && chain == TREE_CHAIN (t))
12064           return t;
12065         return tree_cons (purpose, value, chain);
12066       }
12067
12068     case RECORD_TYPE:
12069     case UNION_TYPE:
12070     case ENUMERAL_TYPE:
12071     case INTEGER_TYPE:
12072     case TEMPLATE_TYPE_PARM:
12073     case TEMPLATE_TEMPLATE_PARM:
12074     case BOUND_TEMPLATE_TEMPLATE_PARM:
12075     case TEMPLATE_PARM_INDEX:
12076     case POINTER_TYPE:
12077     case REFERENCE_TYPE:
12078     case OFFSET_TYPE:
12079     case FUNCTION_TYPE:
12080     case METHOD_TYPE:
12081     case ARRAY_TYPE:
12082     case TYPENAME_TYPE:
12083     case UNBOUND_CLASS_TEMPLATE:
12084     case TYPEOF_TYPE:
12085     case DECLTYPE_TYPE:
12086     case TYPE_DECL:
12087       return tsubst (t, args, complain, in_decl);
12088
12089     case IDENTIFIER_NODE:
12090       if (IDENTIFIER_TYPENAME_P (t))
12091         {
12092           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12093           return mangle_conv_op_name_for_type (new_type);
12094         }
12095       else
12096         return t;
12097
12098     case CONSTRUCTOR:
12099       /* This is handled by tsubst_copy_and_build.  */
12100       gcc_unreachable ();
12101
12102     case VA_ARG_EXPR:
12103       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12104                                           in_decl),
12105                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12106
12107     case CLEANUP_POINT_EXPR:
12108       /* We shouldn't have built any of these during initial template
12109          generation.  Instead, they should be built during instantiation
12110          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12111       gcc_unreachable ();
12112
12113     case OFFSET_REF:
12114       r = build2
12115         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12116          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12117          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12118       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12119       mark_used (TREE_OPERAND (r, 1));
12120       return r;
12121
12122     case EXPR_PACK_EXPANSION:
12123       error ("invalid use of pack expansion expression");
12124       return error_mark_node;
12125
12126     case NONTYPE_ARGUMENT_PACK:
12127       error ("use %<...%> to expand argument pack");
12128       return error_mark_node;
12129
12130     case INTEGER_CST:
12131     case REAL_CST:
12132     case STRING_CST:
12133     case COMPLEX_CST:
12134       {
12135         /* Instantiate any typedefs in the type.  */
12136         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12137         r = fold_convert (type, t);
12138         gcc_assert (TREE_CODE (r) == code);
12139         return r;
12140       }
12141
12142     case PTRMEM_CST:
12143       /* These can sometimes show up in a partial instantiation, but never
12144          involve template parms.  */
12145       gcc_assert (!uses_template_parms (t));
12146       return t;
12147
12148     default:
12149       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12150       gcc_checking_assert (false);
12151       return t;
12152     }
12153 }
12154
12155 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12156
12157 static tree
12158 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12159                     tree in_decl)
12160 {
12161   tree new_clauses = NULL, nc, oc;
12162
12163   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12164     {
12165       nc = copy_node (oc);
12166       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12167       new_clauses = nc;
12168
12169       switch (OMP_CLAUSE_CODE (nc))
12170         {
12171         case OMP_CLAUSE_LASTPRIVATE:
12172           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12173             {
12174               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12175               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12176                            in_decl, /*integral_constant_expression_p=*/false);
12177               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12178                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12179             }
12180           /* FALLTHRU */
12181         case OMP_CLAUSE_PRIVATE:
12182         case OMP_CLAUSE_SHARED:
12183         case OMP_CLAUSE_FIRSTPRIVATE:
12184         case OMP_CLAUSE_REDUCTION:
12185         case OMP_CLAUSE_COPYIN:
12186         case OMP_CLAUSE_COPYPRIVATE:
12187         case OMP_CLAUSE_IF:
12188         case OMP_CLAUSE_NUM_THREADS:
12189         case OMP_CLAUSE_SCHEDULE:
12190         case OMP_CLAUSE_COLLAPSE:
12191         case OMP_CLAUSE_FINAL:
12192           OMP_CLAUSE_OPERAND (nc, 0)
12193             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12194                            in_decl, /*integral_constant_expression_p=*/false);
12195           break;
12196         case OMP_CLAUSE_NOWAIT:
12197         case OMP_CLAUSE_ORDERED:
12198         case OMP_CLAUSE_DEFAULT:
12199         case OMP_CLAUSE_UNTIED:
12200         case OMP_CLAUSE_MERGEABLE:
12201           break;
12202         default:
12203           gcc_unreachable ();
12204         }
12205     }
12206
12207   return finish_omp_clauses (nreverse (new_clauses));
12208 }
12209
12210 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12211
12212 static tree
12213 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12214                           tree in_decl)
12215 {
12216 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12217
12218   tree purpose, value, chain;
12219
12220   if (t == NULL)
12221     return t;
12222
12223   if (TREE_CODE (t) != TREE_LIST)
12224     return tsubst_copy_and_build (t, args, complain, in_decl,
12225                                   /*function_p=*/false,
12226                                   /*integral_constant_expression_p=*/false);
12227
12228   if (t == void_list_node)
12229     return t;
12230
12231   purpose = TREE_PURPOSE (t);
12232   if (purpose)
12233     purpose = RECUR (purpose);
12234   value = TREE_VALUE (t);
12235   if (value && TREE_CODE (value) != LABEL_DECL)
12236     value = RECUR (value);
12237   chain = TREE_CHAIN (t);
12238   if (chain && chain != void_type_node)
12239     chain = RECUR (chain);
12240   return tree_cons (purpose, value, chain);
12241 #undef RECUR
12242 }
12243
12244 /* Substitute one OMP_FOR iterator.  */
12245
12246 static void
12247 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12248                          tree condv, tree incrv, tree *clauses,
12249                          tree args, tsubst_flags_t complain, tree in_decl,
12250                          bool integral_constant_expression_p)
12251 {
12252 #define RECUR(NODE)                             \
12253   tsubst_expr ((NODE), args, complain, in_decl, \
12254                integral_constant_expression_p)
12255   tree decl, init, cond, incr, auto_node;
12256
12257   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12258   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12259   decl = RECUR (TREE_OPERAND (init, 0));
12260   init = TREE_OPERAND (init, 1);
12261   auto_node = type_uses_auto (TREE_TYPE (decl));
12262   if (auto_node && init)
12263     {
12264       tree init_expr = init;
12265       if (TREE_CODE (init_expr) == DECL_EXPR)
12266         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12267       init_expr = RECUR (init_expr);
12268       TREE_TYPE (decl)
12269         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12270     }
12271   gcc_assert (!type_dependent_expression_p (decl));
12272
12273   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12274     {
12275       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12276       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12277       if (TREE_CODE (incr) == MODIFY_EXPR)
12278         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12279                                     RECUR (TREE_OPERAND (incr, 1)),
12280                                     complain);
12281       else
12282         incr = RECUR (incr);
12283       TREE_VEC_ELT (declv, i) = decl;
12284       TREE_VEC_ELT (initv, i) = init;
12285       TREE_VEC_ELT (condv, i) = cond;
12286       TREE_VEC_ELT (incrv, i) = incr;
12287       return;
12288     }
12289
12290   if (init && TREE_CODE (init) != DECL_EXPR)
12291     {
12292       tree c;
12293       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12294         {
12295           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12296                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12297               && OMP_CLAUSE_DECL (c) == decl)
12298             break;
12299           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12300                    && OMP_CLAUSE_DECL (c) == decl)
12301             error ("iteration variable %qD should not be firstprivate", decl);
12302           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12303                    && OMP_CLAUSE_DECL (c) == decl)
12304             error ("iteration variable %qD should not be reduction", decl);
12305         }
12306       if (c == NULL)
12307         {
12308           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12309           OMP_CLAUSE_DECL (c) = decl;
12310           c = finish_omp_clauses (c);
12311           if (c)
12312             {
12313               OMP_CLAUSE_CHAIN (c) = *clauses;
12314               *clauses = c;
12315             }
12316         }
12317     }
12318   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12319   if (COMPARISON_CLASS_P (cond))
12320     cond = build2 (TREE_CODE (cond), boolean_type_node,
12321                    RECUR (TREE_OPERAND (cond, 0)),
12322                    RECUR (TREE_OPERAND (cond, 1)));
12323   else
12324     cond = RECUR (cond);
12325   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12326   switch (TREE_CODE (incr))
12327     {
12328     case PREINCREMENT_EXPR:
12329     case PREDECREMENT_EXPR:
12330     case POSTINCREMENT_EXPR:
12331     case POSTDECREMENT_EXPR:
12332       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12333                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12334       break;
12335     case MODIFY_EXPR:
12336       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12337           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12338         {
12339           tree rhs = TREE_OPERAND (incr, 1);
12340           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12341                          RECUR (TREE_OPERAND (incr, 0)),
12342                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12343                                  RECUR (TREE_OPERAND (rhs, 0)),
12344                                  RECUR (TREE_OPERAND (rhs, 1))));
12345         }
12346       else
12347         incr = RECUR (incr);
12348       break;
12349     case MODOP_EXPR:
12350       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12351           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12352         {
12353           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12354           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12355                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12356                                  TREE_TYPE (decl), lhs,
12357                                  RECUR (TREE_OPERAND (incr, 2))));
12358         }
12359       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12360                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12361                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12362         {
12363           tree rhs = TREE_OPERAND (incr, 2);
12364           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12365                          RECUR (TREE_OPERAND (incr, 0)),
12366                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12367                                  RECUR (TREE_OPERAND (rhs, 0)),
12368                                  RECUR (TREE_OPERAND (rhs, 1))));
12369         }
12370       else
12371         incr = RECUR (incr);
12372       break;
12373     default:
12374       incr = RECUR (incr);
12375       break;
12376     }
12377
12378   TREE_VEC_ELT (declv, i) = decl;
12379   TREE_VEC_ELT (initv, i) = init;
12380   TREE_VEC_ELT (condv, i) = cond;
12381   TREE_VEC_ELT (incrv, i) = incr;
12382 #undef RECUR
12383 }
12384
12385 /* Like tsubst_copy for expressions, etc. but also does semantic
12386    processing.  */
12387
12388 static tree
12389 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12390              bool integral_constant_expression_p)
12391 {
12392 #define RECUR(NODE)                             \
12393   tsubst_expr ((NODE), args, complain, in_decl, \
12394                integral_constant_expression_p)
12395
12396   tree stmt, tmp;
12397
12398   if (t == NULL_TREE || t == error_mark_node)
12399     return t;
12400
12401   if (EXPR_HAS_LOCATION (t))
12402     input_location = EXPR_LOCATION (t);
12403   if (STATEMENT_CODE_P (TREE_CODE (t)))
12404     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12405
12406   switch (TREE_CODE (t))
12407     {
12408     case STATEMENT_LIST:
12409       {
12410         tree_stmt_iterator i;
12411         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12412           RECUR (tsi_stmt (i));
12413         break;
12414       }
12415
12416     case CTOR_INITIALIZER:
12417       finish_mem_initializers (tsubst_initializer_list
12418                                (TREE_OPERAND (t, 0), args));
12419       break;
12420
12421     case RETURN_EXPR:
12422       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12423       break;
12424
12425     case EXPR_STMT:
12426       tmp = RECUR (EXPR_STMT_EXPR (t));
12427       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12428         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12429       else
12430         finish_expr_stmt (tmp);
12431       break;
12432
12433     case USING_STMT:
12434       do_using_directive (USING_STMT_NAMESPACE (t));
12435       break;
12436
12437     case DECL_EXPR:
12438       {
12439         tree decl, pattern_decl;
12440         tree init;
12441
12442         pattern_decl = decl = DECL_EXPR_DECL (t);
12443         if (TREE_CODE (decl) == LABEL_DECL)
12444           finish_label_decl (DECL_NAME (decl));
12445         else if (TREE_CODE (decl) == USING_DECL)
12446           {
12447             tree scope = USING_DECL_SCOPE (decl);
12448             tree name = DECL_NAME (decl);
12449             tree decl;
12450
12451             scope = tsubst (scope, args, complain, in_decl);
12452             decl = lookup_qualified_name (scope, name,
12453                                           /*is_type_p=*/false,
12454                                           /*complain=*/false);
12455             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12456               qualified_name_lookup_error (scope, name, decl, input_location);
12457             else
12458               do_local_using_decl (decl, scope, name);
12459           }
12460         else
12461           {
12462             init = DECL_INITIAL (decl);
12463             decl = tsubst (decl, args, complain, in_decl);
12464             if (decl != error_mark_node)
12465               {
12466                 /* By marking the declaration as instantiated, we avoid
12467                    trying to instantiate it.  Since instantiate_decl can't
12468                    handle local variables, and since we've already done
12469                    all that needs to be done, that's the right thing to
12470                    do.  */
12471                 if (TREE_CODE (decl) == VAR_DECL)
12472                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12473                 if (TREE_CODE (decl) == VAR_DECL
12474                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12475                   /* Anonymous aggregates are a special case.  */
12476                   finish_anon_union (decl);
12477                 else
12478                   {
12479                     int const_init = false;
12480                     maybe_push_decl (decl);
12481                     if (TREE_CODE (decl) == VAR_DECL
12482                         && DECL_PRETTY_FUNCTION_P (decl))
12483                       {
12484                         /* For __PRETTY_FUNCTION__ we have to adjust the
12485                            initializer.  */
12486                         const char *const name
12487                           = cxx_printable_name (current_function_decl, 2);
12488                         init = cp_fname_init (name, &TREE_TYPE (decl));
12489                       }
12490                     else
12491                       {
12492                         tree t = RECUR (init);
12493
12494                         if (init && !t)
12495                           {
12496                             /* If we had an initializer but it
12497                                instantiated to nothing,
12498                                value-initialize the object.  This will
12499                                only occur when the initializer was a
12500                                pack expansion where the parameter packs
12501                                used in that expansion were of length
12502                                zero.  */
12503                             init = build_value_init (TREE_TYPE (decl),
12504                                                      complain);
12505                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12506                               init = get_target_expr_sfinae (init, complain);
12507                           }
12508                         else
12509                           init = t;
12510                       }
12511
12512                     if (TREE_CODE (decl) == VAR_DECL)
12513                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12514                                     (pattern_decl));
12515                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12516                   }
12517               }
12518           }
12519
12520         /* A DECL_EXPR can also be used as an expression, in the condition
12521            clause of an if/for/while construct.  */
12522         return decl;
12523       }
12524
12525     case FOR_STMT:
12526       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12527       RECUR (FOR_INIT_STMT (t));
12528       finish_for_init_stmt (stmt);
12529       tmp = RECUR (FOR_COND (t));
12530       finish_for_cond (tmp, stmt);
12531       tmp = RECUR (FOR_EXPR (t));
12532       finish_for_expr (tmp, stmt);
12533       RECUR (FOR_BODY (t));
12534       finish_for_stmt (stmt);
12535       break;
12536
12537     case RANGE_FOR_STMT:
12538       {
12539         tree decl, expr;
12540         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12541         decl = RANGE_FOR_DECL (t);
12542         decl = tsubst (decl, args, complain, in_decl);
12543         maybe_push_decl (decl);
12544         expr = RECUR (RANGE_FOR_EXPR (t));
12545         stmt = cp_convert_range_for (stmt, decl, expr);
12546         RECUR (RANGE_FOR_BODY (t));
12547         finish_for_stmt (stmt);
12548       }
12549       break;
12550
12551     case WHILE_STMT:
12552       stmt = begin_while_stmt ();
12553       tmp = RECUR (WHILE_COND (t));
12554       finish_while_stmt_cond (tmp, stmt);
12555       RECUR (WHILE_BODY (t));
12556       finish_while_stmt (stmt);
12557       break;
12558
12559     case DO_STMT:
12560       stmt = begin_do_stmt ();
12561       RECUR (DO_BODY (t));
12562       finish_do_body (stmt);
12563       tmp = RECUR (DO_COND (t));
12564       finish_do_stmt (tmp, stmt);
12565       break;
12566
12567     case IF_STMT:
12568       stmt = begin_if_stmt ();
12569       tmp = RECUR (IF_COND (t));
12570       finish_if_stmt_cond (tmp, stmt);
12571       RECUR (THEN_CLAUSE (t));
12572       finish_then_clause (stmt);
12573
12574       if (ELSE_CLAUSE (t))
12575         {
12576           begin_else_clause (stmt);
12577           RECUR (ELSE_CLAUSE (t));
12578           finish_else_clause (stmt);
12579         }
12580
12581       finish_if_stmt (stmt);
12582       break;
12583
12584     case BIND_EXPR:
12585       if (BIND_EXPR_BODY_BLOCK (t))
12586         stmt = begin_function_body ();
12587       else
12588         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12589                                     ? BCS_TRY_BLOCK : 0);
12590
12591       RECUR (BIND_EXPR_BODY (t));
12592
12593       if (BIND_EXPR_BODY_BLOCK (t))
12594         finish_function_body (stmt);
12595       else
12596         finish_compound_stmt (stmt);
12597       break;
12598
12599     case BREAK_STMT:
12600       finish_break_stmt ();
12601       break;
12602
12603     case CONTINUE_STMT:
12604       finish_continue_stmt ();
12605       break;
12606
12607     case SWITCH_STMT:
12608       stmt = begin_switch_stmt ();
12609       tmp = RECUR (SWITCH_STMT_COND (t));
12610       finish_switch_cond (tmp, stmt);
12611       RECUR (SWITCH_STMT_BODY (t));
12612       finish_switch_stmt (stmt);
12613       break;
12614
12615     case CASE_LABEL_EXPR:
12616       finish_case_label (EXPR_LOCATION (t),
12617                          RECUR (CASE_LOW (t)),
12618                          RECUR (CASE_HIGH (t)));
12619       break;
12620
12621     case LABEL_EXPR:
12622       {
12623         tree decl = LABEL_EXPR_LABEL (t);
12624         tree label;
12625
12626         label = finish_label_stmt (DECL_NAME (decl));
12627         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12628           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12629       }
12630       break;
12631
12632     case GOTO_EXPR:
12633       tmp = GOTO_DESTINATION (t);
12634       if (TREE_CODE (tmp) != LABEL_DECL)
12635         /* Computed goto's must be tsubst'd into.  On the other hand,
12636            non-computed gotos must not be; the identifier in question
12637            will have no binding.  */
12638         tmp = RECUR (tmp);
12639       else
12640         tmp = DECL_NAME (tmp);
12641       finish_goto_stmt (tmp);
12642       break;
12643
12644     case ASM_EXPR:
12645       tmp = finish_asm_stmt
12646         (ASM_VOLATILE_P (t),
12647          RECUR (ASM_STRING (t)),
12648          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12649          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12650          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12651          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12652       {
12653         tree asm_expr = tmp;
12654         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12655           asm_expr = TREE_OPERAND (asm_expr, 0);
12656         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12657       }
12658       break;
12659
12660     case TRY_BLOCK:
12661       if (CLEANUP_P (t))
12662         {
12663           stmt = begin_try_block ();
12664           RECUR (TRY_STMTS (t));
12665           finish_cleanup_try_block (stmt);
12666           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12667         }
12668       else
12669         {
12670           tree compound_stmt = NULL_TREE;
12671
12672           if (FN_TRY_BLOCK_P (t))
12673             stmt = begin_function_try_block (&compound_stmt);
12674           else
12675             stmt = begin_try_block ();
12676
12677           RECUR (TRY_STMTS (t));
12678
12679           if (FN_TRY_BLOCK_P (t))
12680             finish_function_try_block (stmt);
12681           else
12682             finish_try_block (stmt);
12683
12684           RECUR (TRY_HANDLERS (t));
12685           if (FN_TRY_BLOCK_P (t))
12686             finish_function_handler_sequence (stmt, compound_stmt);
12687           else
12688             finish_handler_sequence (stmt);
12689         }
12690       break;
12691
12692     case HANDLER:
12693       {
12694         tree decl = HANDLER_PARMS (t);
12695
12696         if (decl)
12697           {
12698             decl = tsubst (decl, args, complain, in_decl);
12699             /* Prevent instantiate_decl from trying to instantiate
12700                this variable.  We've already done all that needs to be
12701                done.  */
12702             if (decl != error_mark_node)
12703               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12704           }
12705         stmt = begin_handler ();
12706         finish_handler_parms (decl, stmt);
12707         RECUR (HANDLER_BODY (t));
12708         finish_handler (stmt);
12709       }
12710       break;
12711
12712     case TAG_DEFN:
12713       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12714       break;
12715
12716     case STATIC_ASSERT:
12717       {
12718         tree condition = 
12719           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12720                        args,
12721                        complain, in_decl,
12722                        /*integral_constant_expression_p=*/true);
12723         finish_static_assert (condition,
12724                               STATIC_ASSERT_MESSAGE (t),
12725                               STATIC_ASSERT_SOURCE_LOCATION (t),
12726                               /*member_p=*/false);
12727       }
12728       break;
12729
12730     case OMP_PARALLEL:
12731       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12732                                 args, complain, in_decl);
12733       stmt = begin_omp_parallel ();
12734       RECUR (OMP_PARALLEL_BODY (t));
12735       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12736         = OMP_PARALLEL_COMBINED (t);
12737       break;
12738
12739     case OMP_TASK:
12740       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12741                                 args, complain, in_decl);
12742       stmt = begin_omp_task ();
12743       RECUR (OMP_TASK_BODY (t));
12744       finish_omp_task (tmp, stmt);
12745       break;
12746
12747     case OMP_FOR:
12748       {
12749         tree clauses, body, pre_body;
12750         tree declv, initv, condv, incrv;
12751         int i;
12752
12753         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12754                                       args, complain, in_decl);
12755         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12756         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12757         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12758         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12759
12760         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12761           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12762                                    &clauses, args, complain, in_decl,
12763                                    integral_constant_expression_p);
12764
12765         stmt = begin_omp_structured_block ();
12766
12767         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12768           if (TREE_VEC_ELT (initv, i) == NULL
12769               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12770             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12771           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12772             {
12773               tree init = RECUR (TREE_VEC_ELT (initv, i));
12774               gcc_assert (init == TREE_VEC_ELT (declv, i));
12775               TREE_VEC_ELT (initv, i) = NULL_TREE;
12776             }
12777           else
12778             {
12779               tree decl_expr = TREE_VEC_ELT (initv, i);
12780               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12781               gcc_assert (init != NULL);
12782               TREE_VEC_ELT (initv, i) = RECUR (init);
12783               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12784               RECUR (decl_expr);
12785               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12786             }
12787
12788         pre_body = push_stmt_list ();
12789         RECUR (OMP_FOR_PRE_BODY (t));
12790         pre_body = pop_stmt_list (pre_body);
12791
12792         body = push_stmt_list ();
12793         RECUR (OMP_FOR_BODY (t));
12794         body = pop_stmt_list (body);
12795
12796         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12797                             body, pre_body, clauses);
12798
12799         add_stmt (finish_omp_structured_block (stmt));
12800       }
12801       break;
12802
12803     case OMP_SECTIONS:
12804     case OMP_SINGLE:
12805       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12806       stmt = push_stmt_list ();
12807       RECUR (OMP_BODY (t));
12808       stmt = pop_stmt_list (stmt);
12809
12810       t = copy_node (t);
12811       OMP_BODY (t) = stmt;
12812       OMP_CLAUSES (t) = tmp;
12813       add_stmt (t);
12814       break;
12815
12816     case OMP_SECTION:
12817     case OMP_CRITICAL:
12818     case OMP_MASTER:
12819     case OMP_ORDERED:
12820       stmt = push_stmt_list ();
12821       RECUR (OMP_BODY (t));
12822       stmt = pop_stmt_list (stmt);
12823
12824       t = copy_node (t);
12825       OMP_BODY (t) = stmt;
12826       add_stmt (t);
12827       break;
12828
12829     case OMP_ATOMIC:
12830       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12831       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12832         {
12833           tree op1 = TREE_OPERAND (t, 1);
12834           tree rhs1 = NULL_TREE;
12835           tree lhs, rhs;
12836           if (TREE_CODE (op1) == COMPOUND_EXPR)
12837             {
12838               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12839               op1 = TREE_OPERAND (op1, 1);
12840             }
12841           lhs = RECUR (TREE_OPERAND (op1, 0));
12842           rhs = RECUR (TREE_OPERAND (op1, 1));
12843           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12844                              NULL_TREE, NULL_TREE, rhs1);
12845         }
12846       else
12847         {
12848           tree op1 = TREE_OPERAND (t, 1);
12849           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12850           tree rhs1 = NULL_TREE;
12851           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12852           enum tree_code opcode = NOP_EXPR;
12853           if (code == OMP_ATOMIC_READ)
12854             {
12855               v = RECUR (TREE_OPERAND (op1, 0));
12856               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12857             }
12858           else if (code == OMP_ATOMIC_CAPTURE_OLD
12859                    || code == OMP_ATOMIC_CAPTURE_NEW)
12860             {
12861               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12862               v = RECUR (TREE_OPERAND (op1, 0));
12863               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12864               if (TREE_CODE (op11) == COMPOUND_EXPR)
12865                 {
12866                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12867                   op11 = TREE_OPERAND (op11, 1);
12868                 }
12869               lhs = RECUR (TREE_OPERAND (op11, 0));
12870               rhs = RECUR (TREE_OPERAND (op11, 1));
12871               opcode = TREE_CODE (op11);
12872             }
12873           else
12874             {
12875               code = OMP_ATOMIC;
12876               lhs = RECUR (TREE_OPERAND (op1, 0));
12877               rhs = RECUR (TREE_OPERAND (op1, 1));
12878             }
12879           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12880         }
12881       break;
12882
12883     case EXPR_PACK_EXPANSION:
12884       error ("invalid use of pack expansion expression");
12885       return error_mark_node;
12886
12887     case NONTYPE_ARGUMENT_PACK:
12888       error ("use %<...%> to expand argument pack");
12889       return error_mark_node;
12890
12891     default:
12892       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12893
12894       return tsubst_copy_and_build (t, args, complain, in_decl,
12895                                     /*function_p=*/false,
12896                                     integral_constant_expression_p);
12897     }
12898
12899   return NULL_TREE;
12900 #undef RECUR
12901 }
12902
12903 /* T is a postfix-expression that is not being used in a function
12904    call.  Return the substituted version of T.  */
12905
12906 static tree
12907 tsubst_non_call_postfix_expression (tree t, tree args,
12908                                     tsubst_flags_t complain,
12909                                     tree in_decl)
12910 {
12911   if (TREE_CODE (t) == SCOPE_REF)
12912     t = tsubst_qualified_id (t, args, complain, in_decl,
12913                              /*done=*/false, /*address_p=*/false);
12914   else
12915     t = tsubst_copy_and_build (t, args, complain, in_decl,
12916                                /*function_p=*/false,
12917                                /*integral_constant_expression_p=*/false);
12918
12919   return t;
12920 }
12921
12922 /* Like tsubst but deals with expressions and performs semantic
12923    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12924
12925 tree
12926 tsubst_copy_and_build (tree t,
12927                        tree args,
12928                        tsubst_flags_t complain,
12929                        tree in_decl,
12930                        bool function_p,
12931                        bool integral_constant_expression_p)
12932 {
12933 #define RECUR(NODE)                                             \
12934   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12935                          /*function_p=*/false,                  \
12936                          integral_constant_expression_p)
12937
12938   tree op1;
12939
12940   if (t == NULL_TREE || t == error_mark_node)
12941     return t;
12942
12943   switch (TREE_CODE (t))
12944     {
12945     case USING_DECL:
12946       t = DECL_NAME (t);
12947       /* Fall through.  */
12948     case IDENTIFIER_NODE:
12949       {
12950         tree decl;
12951         cp_id_kind idk;
12952         bool non_integral_constant_expression_p;
12953         const char *error_msg;
12954
12955         if (IDENTIFIER_TYPENAME_P (t))
12956           {
12957             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12958             t = mangle_conv_op_name_for_type (new_type);
12959           }
12960
12961         /* Look up the name.  */
12962         decl = lookup_name (t);
12963
12964         /* By convention, expressions use ERROR_MARK_NODE to indicate
12965            failure, not NULL_TREE.  */
12966         if (decl == NULL_TREE)
12967           decl = error_mark_node;
12968
12969         decl = finish_id_expression (t, decl, NULL_TREE,
12970                                      &idk,
12971                                      integral_constant_expression_p,
12972                                      /*allow_non_integral_constant_expression_p=*/false,
12973                                      &non_integral_constant_expression_p,
12974                                      /*template_p=*/false,
12975                                      /*done=*/true,
12976                                      /*address_p=*/false,
12977                                      /*template_arg_p=*/false,
12978                                      &error_msg,
12979                                      input_location);
12980         if (error_msg)
12981           error (error_msg);
12982         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12983           decl = unqualified_name_lookup_error (decl);
12984         return decl;
12985       }
12986
12987     case TEMPLATE_ID_EXPR:
12988       {
12989         tree object;
12990         tree templ = RECUR (TREE_OPERAND (t, 0));
12991         tree targs = TREE_OPERAND (t, 1);
12992
12993         if (targs)
12994           targs = tsubst_template_args (targs, args, complain, in_decl);
12995
12996         if (TREE_CODE (templ) == COMPONENT_REF)
12997           {
12998             object = TREE_OPERAND (templ, 0);
12999             templ = TREE_OPERAND (templ, 1);
13000           }
13001         else
13002           object = NULL_TREE;
13003         templ = lookup_template_function (templ, targs);
13004
13005         if (object)
13006           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13007                          object, templ, NULL_TREE);
13008         else
13009           return baselink_for_fns (templ);
13010       }
13011
13012     case INDIRECT_REF:
13013       {
13014         tree r = RECUR (TREE_OPERAND (t, 0));
13015
13016         if (REFERENCE_REF_P (t))
13017           {
13018             /* A type conversion to reference type will be enclosed in
13019                such an indirect ref, but the substitution of the cast
13020                will have also added such an indirect ref.  */
13021             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13022               r = convert_from_reference (r);
13023           }
13024         else
13025           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13026         return r;
13027       }
13028
13029     case NOP_EXPR:
13030       return build_nop
13031         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13032          RECUR (TREE_OPERAND (t, 0)));
13033
13034     case CAST_EXPR:
13035     case REINTERPRET_CAST_EXPR:
13036     case CONST_CAST_EXPR:
13037     case DYNAMIC_CAST_EXPR:
13038     case STATIC_CAST_EXPR:
13039       {
13040         tree type;
13041         tree op;
13042
13043         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13044         if (integral_constant_expression_p
13045             && !cast_valid_in_integral_constant_expression_p (type))
13046           {
13047             if (complain & tf_error)
13048               error ("a cast to a type other than an integral or "
13049                      "enumeration type cannot appear in a constant-expression");
13050             return error_mark_node; 
13051           }
13052
13053         op = RECUR (TREE_OPERAND (t, 0));
13054
13055         switch (TREE_CODE (t))
13056           {
13057           case CAST_EXPR:
13058             return build_functional_cast (type, op, complain);
13059           case REINTERPRET_CAST_EXPR:
13060             return build_reinterpret_cast (type, op, complain);
13061           case CONST_CAST_EXPR:
13062             return build_const_cast (type, op, complain);
13063           case DYNAMIC_CAST_EXPR:
13064             return build_dynamic_cast (type, op, complain);
13065           case STATIC_CAST_EXPR:
13066             return build_static_cast (type, op, complain);
13067           default:
13068             gcc_unreachable ();
13069           }
13070       }
13071
13072     case POSTDECREMENT_EXPR:
13073     case POSTINCREMENT_EXPR:
13074       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13075                                                 args, complain, in_decl);
13076       return build_x_unary_op (TREE_CODE (t), op1, complain);
13077
13078     case PREDECREMENT_EXPR:
13079     case PREINCREMENT_EXPR:
13080     case NEGATE_EXPR:
13081     case BIT_NOT_EXPR:
13082     case ABS_EXPR:
13083     case TRUTH_NOT_EXPR:
13084     case UNARY_PLUS_EXPR:  /* Unary + */
13085     case REALPART_EXPR:
13086     case IMAGPART_EXPR:
13087       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13088                                complain);
13089
13090     case ADDR_EXPR:
13091       op1 = TREE_OPERAND (t, 0);
13092       if (TREE_CODE (op1) == LABEL_DECL)
13093         return finish_label_address_expr (DECL_NAME (op1),
13094                                           EXPR_LOCATION (op1));
13095       if (TREE_CODE (op1) == SCOPE_REF)
13096         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13097                                    /*done=*/true, /*address_p=*/true);
13098       else
13099         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13100                                                   in_decl);
13101       return build_x_unary_op (ADDR_EXPR, op1, complain);
13102
13103     case PLUS_EXPR:
13104     case MINUS_EXPR:
13105     case MULT_EXPR:
13106     case TRUNC_DIV_EXPR:
13107     case CEIL_DIV_EXPR:
13108     case FLOOR_DIV_EXPR:
13109     case ROUND_DIV_EXPR:
13110     case EXACT_DIV_EXPR:
13111     case BIT_AND_EXPR:
13112     case BIT_IOR_EXPR:
13113     case BIT_XOR_EXPR:
13114     case TRUNC_MOD_EXPR:
13115     case FLOOR_MOD_EXPR:
13116     case TRUTH_ANDIF_EXPR:
13117     case TRUTH_ORIF_EXPR:
13118     case TRUTH_AND_EXPR:
13119     case TRUTH_OR_EXPR:
13120     case RSHIFT_EXPR:
13121     case LSHIFT_EXPR:
13122     case RROTATE_EXPR:
13123     case LROTATE_EXPR:
13124     case EQ_EXPR:
13125     case NE_EXPR:
13126     case MAX_EXPR:
13127     case MIN_EXPR:
13128     case LE_EXPR:
13129     case GE_EXPR:
13130     case LT_EXPR:
13131     case GT_EXPR:
13132     case MEMBER_REF:
13133     case DOTSTAR_EXPR:
13134       return build_x_binary_op
13135         (TREE_CODE (t),
13136          RECUR (TREE_OPERAND (t, 0)),
13137          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13138           ? ERROR_MARK
13139           : TREE_CODE (TREE_OPERAND (t, 0))),
13140          RECUR (TREE_OPERAND (t, 1)),
13141          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13142           ? ERROR_MARK
13143           : TREE_CODE (TREE_OPERAND (t, 1))),
13144          /*overload=*/NULL,
13145          complain);
13146
13147     case SCOPE_REF:
13148       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13149                                   /*address_p=*/false);
13150     case ARRAY_REF:
13151       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13152                                                 args, complain, in_decl);
13153       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13154
13155     case SIZEOF_EXPR:
13156       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13157         return tsubst_copy (t, args, complain, in_decl);
13158       /* Fall through */
13159       
13160     case ALIGNOF_EXPR:
13161       op1 = TREE_OPERAND (t, 0);
13162       if (!args)
13163         {
13164           /* When there are no ARGS, we are trying to evaluate a
13165              non-dependent expression from the parser.  Trying to do
13166              the substitutions may not work.  */
13167           if (!TYPE_P (op1))
13168             op1 = TREE_TYPE (op1);
13169         }
13170       else
13171         {
13172           ++cp_unevaluated_operand;
13173           ++c_inhibit_evaluation_warnings;
13174           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13175                                        /*function_p=*/false,
13176                                        /*integral_constant_expression_p=*/false);
13177           --cp_unevaluated_operand;
13178           --c_inhibit_evaluation_warnings;
13179         }
13180       if (TYPE_P (op1))
13181         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13182                                            complain & tf_error);
13183       else
13184         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13185                                            complain & tf_error);
13186
13187     case AT_ENCODE_EXPR:
13188       {
13189         op1 = TREE_OPERAND (t, 0);
13190         ++cp_unevaluated_operand;
13191         ++c_inhibit_evaluation_warnings;
13192         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13193                                      /*function_p=*/false,
13194                                      /*integral_constant_expression_p=*/false);
13195         --cp_unevaluated_operand;
13196         --c_inhibit_evaluation_warnings;
13197         return objc_build_encode_expr (op1);
13198       }
13199
13200     case NOEXCEPT_EXPR:
13201       op1 = TREE_OPERAND (t, 0);
13202       ++cp_unevaluated_operand;
13203       ++c_inhibit_evaluation_warnings;
13204       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13205                                    /*function_p=*/false,
13206                                    /*integral_constant_expression_p=*/false);
13207       --cp_unevaluated_operand;
13208       --c_inhibit_evaluation_warnings;
13209       return finish_noexcept_expr (op1, complain);
13210
13211     case MODOP_EXPR:
13212       {
13213         tree r = build_x_modify_expr
13214           (RECUR (TREE_OPERAND (t, 0)),
13215            TREE_CODE (TREE_OPERAND (t, 1)),
13216            RECUR (TREE_OPERAND (t, 2)),
13217            complain);
13218         /* TREE_NO_WARNING must be set if either the expression was
13219            parenthesized or it uses an operator such as >>= rather
13220            than plain assignment.  In the former case, it was already
13221            set and must be copied.  In the latter case,
13222            build_x_modify_expr sets it and it must not be reset
13223            here.  */
13224         if (TREE_NO_WARNING (t))
13225           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13226         return r;
13227       }
13228
13229     case ARROW_EXPR:
13230       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13231                                                 args, complain, in_decl);
13232       /* Remember that there was a reference to this entity.  */
13233       if (DECL_P (op1))
13234         mark_used (op1);
13235       return build_x_arrow (op1);
13236
13237     case NEW_EXPR:
13238       {
13239         tree placement = RECUR (TREE_OPERAND (t, 0));
13240         tree init = RECUR (TREE_OPERAND (t, 3));
13241         VEC(tree,gc) *placement_vec;
13242         VEC(tree,gc) *init_vec;
13243         tree ret;
13244
13245         if (placement == NULL_TREE)
13246           placement_vec = NULL;
13247         else
13248           {
13249             placement_vec = make_tree_vector ();
13250             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13251               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13252           }
13253
13254         /* If there was an initializer in the original tree, but it
13255            instantiated to an empty list, then we should pass a
13256            non-NULL empty vector to tell build_new that it was an
13257            empty initializer() rather than no initializer.  This can
13258            only happen when the initializer is a pack expansion whose
13259            parameter packs are of length zero.  */
13260         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13261           init_vec = NULL;
13262         else
13263           {
13264             init_vec = make_tree_vector ();
13265             if (init == void_zero_node)
13266               gcc_assert (init_vec != NULL);
13267             else
13268               {
13269                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13270                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13271               }
13272           }
13273
13274         ret = build_new (&placement_vec,
13275                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13276                          RECUR (TREE_OPERAND (t, 2)),
13277                          &init_vec,
13278                          NEW_EXPR_USE_GLOBAL (t),
13279                          complain);
13280
13281         if (placement_vec != NULL)
13282           release_tree_vector (placement_vec);
13283         if (init_vec != NULL)
13284           release_tree_vector (init_vec);
13285
13286         return ret;
13287       }
13288
13289     case DELETE_EXPR:
13290      return delete_sanity
13291        (RECUR (TREE_OPERAND (t, 0)),
13292         RECUR (TREE_OPERAND (t, 1)),
13293         DELETE_EXPR_USE_VEC (t),
13294         DELETE_EXPR_USE_GLOBAL (t),
13295         complain);
13296
13297     case COMPOUND_EXPR:
13298       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13299                                     RECUR (TREE_OPERAND (t, 1)),
13300                                     complain);
13301
13302     case CALL_EXPR:
13303       {
13304         tree function;
13305         VEC(tree,gc) *call_args;
13306         unsigned int nargs, i;
13307         bool qualified_p;
13308         bool koenig_p;
13309         tree ret;
13310
13311         function = CALL_EXPR_FN (t);
13312         /* When we parsed the expression,  we determined whether or
13313            not Koenig lookup should be performed.  */
13314         koenig_p = KOENIG_LOOKUP_P (t);
13315         if (TREE_CODE (function) == SCOPE_REF)
13316           {
13317             qualified_p = true;
13318             function = tsubst_qualified_id (function, args, complain, in_decl,
13319                                             /*done=*/false,
13320                                             /*address_p=*/false);
13321           }
13322         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13323           {
13324             /* Do nothing; calling tsubst_copy_and_build on an identifier
13325                would incorrectly perform unqualified lookup again.
13326
13327                Note that we can also have an IDENTIFIER_NODE if the earlier
13328                unqualified lookup found a member function; in that case
13329                koenig_p will be false and we do want to do the lookup
13330                again to find the instantiated member function.
13331
13332                FIXME but doing that causes c++/15272, so we need to stop
13333                using IDENTIFIER_NODE in that situation.  */
13334             qualified_p = false;
13335           }
13336         else
13337           {
13338             if (TREE_CODE (function) == COMPONENT_REF)
13339               {
13340                 tree op = TREE_OPERAND (function, 1);
13341
13342                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13343                                || (BASELINK_P (op)
13344                                    && BASELINK_QUALIFIED_P (op)));
13345               }
13346             else
13347               qualified_p = false;
13348
13349             function = tsubst_copy_and_build (function, args, complain,
13350                                               in_decl,
13351                                               !qualified_p,
13352                                               integral_constant_expression_p);
13353
13354             if (BASELINK_P (function))
13355               qualified_p = true;
13356           }
13357
13358         nargs = call_expr_nargs (t);
13359         call_args = make_tree_vector ();
13360         for (i = 0; i < nargs; ++i)
13361           {
13362             tree arg = CALL_EXPR_ARG (t, i);
13363
13364             if (!PACK_EXPANSION_P (arg))
13365               VEC_safe_push (tree, gc, call_args,
13366                              RECUR (CALL_EXPR_ARG (t, i)));
13367             else
13368               {
13369                 /* Expand the pack expansion and push each entry onto
13370                    CALL_ARGS.  */
13371                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13372                 if (TREE_CODE (arg) == TREE_VEC)
13373                   {
13374                     unsigned int len, j;
13375
13376                     len = TREE_VEC_LENGTH (arg);
13377                     for (j = 0; j < len; ++j)
13378                       {
13379                         tree value = TREE_VEC_ELT (arg, j);
13380                         if (value != NULL_TREE)
13381                           value = convert_from_reference (value);
13382                         VEC_safe_push (tree, gc, call_args, value);
13383                       }
13384                   }
13385                 else
13386                   {
13387                     /* A partial substitution.  Add one entry.  */
13388                     VEC_safe_push (tree, gc, call_args, arg);
13389                   }
13390               }
13391           }
13392
13393         /* We do not perform argument-dependent lookup if normal
13394            lookup finds a non-function, in accordance with the
13395            expected resolution of DR 218.  */
13396         if (koenig_p
13397             && ((is_overloaded_fn (function)
13398                  /* If lookup found a member function, the Koenig lookup is
13399                     not appropriate, even if an unqualified-name was used
13400                     to denote the function.  */
13401                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13402                 || TREE_CODE (function) == IDENTIFIER_NODE)
13403             /* Only do this when substitution turns a dependent call
13404                into a non-dependent call.  */
13405             && type_dependent_expression_p_push (t)
13406             && !any_type_dependent_arguments_p (call_args))
13407           function = perform_koenig_lookup (function, call_args, false,
13408                                             tf_none);
13409
13410         if (TREE_CODE (function) == IDENTIFIER_NODE
13411             && !any_type_dependent_arguments_p (call_args))
13412           {
13413             if (koenig_p && (complain & tf_warning_or_error))
13414               {
13415                 /* For backwards compatibility and good diagnostics, try
13416                    the unqualified lookup again if we aren't in SFINAE
13417                    context.  */
13418                 tree unq = (tsubst_copy_and_build
13419                             (function, args, complain, in_decl, true,
13420                              integral_constant_expression_p));
13421                 if (unq != function)
13422                   {
13423                     tree fn = unq;
13424                     if (TREE_CODE (fn) == COMPONENT_REF)
13425                       fn = TREE_OPERAND (fn, 1);
13426                     if (is_overloaded_fn (fn))
13427                       fn = get_first_fn (fn);
13428                     permerror (EXPR_LOC_OR_HERE (t),
13429                                "%qD was not declared in this scope, "
13430                                "and no declarations were found by "
13431                                "argument-dependent lookup at the point "
13432                                "of instantiation", function);
13433                     if (DECL_CLASS_SCOPE_P (fn))
13434                       {
13435                         inform (EXPR_LOC_OR_HERE (t),
13436                                 "declarations in dependent base %qT are "
13437                                 "not found by unqualified lookup",
13438                                 DECL_CLASS_CONTEXT (fn));
13439                         if (current_class_ptr)
13440                           inform (EXPR_LOC_OR_HERE (t),
13441                                   "use %<this->%D%> instead", function);
13442                         else
13443                           inform (EXPR_LOC_OR_HERE (t),
13444                                   "use %<%T::%D%> instead",
13445                                   current_class_name, function);
13446                       }
13447                     else
13448                       inform (0, "%q+D declared here, later in the "
13449                                 "translation unit", fn);
13450                     function = unq;
13451                   }
13452               }
13453             if (TREE_CODE (function) == IDENTIFIER_NODE)
13454               {
13455                 unqualified_name_lookup_error (function);
13456                 release_tree_vector (call_args);
13457                 return error_mark_node;
13458               }
13459           }
13460
13461         /* Remember that there was a reference to this entity.  */
13462         if (DECL_P (function))
13463           mark_used (function);
13464
13465         if (TREE_CODE (function) == OFFSET_REF)
13466           ret = build_offset_ref_call_from_tree (function, &call_args);
13467         else if (TREE_CODE (function) == COMPONENT_REF)
13468           {
13469             tree instance = TREE_OPERAND (function, 0);
13470             tree fn = TREE_OPERAND (function, 1);
13471
13472             if (processing_template_decl
13473                 && (type_dependent_expression_p (instance)
13474                     || (!BASELINK_P (fn)
13475                         && TREE_CODE (fn) != FIELD_DECL)
13476                     || type_dependent_expression_p (fn)
13477                     || any_type_dependent_arguments_p (call_args)))
13478               ret = build_nt_call_vec (function, call_args);
13479             else if (!BASELINK_P (fn))
13480               ret = finish_call_expr (function, &call_args,
13481                                        /*disallow_virtual=*/false,
13482                                        /*koenig_p=*/false,
13483                                        complain);
13484             else
13485               ret = (build_new_method_call
13486                       (instance, fn,
13487                        &call_args, NULL_TREE,
13488                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13489                        /*fn_p=*/NULL,
13490                        complain));
13491           }
13492         else
13493           ret = finish_call_expr (function, &call_args,
13494                                   /*disallow_virtual=*/qualified_p,
13495                                   koenig_p,
13496                                   complain);
13497
13498         release_tree_vector (call_args);
13499
13500         return ret;
13501       }
13502
13503     case COND_EXPR:
13504       return build_x_conditional_expr
13505         (RECUR (TREE_OPERAND (t, 0)),
13506          RECUR (TREE_OPERAND (t, 1)),
13507          RECUR (TREE_OPERAND (t, 2)),
13508          complain);
13509
13510     case PSEUDO_DTOR_EXPR:
13511       return finish_pseudo_destructor_expr
13512         (RECUR (TREE_OPERAND (t, 0)),
13513          RECUR (TREE_OPERAND (t, 1)),
13514          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13515
13516     case TREE_LIST:
13517       {
13518         tree purpose, value, chain;
13519
13520         if (t == void_list_node)
13521           return t;
13522
13523         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13524             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13525           {
13526             /* We have pack expansions, so expand those and
13527                create a new list out of it.  */
13528             tree purposevec = NULL_TREE;
13529             tree valuevec = NULL_TREE;
13530             tree chain;
13531             int i, len = -1;
13532
13533             /* Expand the argument expressions.  */
13534             if (TREE_PURPOSE (t))
13535               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13536                                                  complain, in_decl);
13537             if (TREE_VALUE (t))
13538               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13539                                                complain, in_decl);
13540
13541             /* Build the rest of the list.  */
13542             chain = TREE_CHAIN (t);
13543             if (chain && chain != void_type_node)
13544               chain = RECUR (chain);
13545
13546             /* Determine the number of arguments.  */
13547             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13548               {
13549                 len = TREE_VEC_LENGTH (purposevec);
13550                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13551               }
13552             else if (TREE_CODE (valuevec) == TREE_VEC)
13553               len = TREE_VEC_LENGTH (valuevec);
13554             else
13555               {
13556                 /* Since we only performed a partial substitution into
13557                    the argument pack, we only return a single list
13558                    node.  */
13559                 if (purposevec == TREE_PURPOSE (t)
13560                     && valuevec == TREE_VALUE (t)
13561                     && chain == TREE_CHAIN (t))
13562                   return t;
13563
13564                 return tree_cons (purposevec, valuevec, chain);
13565               }
13566             
13567             /* Convert the argument vectors into a TREE_LIST */
13568             i = len;
13569             while (i > 0)
13570               {
13571                 /* Grab the Ith values.  */
13572                 i--;
13573                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13574                                      : NULL_TREE;
13575                 value 
13576                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13577                              : NULL_TREE;
13578
13579                 /* Build the list (backwards).  */
13580                 chain = tree_cons (purpose, value, chain);
13581               }
13582
13583             return chain;
13584           }
13585
13586         purpose = TREE_PURPOSE (t);
13587         if (purpose)
13588           purpose = RECUR (purpose);
13589         value = TREE_VALUE (t);
13590         if (value)
13591           value = RECUR (value);
13592         chain = TREE_CHAIN (t);
13593         if (chain && chain != void_type_node)
13594           chain = RECUR (chain);
13595         if (purpose == TREE_PURPOSE (t)
13596             && value == TREE_VALUE (t)
13597             && chain == TREE_CHAIN (t))
13598           return t;
13599         return tree_cons (purpose, value, chain);
13600       }
13601
13602     case COMPONENT_REF:
13603       {
13604         tree object;
13605         tree object_type;
13606         tree member;
13607
13608         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13609                                                      args, complain, in_decl);
13610         /* Remember that there was a reference to this entity.  */
13611         if (DECL_P (object))
13612           mark_used (object);
13613         object_type = TREE_TYPE (object);
13614
13615         member = TREE_OPERAND (t, 1);
13616         if (BASELINK_P (member))
13617           member = tsubst_baselink (member,
13618                                     non_reference (TREE_TYPE (object)),
13619                                     args, complain, in_decl);
13620         else
13621           member = tsubst_copy (member, args, complain, in_decl);
13622         if (member == error_mark_node)
13623           return error_mark_node;
13624
13625         if (object_type && !CLASS_TYPE_P (object_type))
13626           {
13627             if (SCALAR_TYPE_P (object_type))
13628               {
13629                 tree s = NULL_TREE;
13630                 tree dtor = member;
13631
13632                 if (TREE_CODE (dtor) == SCOPE_REF)
13633                   {
13634                     s = TREE_OPERAND (dtor, 0);
13635                     dtor = TREE_OPERAND (dtor, 1);
13636                   }
13637                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13638                   {
13639                     dtor = TREE_OPERAND (dtor, 0);
13640                     if (TYPE_P (dtor))
13641                       return finish_pseudo_destructor_expr (object, s, dtor);
13642                   }
13643               }
13644           }
13645         else if (TREE_CODE (member) == SCOPE_REF
13646                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13647           {
13648             tree tmpl;
13649             tree args;
13650
13651             /* Lookup the template functions now that we know what the
13652                scope is.  */
13653             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13654             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13655             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13656                                             /*is_type_p=*/false,
13657                                             /*complain=*/false);
13658             if (BASELINK_P (member))
13659               {
13660                 BASELINK_FUNCTIONS (member)
13661                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13662                               args);
13663                 member = (adjust_result_of_qualified_name_lookup
13664                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13665                            object_type));
13666               }
13667             else
13668               {
13669                 qualified_name_lookup_error (object_type, tmpl, member,
13670                                              input_location);
13671                 return error_mark_node;
13672               }
13673           }
13674         else if (TREE_CODE (member) == SCOPE_REF
13675                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13676                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13677           {
13678             if (complain & tf_error)
13679               {
13680                 if (TYPE_P (TREE_OPERAND (member, 0)))
13681                   error ("%qT is not a class or namespace",
13682                          TREE_OPERAND (member, 0));
13683                 else
13684                   error ("%qD is not a class or namespace",
13685                          TREE_OPERAND (member, 0));
13686               }
13687             return error_mark_node;
13688           }
13689         else if (TREE_CODE (member) == FIELD_DECL)
13690           return finish_non_static_data_member (member, object, NULL_TREE);
13691
13692         return finish_class_member_access_expr (object, member,
13693                                                 /*template_p=*/false,
13694                                                 complain);
13695       }
13696
13697     case THROW_EXPR:
13698       return build_throw
13699         (RECUR (TREE_OPERAND (t, 0)));
13700
13701     case CONSTRUCTOR:
13702       {
13703         VEC(constructor_elt,gc) *n;
13704         constructor_elt *ce;
13705         unsigned HOST_WIDE_INT idx;
13706         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13707         bool process_index_p;
13708         int newlen;
13709         bool need_copy_p = false;
13710         tree r;
13711
13712         if (type == error_mark_node)
13713           return error_mark_node;
13714
13715         /* digest_init will do the wrong thing if we let it.  */
13716         if (type && TYPE_PTRMEMFUNC_P (type))
13717           return t;
13718
13719         /* We do not want to process the index of aggregate
13720            initializers as they are identifier nodes which will be
13721            looked up by digest_init.  */
13722         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13723
13724         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13725         newlen = VEC_length (constructor_elt, n);
13726         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13727           {
13728             if (ce->index && process_index_p)
13729               ce->index = RECUR (ce->index);
13730
13731             if (PACK_EXPANSION_P (ce->value))
13732               {
13733                 /* Substitute into the pack expansion.  */
13734                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13735                                                   in_decl);
13736
13737                 if (ce->value == error_mark_node
13738                     || PACK_EXPANSION_P (ce->value))
13739                   ;
13740                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13741                   /* Just move the argument into place.  */
13742                   ce->value = TREE_VEC_ELT (ce->value, 0);
13743                 else
13744                   {
13745                     /* Update the length of the final CONSTRUCTOR
13746                        arguments vector, and note that we will need to
13747                        copy.*/
13748                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13749                     need_copy_p = true;
13750                   }
13751               }
13752             else
13753               ce->value = RECUR (ce->value);
13754           }
13755
13756         if (need_copy_p)
13757           {
13758             VEC(constructor_elt,gc) *old_n = n;
13759
13760             n = VEC_alloc (constructor_elt, gc, newlen);
13761             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13762               {
13763                 if (TREE_CODE (ce->value) == TREE_VEC)
13764                   {
13765                     int i, len = TREE_VEC_LENGTH (ce->value);
13766                     for (i = 0; i < len; ++i)
13767                       CONSTRUCTOR_APPEND_ELT (n, 0,
13768                                               TREE_VEC_ELT (ce->value, i));
13769                   }
13770                 else
13771                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13772               }
13773           }
13774
13775         r = build_constructor (init_list_type_node, n);
13776         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13777
13778         if (TREE_HAS_CONSTRUCTOR (t))
13779           return finish_compound_literal (type, r, complain);
13780
13781         TREE_TYPE (r) = type;
13782         return r;
13783       }
13784
13785     case TYPEID_EXPR:
13786       {
13787         tree operand_0 = TREE_OPERAND (t, 0);
13788         if (TYPE_P (operand_0))
13789           {
13790             operand_0 = tsubst (operand_0, args, complain, in_decl);
13791             return get_typeid (operand_0);
13792           }
13793         else
13794           {
13795             operand_0 = RECUR (operand_0);
13796             return build_typeid (operand_0);
13797           }
13798       }
13799
13800     case VAR_DECL:
13801       if (!args)
13802         return t;
13803       /* Fall through */
13804
13805     case PARM_DECL:
13806       {
13807         tree r = tsubst_copy (t, args, complain, in_decl);
13808
13809         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13810           /* If the original type was a reference, we'll be wrapped in
13811              the appropriate INDIRECT_REF.  */
13812           r = convert_from_reference (r);
13813         return r;
13814       }
13815
13816     case VA_ARG_EXPR:
13817       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13818                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13819
13820     case OFFSETOF_EXPR:
13821       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13822
13823     case TRAIT_EXPR:
13824       {
13825         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13826                                   complain, in_decl);
13827
13828         tree type2 = TRAIT_EXPR_TYPE2 (t);
13829         if (type2)
13830           type2 = tsubst_copy (type2, args, complain, in_decl);
13831         
13832         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13833       }
13834
13835     case STMT_EXPR:
13836       {
13837         tree old_stmt_expr = cur_stmt_expr;
13838         tree stmt_expr = begin_stmt_expr ();
13839
13840         cur_stmt_expr = stmt_expr;
13841         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13842                      integral_constant_expression_p);
13843         stmt_expr = finish_stmt_expr (stmt_expr, false);
13844         cur_stmt_expr = old_stmt_expr;
13845
13846         /* If the resulting list of expression statement is empty,
13847            fold it further into void_zero_node.  */
13848         if (empty_expr_stmt_p (stmt_expr))
13849           stmt_expr = void_zero_node;
13850
13851         return stmt_expr;
13852       }
13853
13854     case CONST_DECL:
13855       t = tsubst_copy (t, args, complain, in_decl);
13856       /* As in finish_id_expression, we resolve enumeration constants
13857          to their underlying values.  */
13858       if (TREE_CODE (t) == CONST_DECL)
13859         {
13860           used_types_insert (TREE_TYPE (t));
13861           return DECL_INITIAL (t);
13862         }
13863       return t;
13864
13865     case LAMBDA_EXPR:
13866       {
13867         tree r = build_lambda_expr ();
13868
13869         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13870         TREE_TYPE (r) = type;
13871         CLASSTYPE_LAMBDA_EXPR (type) = r;
13872
13873         LAMBDA_EXPR_LOCATION (r)
13874           = LAMBDA_EXPR_LOCATION (t);
13875         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13876           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13877         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13878         LAMBDA_EXPR_DISCRIMINATOR (r)
13879           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13880         LAMBDA_EXPR_CAPTURE_LIST (r)
13881           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13882         LAMBDA_EXPR_EXTRA_SCOPE (r)
13883           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13884         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13885                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13886
13887         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13888         determine_visibility (TYPE_NAME (type));
13889         /* Now that we know visibility, instantiate the type so we have a
13890            declaration of the op() for later calls to lambda_function.  */
13891         complete_type (type);
13892
13893         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13894         if (type)
13895           apply_lambda_return_type (r, type);
13896
13897         return build_lambda_object (r);
13898       }
13899
13900     case TARGET_EXPR:
13901       /* We can get here for a constant initializer of non-dependent type.
13902          FIXME stop folding in cp_parser_initializer_clause.  */
13903       gcc_assert (TREE_CONSTANT (t));
13904       {
13905         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13906         TREE_CONSTANT (r) = true;
13907         return r;
13908       }
13909
13910     default:
13911       /* Handle Objective-C++ constructs, if appropriate.  */
13912       {
13913         tree subst
13914           = objcp_tsubst_copy_and_build (t, args, complain,
13915                                          in_decl, /*function_p=*/false);
13916         if (subst)
13917           return subst;
13918       }
13919       return tsubst_copy (t, args, complain, in_decl);
13920     }
13921
13922 #undef RECUR
13923 }
13924
13925 /* Verify that the instantiated ARGS are valid. For type arguments,
13926    make sure that the type's linkage is ok. For non-type arguments,
13927    make sure they are constants if they are integral or enumerations.
13928    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13929
13930 static bool
13931 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13932 {
13933   if (ARGUMENT_PACK_P (t))
13934     {
13935       tree vec = ARGUMENT_PACK_ARGS (t);
13936       int len = TREE_VEC_LENGTH (vec);
13937       bool result = false;
13938       int i;
13939
13940       for (i = 0; i < len; ++i)
13941         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13942           result = true;
13943       return result;
13944     }
13945   else if (TYPE_P (t))
13946     {
13947       /* [basic.link]: A name with no linkage (notably, the name
13948          of a class or enumeration declared in a local scope)
13949          shall not be used to declare an entity with linkage.
13950          This implies that names with no linkage cannot be used as
13951          template arguments
13952
13953          DR 757 relaxes this restriction for C++0x.  */
13954       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13955                  : no_linkage_check (t, /*relaxed_p=*/false));
13956
13957       if (nt)
13958         {
13959           /* DR 488 makes use of a type with no linkage cause
13960              type deduction to fail.  */
13961           if (complain & tf_error)
13962             {
13963               if (TYPE_ANONYMOUS_P (nt))
13964                 error ("%qT is/uses anonymous type", t);
13965               else
13966                 error ("template argument for %qD uses local type %qT",
13967                        tmpl, t);
13968             }
13969           return true;
13970         }
13971       /* In order to avoid all sorts of complications, we do not
13972          allow variably-modified types as template arguments.  */
13973       else if (variably_modified_type_p (t, NULL_TREE))
13974         {
13975           if (complain & tf_error)
13976             error ("%qT is a variably modified type", t);
13977           return true;
13978         }
13979     }
13980   /* A non-type argument of integral or enumerated type must be a
13981      constant.  */
13982   else if (TREE_TYPE (t)
13983            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13984            && !TREE_CONSTANT (t))
13985     {
13986       if (complain & tf_error)
13987         error ("integral expression %qE is not constant", t);
13988       return true;
13989     }
13990   return false;
13991 }
13992
13993 static bool
13994 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13995 {
13996   int ix, len = DECL_NTPARMS (tmpl);
13997   bool result = false;
13998
13999   for (ix = 0; ix != len; ix++)
14000     {
14001       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14002         result = true;
14003     }
14004   if (result && (complain & tf_error))
14005     error ("  trying to instantiate %qD", tmpl);
14006   return result;
14007 }
14008
14009 /* In C++0x, it's possible to have a function template whose type depends
14010    on itself recursively.  This is most obvious with decltype, but can also
14011    occur with enumeration scope (c++/48969).  So we need to catch infinite
14012    recursion and reject the substitution at deduction time; this function
14013    will return error_mark_node for any repeated substitution.
14014
14015    This also catches excessive recursion such as when f<N> depends on
14016    f<N-1> across all integers, and returns error_mark_node for all the
14017    substitutions back up to the initial one.
14018
14019    This is, of course, not reentrant.  */
14020
14021 static tree
14022 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14023 {
14024   static bool excessive_deduction_depth;
14025   static int deduction_depth;
14026   struct pending_template *old_last_pend = last_pending_template;
14027   struct tinst_level *old_error_tinst = last_error_tinst_level;
14028
14029   tree fntype = TREE_TYPE (fn);
14030   tree tinst;
14031   tree r;
14032
14033   if (excessive_deduction_depth)
14034     return error_mark_node;
14035
14036   tinst = build_tree_list (fn, targs);
14037   if (!push_tinst_level (tinst))
14038     {
14039       excessive_deduction_depth = true;
14040       ggc_free (tinst);
14041       return error_mark_node;
14042     }
14043
14044   input_location = DECL_SOURCE_LOCATION (fn);
14045   ++deduction_depth;
14046   push_deduction_access_scope (fn);
14047   r = tsubst (fntype, targs, complain, NULL_TREE);
14048   pop_deduction_access_scope (fn);
14049   --deduction_depth;
14050
14051   if (excessive_deduction_depth)
14052     {
14053       r = error_mark_node;
14054       if (deduction_depth == 0)
14055         /* Reset once we're all the way out.  */
14056         excessive_deduction_depth = false;
14057     }
14058
14059   pop_tinst_level ();
14060   /* We can't free this if a pending_template entry or last_error_tinst_level
14061      is pointing at it.  */
14062   if (last_pending_template == old_last_pend
14063       && last_error_tinst_level == old_error_tinst)
14064     ggc_free (tinst);
14065   return r;
14066 }
14067
14068 /* Instantiate the indicated variable or function template TMPL with
14069    the template arguments in TARG_PTR.  */
14070
14071 static tree
14072 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14073 {
14074   tree targ_ptr = orig_args;
14075   tree fndecl;
14076   tree gen_tmpl;
14077   tree spec;
14078   HOST_WIDE_INT saved_processing_template_decl;
14079
14080   if (tmpl == error_mark_node)
14081     return error_mark_node;
14082
14083   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14084
14085   /* If this function is a clone, handle it specially.  */
14086   if (DECL_CLONED_FUNCTION_P (tmpl))
14087     {
14088       tree spec;
14089       tree clone;
14090
14091       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14092          DECL_CLONED_FUNCTION.  */
14093       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14094                                    targ_ptr, complain);
14095       if (spec == error_mark_node)
14096         return error_mark_node;
14097
14098       /* Look for the clone.  */
14099       FOR_EACH_CLONE (clone, spec)
14100         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14101           return clone;
14102       /* We should always have found the clone by now.  */
14103       gcc_unreachable ();
14104       return NULL_TREE;
14105     }
14106
14107   /* Check to see if we already have this specialization.  */
14108   gen_tmpl = most_general_template (tmpl);
14109   if (tmpl != gen_tmpl)
14110     /* The TMPL is a partial instantiation.  To get a full set of
14111        arguments we must add the arguments used to perform the
14112        partial instantiation.  */
14113     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14114                                             targ_ptr);
14115
14116   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14117      but it doesn't seem to be on the hot path.  */
14118   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14119
14120   gcc_assert (tmpl == gen_tmpl
14121               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14122                   == spec)
14123               || fndecl == NULL_TREE);
14124
14125   if (spec != NULL_TREE)
14126     return spec;
14127
14128   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14129                                complain))
14130     return error_mark_node;
14131
14132   /* We are building a FUNCTION_DECL, during which the access of its
14133      parameters and return types have to be checked.  However this
14134      FUNCTION_DECL which is the desired context for access checking
14135      is not built yet.  We solve this chicken-and-egg problem by
14136      deferring all checks until we have the FUNCTION_DECL.  */
14137   push_deferring_access_checks (dk_deferred);
14138
14139   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14140      (because, for example, we have encountered a non-dependent
14141      function call in the body of a template function and must now
14142      determine which of several overloaded functions will be called),
14143      within the instantiation itself we are not processing a
14144      template.  */  
14145   saved_processing_template_decl = processing_template_decl;
14146   processing_template_decl = 0;
14147   /* Substitute template parameters to obtain the specialization.  */
14148   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14149                    targ_ptr, complain, gen_tmpl);
14150   processing_template_decl = saved_processing_template_decl;
14151   if (fndecl == error_mark_node)
14152     return error_mark_node;
14153
14154   /* Now we know the specialization, compute access previously
14155      deferred.  */
14156   push_access_scope (fndecl);
14157
14158   /* Some typedefs referenced from within the template code need to be access
14159      checked at template instantiation time, i.e now. These types were
14160      added to the template at parsing time. Let's get those and perfom
14161      the acces checks then.  */
14162   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14163   perform_deferred_access_checks ();
14164   pop_access_scope (fndecl);
14165   pop_deferring_access_checks ();
14166
14167   /* The DECL_TI_TEMPLATE should always be the immediate parent
14168      template, not the most general template.  */
14169   DECL_TI_TEMPLATE (fndecl) = tmpl;
14170
14171   /* If we've just instantiated the main entry point for a function,
14172      instantiate all the alternate entry points as well.  We do this
14173      by cloning the instantiation of the main entry point, not by
14174      instantiating the template clones.  */
14175   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14176     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14177
14178   return fndecl;
14179 }
14180
14181 /* Wrapper for instantiate_template_1.  */
14182
14183 tree
14184 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14185 {
14186   tree ret;
14187   timevar_push (TV_TEMPLATE_INST);
14188   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14189   timevar_pop (TV_TEMPLATE_INST);
14190   return ret;
14191 }
14192
14193 /* We're going to do deduction substitution on the type of TMPL, a function
14194    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14195    disable access checking.  */
14196
14197 static void
14198 push_deduction_access_scope (tree tmpl)
14199 {
14200   if (cxx_dialect >= cxx0x)
14201     {
14202       int ptd = processing_template_decl;
14203       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14204       /* Preserve processing_template_decl across push_to_top_level.  */
14205       if (ptd && !processing_template_decl)
14206         ++processing_template_decl;
14207     }
14208   else
14209     push_deferring_access_checks (dk_no_check);
14210 }
14211
14212 /* And pop back out.  */
14213
14214 static void
14215 pop_deduction_access_scope (tree tmpl)
14216 {
14217   if (cxx_dialect >= cxx0x)
14218     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14219   else
14220     pop_deferring_access_checks ();
14221 }
14222
14223 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14224    NARGS elements of the arguments that are being used when calling
14225    it.  TARGS is a vector into which the deduced template arguments
14226    are placed.
14227
14228    Return zero for success, 2 for an incomplete match that doesn't resolve
14229    all the types, and 1 for complete failure.  An error message will be
14230    printed only for an incomplete match.
14231
14232    If FN is a conversion operator, or we are trying to produce a specific
14233    specialization, RETURN_TYPE is the return type desired.
14234
14235    The EXPLICIT_TARGS are explicit template arguments provided via a
14236    template-id.
14237
14238    The parameter STRICT is one of:
14239
14240    DEDUCE_CALL:
14241      We are deducing arguments for a function call, as in
14242      [temp.deduct.call].
14243
14244    DEDUCE_CONV:
14245      We are deducing arguments for a conversion function, as in
14246      [temp.deduct.conv].
14247
14248    DEDUCE_EXACT:
14249      We are deducing arguments when doing an explicit instantiation
14250      as in [temp.explicit], when determining an explicit specialization
14251      as in [temp.expl.spec], or when taking the address of a function
14252      template, as in [temp.deduct.funcaddr].  */
14253
14254 int
14255 fn_type_unification (tree fn,
14256                      tree explicit_targs,
14257                      tree targs,
14258                      const tree *args,
14259                      unsigned int nargs,
14260                      tree return_type,
14261                      unification_kind_t strict,
14262                      int flags,
14263                      bool explain_p)
14264 {
14265   tree parms;
14266   tree fntype;
14267   int result;
14268   bool incomplete_argument_packs_p = false;
14269
14270   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14271
14272   fntype = TREE_TYPE (fn);
14273   if (explicit_targs)
14274     {
14275       /* [temp.deduct]
14276
14277          The specified template arguments must match the template
14278          parameters in kind (i.e., type, nontype, template), and there
14279          must not be more arguments than there are parameters;
14280          otherwise type deduction fails.
14281
14282          Nontype arguments must match the types of the corresponding
14283          nontype template parameters, or must be convertible to the
14284          types of the corresponding nontype parameters as specified in
14285          _temp.arg.nontype_, otherwise type deduction fails.
14286
14287          All references in the function type of the function template
14288          to the corresponding template parameters are replaced by the
14289          specified template argument values.  If a substitution in a
14290          template parameter or in the function type of the function
14291          template results in an invalid type, type deduction fails.  */
14292       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14293       int i, len = TREE_VEC_LENGTH (tparms);
14294       tree converted_args;
14295       bool incomplete = false;
14296
14297       if (explicit_targs == error_mark_node)
14298         return unify_invalid (explain_p);
14299
14300       converted_args
14301         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14302                                   (explain_p
14303                                    ? tf_warning_or_error
14304                                    : tf_none),
14305                                    /*require_all_args=*/false,
14306                                    /*use_default_args=*/false));
14307       if (converted_args == error_mark_node)
14308         return 1;
14309
14310       /* Substitute the explicit args into the function type.  This is
14311          necessary so that, for instance, explicitly declared function
14312          arguments can match null pointed constants.  If we were given
14313          an incomplete set of explicit args, we must not do semantic
14314          processing during substitution as we could create partial
14315          instantiations.  */
14316       for (i = 0; i < len; i++)
14317         {
14318           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14319           bool parameter_pack = false;
14320
14321           /* Dig out the actual parm.  */
14322           if (TREE_CODE (parm) == TYPE_DECL
14323               || TREE_CODE (parm) == TEMPLATE_DECL)
14324             {
14325               parm = TREE_TYPE (parm);
14326               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14327             }
14328           else if (TREE_CODE (parm) == PARM_DECL)
14329             {
14330               parm = DECL_INITIAL (parm);
14331               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14332             }
14333
14334           if (parameter_pack)
14335             {
14336               int level, idx;
14337               tree targ;
14338               template_parm_level_and_index (parm, &level, &idx);
14339
14340               /* Mark the argument pack as "incomplete". We could
14341                  still deduce more arguments during unification.
14342                  We remove this mark in type_unification_real.  */
14343               targ = TMPL_ARG (converted_args, level, idx);
14344               if (targ)
14345                 {
14346                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14347                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14348                     = ARGUMENT_PACK_ARGS (targ);
14349                 }
14350
14351               /* We have some incomplete argument packs.  */
14352               incomplete_argument_packs_p = true;
14353             }
14354         }
14355
14356       if (incomplete_argument_packs_p)
14357         /* Any substitution is guaranteed to be incomplete if there
14358            are incomplete argument packs, because we can still deduce
14359            more arguments.  */
14360         incomplete = 1;
14361       else
14362         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
14363
14364       processing_template_decl += incomplete;
14365       fntype = deduction_tsubst_fntype (fn, converted_args,
14366                                         (explain_p
14367                                          ? tf_warning_or_error
14368                                          : tf_none));
14369       processing_template_decl -= incomplete;
14370
14371       if (fntype == error_mark_node)
14372         return 1;
14373
14374       /* Place the explicitly specified arguments in TARGS.  */
14375       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14376         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14377     }
14378
14379   /* Never do unification on the 'this' parameter.  */
14380   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14381
14382   if (return_type)
14383     {
14384       tree *new_args;
14385
14386       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14387       new_args = XALLOCAVEC (tree, nargs + 1);
14388       new_args[0] = return_type;
14389       memcpy (new_args + 1, args, nargs * sizeof (tree));
14390       args = new_args;
14391       ++nargs;
14392     }
14393
14394   /* We allow incomplete unification without an error message here
14395      because the standard doesn't seem to explicitly prohibit it.  Our
14396      callers must be ready to deal with unification failures in any
14397      event.  */
14398   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14399                                   targs, parms, args, nargs, /*subr=*/0,
14400                                   strict, flags, explain_p);
14401
14402   /* Now that we have bindings for all of the template arguments,
14403      ensure that the arguments deduced for the template template
14404      parameters have compatible template parameter lists.  We cannot
14405      check this property before we have deduced all template
14406      arguments, because the template parameter types of a template
14407      template parameter might depend on prior template parameters
14408      deduced after the template template parameter.  The following
14409      ill-formed example illustrates this issue:
14410
14411        template<typename T, template<T> class C> void f(C<5>, T);
14412
14413        template<int N> struct X {};
14414
14415        void g() {
14416          f(X<5>(), 5l); // error: template argument deduction fails
14417        }
14418
14419      The template parameter list of 'C' depends on the template type
14420      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14421      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14422      time that we deduce 'C'.  */
14423   if (result == 0
14424       && !template_template_parm_bindings_ok_p 
14425            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14426     return unify_inconsistent_template_template_parameters (explain_p);
14427
14428   if (result == 0)
14429     /* All is well so far.  Now, check:
14430
14431        [temp.deduct]
14432
14433        When all template arguments have been deduced, all uses of
14434        template parameters in nondeduced contexts are replaced with
14435        the corresponding deduced argument values.  If the
14436        substitution results in an invalid type, as described above,
14437        type deduction fails.  */
14438     {
14439       tree substed = deduction_tsubst_fntype (fn, targs,
14440                                               (explain_p
14441                                                ? tf_warning_or_error
14442                                                : tf_none));
14443       if (substed == error_mark_node)
14444         return 1;
14445
14446       /* If we're looking for an exact match, check that what we got
14447          is indeed an exact match.  It might not be if some template
14448          parameters are used in non-deduced contexts.  */
14449       if (strict == DEDUCE_EXACT)
14450         {
14451           unsigned int i;
14452
14453           tree sarg
14454             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14455           if (return_type)
14456             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14457           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14458             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14459               return unify_type_mismatch (explain_p, args[i],
14460                                           TREE_VALUE (sarg));
14461         }
14462     }
14463
14464   return result;
14465 }
14466
14467 /* Adjust types before performing type deduction, as described in
14468    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14469    sections are symmetric.  PARM is the type of a function parameter
14470    or the return type of the conversion function.  ARG is the type of
14471    the argument passed to the call, or the type of the value
14472    initialized with the result of the conversion function.
14473    ARG_EXPR is the original argument expression, which may be null.  */
14474
14475 static int
14476 maybe_adjust_types_for_deduction (unification_kind_t strict,
14477                                   tree* parm,
14478                                   tree* arg,
14479                                   tree arg_expr)
14480 {
14481   int result = 0;
14482
14483   switch (strict)
14484     {
14485     case DEDUCE_CALL:
14486       break;
14487
14488     case DEDUCE_CONV:
14489       {
14490         /* Swap PARM and ARG throughout the remainder of this
14491            function; the handling is precisely symmetric since PARM
14492            will initialize ARG rather than vice versa.  */
14493         tree* temp = parm;
14494         parm = arg;
14495         arg = temp;
14496         break;
14497       }
14498
14499     case DEDUCE_EXACT:
14500       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14501          too, but here handle it by stripping the reference from PARM
14502          rather than by adding it to ARG.  */
14503       if (TREE_CODE (*parm) == REFERENCE_TYPE
14504           && TYPE_REF_IS_RVALUE (*parm)
14505           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14506           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14507           && TREE_CODE (*arg) == REFERENCE_TYPE
14508           && !TYPE_REF_IS_RVALUE (*arg))
14509         *parm = TREE_TYPE (*parm);
14510       /* Nothing else to do in this case.  */
14511       return 0;
14512
14513     default:
14514       gcc_unreachable ();
14515     }
14516
14517   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14518     {
14519       /* [temp.deduct.call]
14520
14521          If P is not a reference type:
14522
14523          --If A is an array type, the pointer type produced by the
14524          array-to-pointer standard conversion (_conv.array_) is
14525          used in place of A for type deduction; otherwise,
14526
14527          --If A is a function type, the pointer type produced by
14528          the function-to-pointer standard conversion
14529          (_conv.func_) is used in place of A for type deduction;
14530          otherwise,
14531
14532          --If A is a cv-qualified type, the top level
14533          cv-qualifiers of A's type are ignored for type
14534          deduction.  */
14535       if (TREE_CODE (*arg) == ARRAY_TYPE)
14536         *arg = build_pointer_type (TREE_TYPE (*arg));
14537       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14538         *arg = build_pointer_type (*arg);
14539       else
14540         *arg = TYPE_MAIN_VARIANT (*arg);
14541     }
14542
14543   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14544      of the form T&&, where T is a template parameter, and the argument
14545      is an lvalue, T is deduced as A& */
14546   if (TREE_CODE (*parm) == REFERENCE_TYPE
14547       && TYPE_REF_IS_RVALUE (*parm)
14548       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14549       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14550       && (arg_expr ? real_lvalue_p (arg_expr)
14551           /* try_one_overload doesn't provide an arg_expr, but
14552              functions are always lvalues.  */
14553           : TREE_CODE (*arg) == FUNCTION_TYPE))
14554     *arg = build_reference_type (*arg);
14555
14556   /* [temp.deduct.call]
14557
14558      If P is a cv-qualified type, the top level cv-qualifiers
14559      of P's type are ignored for type deduction.  If P is a
14560      reference type, the type referred to by P is used for
14561      type deduction.  */
14562   *parm = TYPE_MAIN_VARIANT (*parm);
14563   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14564     {
14565       *parm = TREE_TYPE (*parm);
14566       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14567     }
14568
14569   /* DR 322. For conversion deduction, remove a reference type on parm
14570      too (which has been swapped into ARG).  */
14571   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14572     *arg = TREE_TYPE (*arg);
14573
14574   return result;
14575 }
14576
14577 /* Most parms like fn_type_unification.
14578
14579    If SUBR is 1, we're being called recursively (to unify the
14580    arguments of a function or method parameter of a function
14581    template). */
14582
14583 static int
14584 type_unification_real (tree tparms,
14585                        tree targs,
14586                        tree xparms,
14587                        const tree *xargs,
14588                        unsigned int xnargs,
14589                        int subr,
14590                        unification_kind_t strict,
14591                        int flags,
14592                        bool explain_p)
14593 {
14594   tree parm, arg, arg_expr;
14595   int i;
14596   int ntparms = TREE_VEC_LENGTH (tparms);
14597   int sub_strict;
14598   int saw_undeduced = 0;
14599   tree parms;
14600   const tree *args;
14601   unsigned int nargs;
14602   unsigned int ia;
14603
14604   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14605   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14606   gcc_assert (ntparms > 0);
14607
14608   /* Reset the number of non-defaulted template arguments contained
14609      in TARGS.  */
14610   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14611
14612   switch (strict)
14613     {
14614     case DEDUCE_CALL:
14615       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14616                     | UNIFY_ALLOW_DERIVED);
14617       break;
14618
14619     case DEDUCE_CONV:
14620       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14621       break;
14622
14623     case DEDUCE_EXACT:
14624       sub_strict = UNIFY_ALLOW_NONE;
14625       break;
14626
14627     default:
14628       gcc_unreachable ();
14629     }
14630
14631  again:
14632   parms = xparms;
14633   args = xargs;
14634   nargs = xnargs;
14635
14636   ia = 0;
14637   while (parms && parms != void_list_node
14638          && ia < nargs)
14639     {
14640       parm = TREE_VALUE (parms);
14641
14642       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14643           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14644         /* For a function parameter pack that occurs at the end of the
14645            parameter-declaration-list, the type A of each remaining
14646            argument of the call is compared with the type P of the
14647            declarator-id of the function parameter pack.  */
14648         break;
14649
14650       parms = TREE_CHAIN (parms);
14651
14652       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14653         /* For a function parameter pack that does not occur at the
14654            end of the parameter-declaration-list, the type of the
14655            parameter pack is a non-deduced context.  */
14656         continue;
14657
14658       arg = args[ia];
14659       ++ia;
14660       arg_expr = NULL;
14661
14662       if (arg == error_mark_node)
14663         return unify_invalid (explain_p);
14664       if (arg == unknown_type_node)
14665         /* We can't deduce anything from this, but we might get all the
14666            template args from other function args.  */
14667         continue;
14668
14669       /* Conversions will be performed on a function argument that
14670          corresponds with a function parameter that contains only
14671          non-deducible template parameters and explicitly specified
14672          template parameters.  */
14673       if (!uses_template_parms (parm))
14674         {
14675           tree type;
14676
14677           if (!TYPE_P (arg))
14678             type = TREE_TYPE (arg);
14679           else
14680             type = arg;
14681
14682           if (same_type_p (parm, type))
14683             continue;
14684           if (strict != DEDUCE_EXACT
14685               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14686                                   flags))
14687             continue;
14688
14689           if (strict == DEDUCE_EXACT)
14690             return unify_type_mismatch (explain_p, parm, arg);
14691           else
14692             return unify_arg_conversion (explain_p, parm, type, arg);
14693         }
14694
14695       if (!TYPE_P (arg))
14696         {
14697           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14698           if (type_unknown_p (arg))
14699             {
14700               /* [temp.deduct.type] 
14701
14702                  A template-argument can be deduced from a pointer to
14703                  function or pointer to member function argument if
14704                  the set of overloaded functions does not contain
14705                  function templates and at most one of a set of
14706                  overloaded functions provides a unique match.  */
14707               if (resolve_overloaded_unification
14708                   (tparms, targs, parm, arg, strict, sub_strict, explain_p))
14709                 continue;
14710
14711               return unify_overload_resolution_failure (explain_p, arg);
14712             }
14713           arg_expr = arg;
14714           arg = unlowered_expr_type (arg);
14715           if (arg == error_mark_node)
14716             return unify_invalid (explain_p);
14717         }
14718
14719       {
14720         int arg_strict = sub_strict;
14721
14722         if (!subr)
14723           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14724                                                           arg_expr);
14725
14726         if (arg == init_list_type_node && arg_expr)
14727           arg = arg_expr;
14728         if (unify (tparms, targs, parm, arg, arg_strict, explain_p))
14729           /* If unification failed, the recursive call will have updated
14730              UI appropriately.  */
14731           return 1;
14732       }
14733     }
14734
14735
14736   if (parms 
14737       && parms != void_list_node
14738       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14739     {
14740       /* Unify the remaining arguments with the pack expansion type.  */
14741       tree argvec;
14742       tree parmvec = make_tree_vec (1);
14743
14744       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14745       argvec = make_tree_vec (nargs - ia);
14746       for (i = 0; ia < nargs; ++ia, ++i)
14747         TREE_VEC_ELT (argvec, i) = args[ia];
14748
14749       /* Copy the parameter into parmvec.  */
14750       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14751       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14752                                 /*call_args_p=*/true, /*subr=*/subr, explain_p))
14753         return 1;
14754
14755       /* Advance to the end of the list of parameters.  */
14756       parms = TREE_CHAIN (parms);
14757     }
14758
14759   /* Fail if we've reached the end of the parm list, and more args
14760      are present, and the parm list isn't variadic.  */
14761   if (ia < nargs && parms == void_list_node)
14762     return unify_too_many_arguments (explain_p, nargs, ia);
14763   /* Fail if parms are left and they don't have default values.  */
14764   if (parms && parms != void_list_node
14765       && TREE_PURPOSE (parms) == NULL_TREE)
14766     {
14767       unsigned int count = nargs;
14768       tree p = parms;
14769       while (p && p != void_list_node)
14770         {
14771           count++;
14772           p = TREE_CHAIN (p);
14773         }
14774       return unify_too_few_arguments (explain_p, ia, count);
14775     }
14776
14777   if (!subr)
14778     {
14779       /* Check to see if we need another pass before we start clearing
14780          ARGUMENT_PACK_INCOMPLETE_P.  */
14781       for (i = 0; i < ntparms; i++)
14782         {
14783           tree targ = TREE_VEC_ELT (targs, i);
14784           tree tparm = TREE_VEC_ELT (tparms, i);
14785
14786           if (targ || tparm == error_mark_node)
14787             continue;
14788           tparm = TREE_VALUE (tparm);
14789
14790           /* If this is an undeduced nontype parameter that depends on
14791              a type parameter, try another pass; its type may have been
14792              deduced from a later argument than the one from which
14793              this parameter can be deduced.  */
14794           if (TREE_CODE (tparm) == PARM_DECL
14795               && uses_template_parms (TREE_TYPE (tparm))
14796               && !saw_undeduced++)
14797             goto again;
14798         }
14799
14800       for (i = 0; i < ntparms; i++)
14801         {
14802           tree targ = TREE_VEC_ELT (targs, i);
14803           tree tparm = TREE_VEC_ELT (tparms, i);
14804
14805           /* Clear the "incomplete" flags on all argument packs now so that
14806              substituting them into later default arguments works.  */
14807           if (targ && ARGUMENT_PACK_P (targ))
14808             {
14809               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14810               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14811             }
14812
14813           if (targ || tparm == error_mark_node)
14814             continue;
14815           tparm = TREE_VALUE (tparm);
14816
14817           /* Core issue #226 (C++0x) [temp.deduct]:
14818
14819              If a template argument has not been deduced, its
14820              default template argument, if any, is used. 
14821
14822              When we are in C++98 mode, TREE_PURPOSE will either
14823              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14824              to explicitly check cxx_dialect here.  */
14825           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14826             {
14827               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14828               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14829               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14830               arg = convert_template_argument (parm, arg, targs,
14831                                                (explain_p
14832                                                 ? tf_warning_or_error
14833                                                 : tf_none),
14834                                                i, NULL_TREE);
14835               if (arg == error_mark_node)
14836                 return 1;
14837               else
14838                 {
14839                   TREE_VEC_ELT (targs, i) = arg;
14840                   /* The position of the first default template argument,
14841                      is also the number of non-defaulted arguments in TARGS.
14842                      Record that.  */
14843                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14844                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14845                   continue;
14846                 }
14847             }
14848
14849           /* If the type parameter is a parameter pack, then it will
14850              be deduced to an empty parameter pack.  */
14851           if (template_parameter_pack_p (tparm))
14852             {
14853               tree arg;
14854
14855               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14856                 {
14857                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14858                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14859                   TREE_CONSTANT (arg) = 1;
14860                 }
14861               else
14862                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14863
14864               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14865
14866               TREE_VEC_ELT (targs, i) = arg;
14867               continue;
14868             }
14869
14870           return unify_parameter_deduction_failure (explain_p, tparm);
14871         }
14872     }
14873 #ifdef ENABLE_CHECKING
14874   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14875     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14876 #endif
14877
14878   return unify_success (explain_p);
14879 }
14880
14881 /* Subroutine of type_unification_real.  Args are like the variables
14882    at the call site.  ARG is an overloaded function (or template-id);
14883    we try deducing template args from each of the overloads, and if
14884    only one succeeds, we go with that.  Modifies TARGS and returns
14885    true on success.  */
14886
14887 static bool
14888 resolve_overloaded_unification (tree tparms,
14889                                 tree targs,
14890                                 tree parm,
14891                                 tree arg,
14892                                 unification_kind_t strict,
14893                                 int sub_strict,
14894                                 bool explain_p)
14895 {
14896   tree tempargs = copy_node (targs);
14897   int good = 0;
14898   tree goodfn = NULL_TREE;
14899   bool addr_p;
14900
14901   if (TREE_CODE (arg) == ADDR_EXPR)
14902     {
14903       arg = TREE_OPERAND (arg, 0);
14904       addr_p = true;
14905     }
14906   else
14907     addr_p = false;
14908
14909   if (TREE_CODE (arg) == COMPONENT_REF)
14910     /* Handle `&x' where `x' is some static or non-static member
14911        function name.  */
14912     arg = TREE_OPERAND (arg, 1);
14913
14914   if (TREE_CODE (arg) == OFFSET_REF)
14915     arg = TREE_OPERAND (arg, 1);
14916
14917   /* Strip baselink information.  */
14918   if (BASELINK_P (arg))
14919     arg = BASELINK_FUNCTIONS (arg);
14920
14921   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14922     {
14923       /* If we got some explicit template args, we need to plug them into
14924          the affected templates before we try to unify, in case the
14925          explicit args will completely resolve the templates in question.  */
14926
14927       int ok = 0;
14928       tree expl_subargs = TREE_OPERAND (arg, 1);
14929       arg = TREE_OPERAND (arg, 0);
14930
14931       for (; arg; arg = OVL_NEXT (arg))
14932         {
14933           tree fn = OVL_CURRENT (arg);
14934           tree subargs, elem;
14935
14936           if (TREE_CODE (fn) != TEMPLATE_DECL)
14937             continue;
14938
14939           ++processing_template_decl;
14940           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14941                                   expl_subargs, /*check_ret=*/false);
14942           if (subargs && !any_dependent_template_arguments_p (subargs))
14943             {
14944               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14945               if (try_one_overload (tparms, targs, tempargs, parm,
14946                                     elem, strict, sub_strict, addr_p, explain_p)
14947                   && (!goodfn || !decls_match (goodfn, elem)))
14948                 {
14949                   goodfn = elem;
14950                   ++good;
14951                 }
14952             }
14953           else if (subargs)
14954             ++ok;
14955           --processing_template_decl;
14956         }
14957       /* If no templates (or more than one) are fully resolved by the
14958          explicit arguments, this template-id is a non-deduced context; it
14959          could still be OK if we deduce all template arguments for the
14960          enclosing call through other arguments.  */
14961       if (good != 1)
14962         good = ok;
14963     }
14964   else if (TREE_CODE (arg) != OVERLOAD
14965            && TREE_CODE (arg) != FUNCTION_DECL)
14966     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14967        -- but the deduction does not succeed because the expression is
14968        not just the function on its own.  */
14969     return false;
14970   else
14971     for (; arg; arg = OVL_NEXT (arg))
14972       if (try_one_overload (tparms, targs, tempargs, parm,
14973                             TREE_TYPE (OVL_CURRENT (arg)),
14974                             strict, sub_strict, addr_p, explain_p)
14975           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14976         {
14977           goodfn = OVL_CURRENT (arg);
14978           ++good;
14979         }
14980
14981   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14982      to function or pointer to member function argument if the set of
14983      overloaded functions does not contain function templates and at most
14984      one of a set of overloaded functions provides a unique match.
14985
14986      So if we found multiple possibilities, we return success but don't
14987      deduce anything.  */
14988
14989   if (good == 1)
14990     {
14991       int i = TREE_VEC_LENGTH (targs);
14992       for (; i--; )
14993         if (TREE_VEC_ELT (tempargs, i))
14994           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14995     }
14996   if (good)
14997     return true;
14998
14999   return false;
15000 }
15001
15002 /* Core DR 115: In contexts where deduction is done and fails, or in
15003    contexts where deduction is not done, if a template argument list is
15004    specified and it, along with any default template arguments, identifies
15005    a single function template specialization, then the template-id is an
15006    lvalue for the function template specialization.  */
15007
15008 tree
15009 resolve_nondeduced_context (tree orig_expr)
15010 {
15011   tree expr, offset, baselink;
15012   bool addr;
15013
15014   if (!type_unknown_p (orig_expr))
15015     return orig_expr;
15016
15017   expr = orig_expr;
15018   addr = false;
15019   offset = NULL_TREE;
15020   baselink = NULL_TREE;
15021
15022   if (TREE_CODE (expr) == ADDR_EXPR)
15023     {
15024       expr = TREE_OPERAND (expr, 0);
15025       addr = true;
15026     }
15027   if (TREE_CODE (expr) == OFFSET_REF)
15028     {
15029       offset = expr;
15030       expr = TREE_OPERAND (expr, 1);
15031     }
15032   if (TREE_CODE (expr) == BASELINK)
15033     {
15034       baselink = expr;
15035       expr = BASELINK_FUNCTIONS (expr);
15036     }
15037
15038   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15039     {
15040       int good = 0;
15041       tree goodfn = NULL_TREE;
15042
15043       /* If we got some explicit template args, we need to plug them into
15044          the affected templates before we try to unify, in case the
15045          explicit args will completely resolve the templates in question.  */
15046
15047       tree expl_subargs = TREE_OPERAND (expr, 1);
15048       tree arg = TREE_OPERAND (expr, 0);
15049       tree badfn = NULL_TREE;
15050       tree badargs = NULL_TREE;
15051
15052       for (; arg; arg = OVL_NEXT (arg))
15053         {
15054           tree fn = OVL_CURRENT (arg);
15055           tree subargs, elem;
15056
15057           if (TREE_CODE (fn) != TEMPLATE_DECL)
15058             continue;
15059
15060           ++processing_template_decl;
15061           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15062                                   expl_subargs, /*check_ret=*/false);
15063           if (subargs && !any_dependent_template_arguments_p (subargs))
15064             {
15065               elem = instantiate_template (fn, subargs, tf_none);
15066               if (elem == error_mark_node)
15067                 {
15068                   badfn = fn;
15069                   badargs = subargs;
15070                 }
15071               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15072                 {
15073                   goodfn = elem;
15074                   ++good;
15075                 }
15076             }
15077           --processing_template_decl;
15078         }
15079       if (good == 1)
15080         {
15081           mark_used (goodfn);
15082           expr = goodfn;
15083           if (baselink)
15084             expr = build_baselink (BASELINK_BINFO (baselink),
15085                                    BASELINK_ACCESS_BINFO (baselink),
15086                                    expr, BASELINK_OPTYPE (baselink));
15087           if (offset)
15088             {
15089               tree base
15090                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15091               expr = build_offset_ref (base, expr, addr);
15092             }
15093           if (addr)
15094             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15095           return expr;
15096         }
15097       else if (good == 0 && badargs)
15098         /* There were no good options and at least one bad one, so let the
15099            user know what the problem is.  */
15100         instantiate_template (badfn, badargs, tf_warning_or_error);
15101     }
15102   return orig_expr;
15103 }
15104
15105 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15106    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15107    different overloads deduce different arguments for a given parm.
15108    ADDR_P is true if the expression for which deduction is being
15109    performed was of the form "& fn" rather than simply "fn".
15110
15111    Returns 1 on success.  */
15112
15113 static int
15114 try_one_overload (tree tparms,
15115                   tree orig_targs,
15116                   tree targs,
15117                   tree parm,
15118                   tree arg,
15119                   unification_kind_t strict,
15120                   int sub_strict,
15121                   bool addr_p,
15122                   bool explain_p)
15123 {
15124   int nargs;
15125   tree tempargs;
15126   int i;
15127
15128   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15129      to function or pointer to member function argument if the set of
15130      overloaded functions does not contain function templates and at most
15131      one of a set of overloaded functions provides a unique match.
15132
15133      So if this is a template, just return success.  */
15134
15135   if (uses_template_parms (arg))
15136     return 1;
15137
15138   if (TREE_CODE (arg) == METHOD_TYPE)
15139     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15140   else if (addr_p)
15141     arg = build_pointer_type (arg);
15142
15143   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15144
15145   /* We don't copy orig_targs for this because if we have already deduced
15146      some template args from previous args, unify would complain when we
15147      try to deduce a template parameter for the same argument, even though
15148      there isn't really a conflict.  */
15149   nargs = TREE_VEC_LENGTH (targs);
15150   tempargs = make_tree_vec (nargs);
15151
15152   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15153     return 0;
15154
15155   /* First make sure we didn't deduce anything that conflicts with
15156      explicitly specified args.  */
15157   for (i = nargs; i--; )
15158     {
15159       tree elt = TREE_VEC_ELT (tempargs, i);
15160       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15161
15162       if (!elt)
15163         /*NOP*/;
15164       else if (uses_template_parms (elt))
15165         /* Since we're unifying against ourselves, we will fill in
15166            template args used in the function parm list with our own
15167            template parms.  Discard them.  */
15168         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15169       else if (oldelt && !template_args_equal (oldelt, elt))
15170         return 0;
15171     }
15172
15173   for (i = nargs; i--; )
15174     {
15175       tree elt = TREE_VEC_ELT (tempargs, i);
15176
15177       if (elt)
15178         TREE_VEC_ELT (targs, i) = elt;
15179     }
15180
15181   return 1;
15182 }
15183
15184 /* PARM is a template class (perhaps with unbound template
15185    parameters).  ARG is a fully instantiated type.  If ARG can be
15186    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15187    TARGS are as for unify.  */
15188
15189 static tree
15190 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15191                        bool explain_p)
15192 {
15193   tree copy_of_targs;
15194
15195   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15196       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15197           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15198     return NULL_TREE;
15199
15200   /* We need to make a new template argument vector for the call to
15201      unify.  If we used TARGS, we'd clutter it up with the result of
15202      the attempted unification, even if this class didn't work out.
15203      We also don't want to commit ourselves to all the unifications
15204      we've already done, since unification is supposed to be done on
15205      an argument-by-argument basis.  In other words, consider the
15206      following pathological case:
15207
15208        template <int I, int J, int K>
15209        struct S {};
15210
15211        template <int I, int J>
15212        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15213
15214        template <int I, int J, int K>
15215        void f(S<I, J, K>, S<I, I, I>);
15216
15217        void g() {
15218          S<0, 0, 0> s0;
15219          S<0, 1, 2> s2;
15220
15221          f(s0, s2);
15222        }
15223
15224      Now, by the time we consider the unification involving `s2', we
15225      already know that we must have `f<0, 0, 0>'.  But, even though
15226      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15227      because there are two ways to unify base classes of S<0, 1, 2>
15228      with S<I, I, I>.  If we kept the already deduced knowledge, we
15229      would reject the possibility I=1.  */
15230   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15231
15232   /* If unification failed, we're done.  */
15233   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15234              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15235     return NULL_TREE;
15236
15237   return arg;
15238 }
15239
15240 /* Given a template type PARM and a class type ARG, find the unique
15241    base type in ARG that is an instance of PARM.  We do not examine
15242    ARG itself; only its base-classes.  If there is not exactly one
15243    appropriate base class, return NULL_TREE.  PARM may be the type of
15244    a partial specialization, as well as a plain template type.  Used
15245    by unify.  */
15246
15247 static enum template_base_result
15248 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15249                    bool explain_p, tree *result)
15250 {
15251   tree rval = NULL_TREE;
15252   tree binfo;
15253
15254   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15255
15256   binfo = TYPE_BINFO (complete_type (arg));
15257   if (!binfo)
15258     {
15259       /* The type could not be completed.  */
15260       *result = NULL_TREE;
15261       return tbr_incomplete_type;
15262     }
15263
15264   /* Walk in inheritance graph order.  The search order is not
15265      important, and this avoids multiple walks of virtual bases.  */
15266   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15267     {
15268       tree r = try_class_unification (tparms, targs, parm,
15269                                       BINFO_TYPE (binfo), explain_p);
15270
15271       if (r)
15272         {
15273           /* If there is more than one satisfactory baseclass, then:
15274
15275                [temp.deduct.call]
15276
15277               If they yield more than one possible deduced A, the type
15278               deduction fails.
15279
15280              applies.  */
15281           if (rval && !same_type_p (r, rval))
15282             {
15283               *result = NULL_TREE;
15284               return tbr_ambiguous_baseclass;
15285             }
15286
15287           rval = r;
15288         }
15289     }
15290
15291   *result = rval;
15292   return tbr_success;
15293 }
15294
15295 /* Returns the level of DECL, which declares a template parameter.  */
15296
15297 static int
15298 template_decl_level (tree decl)
15299 {
15300   switch (TREE_CODE (decl))
15301     {
15302     case TYPE_DECL:
15303     case TEMPLATE_DECL:
15304       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15305
15306     case PARM_DECL:
15307       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15308
15309     default:
15310       gcc_unreachable ();
15311     }
15312   return 0;
15313 }
15314
15315 /* Decide whether ARG can be unified with PARM, considering only the
15316    cv-qualifiers of each type, given STRICT as documented for unify.
15317    Returns nonzero iff the unification is OK on that basis.  */
15318
15319 static int
15320 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15321 {
15322   int arg_quals = cp_type_quals (arg);
15323   int parm_quals = cp_type_quals (parm);
15324
15325   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15326       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15327     {
15328       /*  Although a CVR qualifier is ignored when being applied to a
15329           substituted template parameter ([8.3.2]/1 for example), that
15330           does not allow us to unify "const T" with "int&" because both
15331           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15332           It is ok when we're allowing additional CV qualifiers
15333           at the outer level [14.8.2.1]/3,1st bullet.  */
15334       if ((TREE_CODE (arg) == REFERENCE_TYPE
15335            || TREE_CODE (arg) == FUNCTION_TYPE
15336            || TREE_CODE (arg) == METHOD_TYPE)
15337           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15338         return 0;
15339
15340       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15341           && (parm_quals & TYPE_QUAL_RESTRICT))
15342         return 0;
15343     }
15344
15345   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15346       && (arg_quals & parm_quals) != parm_quals)
15347     return 0;
15348
15349   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15350       && (parm_quals & arg_quals) != arg_quals)
15351     return 0;
15352
15353   return 1;
15354 }
15355
15356 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15357 void 
15358 template_parm_level_and_index (tree parm, int* level, int* index)
15359 {
15360   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15361       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15362       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15363     {
15364       *index = TEMPLATE_TYPE_IDX (parm);
15365       *level = TEMPLATE_TYPE_LEVEL (parm);
15366     }
15367   else
15368     {
15369       *index = TEMPLATE_PARM_IDX (parm);
15370       *level = TEMPLATE_PARM_LEVEL (parm);
15371     }
15372 }
15373
15374 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15375   do {                                                                  \
15376     if (unify (TP, TA, P, A, S, EP))                                    \
15377       return 1;                                                         \
15378   } while (0);
15379
15380 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15381    expansion at the end of PACKED_PARMS. Returns 0 if the type
15382    deduction succeeds, 1 otherwise. STRICT is the same as in
15383    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15384    call argument list. We'll need to adjust the arguments to make them
15385    types. SUBR tells us if this is from a recursive call to
15386    type_unification_real.  */
15387 static int
15388 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15389                       tree packed_args, int strict, bool call_args_p,
15390                       bool subr, bool explain_p)
15391 {
15392   tree parm 
15393     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15394   tree pattern = PACK_EXPANSION_PATTERN (parm);
15395   tree pack, packs = NULL_TREE;
15396   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15397   int len = TREE_VEC_LENGTH (packed_args);
15398
15399   /* Determine the parameter packs we will be deducing from the
15400      pattern, and record their current deductions.  */
15401   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15402        pack; pack = TREE_CHAIN (pack))
15403     {
15404       tree parm_pack = TREE_VALUE (pack);
15405       int idx, level;
15406
15407       /* Determine the index and level of this parameter pack.  */
15408       template_parm_level_and_index (parm_pack, &level, &idx);
15409
15410       /* Keep track of the parameter packs and their corresponding
15411          argument packs.  */
15412       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15413       TREE_TYPE (packs) = make_tree_vec (len - start);
15414     }
15415   
15416   /* Loop through all of the arguments that have not yet been
15417      unified and unify each with the pattern.  */
15418   for (i = start; i < len; i++)
15419     {
15420       tree parm = pattern;
15421
15422       /* For each parameter pack, clear out the deduced value so that
15423          we can deduce it again.  */
15424       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15425         {
15426           int idx, level;
15427           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15428
15429           TMPL_ARG (targs, level, idx) = NULL_TREE;
15430         }
15431
15432       /* Unify the pattern with the current argument.  */
15433       {
15434         tree arg = TREE_VEC_ELT (packed_args, i);
15435         tree arg_expr = NULL_TREE;
15436         int arg_strict = strict;
15437
15438         if (call_args_p)
15439           {
15440             int sub_strict;
15441
15442             /* This mirrors what we do in type_unification_real.  */
15443             switch (strict)
15444               {
15445               case DEDUCE_CALL:
15446                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
15447                               | UNIFY_ALLOW_MORE_CV_QUAL
15448                               | UNIFY_ALLOW_DERIVED);
15449                 break;
15450                 
15451               case DEDUCE_CONV:
15452                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
15453                 break;
15454                 
15455               case DEDUCE_EXACT:
15456                 sub_strict = UNIFY_ALLOW_NONE;
15457                 break;
15458                 
15459               default:
15460                 gcc_unreachable ();
15461               }
15462
15463             if (!TYPE_P (arg))
15464               {
15465                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
15466                 if (type_unknown_p (arg))
15467                   {
15468                     /* [temp.deduct.type] A template-argument can be
15469                        deduced from a pointer to function or pointer
15470                        to member function argument if the set of
15471                        overloaded functions does not contain function
15472                        templates and at most one of a set of
15473                        overloaded functions provides a unique
15474                        match.  */
15475
15476                     if (resolve_overloaded_unification
15477                         (tparms, targs, parm, arg,
15478                          (unification_kind_t) strict,
15479                          sub_strict, explain_p))
15480                       goto unified;
15481                     return unify_overload_resolution_failure (explain_p, arg);
15482                   }
15483
15484                 arg_expr = arg;
15485                 arg = unlowered_expr_type (arg);
15486                 if (arg == error_mark_node)
15487                   return unify_invalid (explain_p);
15488               }
15489       
15490             arg_strict = sub_strict;
15491
15492             if (!subr)
15493               arg_strict |= 
15494                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
15495                                                   &parm, &arg, arg_expr);
15496           }
15497
15498         /* For deduction from an init-list we need the actual list.  */
15499         if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15500           arg = arg_expr;
15501         RECUR_AND_CHECK_FAILURE (tparms, targs, parm, arg, arg_strict,
15502                                  explain_p);
15503       }
15504
15505     unified:
15506       /* For each parameter pack, collect the deduced value.  */
15507       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15508         {
15509           int idx, level;
15510           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15511
15512           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15513             TMPL_ARG (targs, level, idx);
15514         }
15515     }
15516
15517   /* Verify that the results of unification with the parameter packs
15518      produce results consistent with what we've seen before, and make
15519      the deduced argument packs available.  */
15520   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15521     {
15522       tree old_pack = TREE_VALUE (pack);
15523       tree new_args = TREE_TYPE (pack);
15524       int i, len = TREE_VEC_LENGTH (new_args);
15525       int idx, level;
15526       bool nondeduced_p = false;
15527
15528       /* By default keep the original deduced argument pack.
15529          If necessary, more specific code is going to update the
15530          resulting deduced argument later down in this function.  */
15531       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15532       TMPL_ARG (targs, level, idx) = old_pack;
15533
15534       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15535          actually deduce anything.  */
15536       for (i = 0; i < len && !nondeduced_p; ++i)
15537         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15538           nondeduced_p = true;
15539       if (nondeduced_p)
15540         continue;
15541
15542       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15543         {
15544           /* Prepend the explicit arguments onto NEW_ARGS.  */
15545           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15546           tree old_args = new_args;
15547           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
15548           int len = explicit_len + TREE_VEC_LENGTH (old_args);
15549
15550           /* Copy the explicit arguments.  */
15551           new_args = make_tree_vec (len);
15552           for (i = 0; i < explicit_len; i++)
15553             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
15554
15555           /* Copy the deduced arguments.  */
15556           for (; i < len; i++)
15557             TREE_VEC_ELT (new_args, i) =
15558               TREE_VEC_ELT (old_args, i - explicit_len);
15559         }
15560
15561       if (!old_pack)
15562         {
15563           tree result;
15564           /* Build the deduced *_ARGUMENT_PACK.  */
15565           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15566             {
15567               result = make_node (NONTYPE_ARGUMENT_PACK);
15568               TREE_TYPE (result) = 
15569                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15570               TREE_CONSTANT (result) = 1;
15571             }
15572           else
15573             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15574
15575           SET_ARGUMENT_PACK_ARGS (result, new_args);
15576
15577           /* Note the deduced argument packs for this parameter
15578              pack.  */
15579           TMPL_ARG (targs, level, idx) = result;
15580         }
15581       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15582                && (ARGUMENT_PACK_ARGS (old_pack) 
15583                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15584         {
15585           /* We only had the explicitly-provided arguments before, but
15586              now we have a complete set of arguments.  */
15587           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15588
15589           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15590           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15591           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15592         }
15593       else
15594         {
15595           tree bad_old_arg, bad_new_arg;
15596           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15597
15598           if (!comp_template_args_with_info (old_args, new_args,
15599                                              &bad_old_arg, &bad_new_arg))
15600             /* Inconsistent unification of this parameter pack.  */
15601             return unify_parameter_pack_inconsistent (explain_p,
15602                                                       bad_old_arg,
15603                                                       bad_new_arg);
15604         }
15605     }
15606
15607   return unify_success (explain_p);
15608 }
15609
15610 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15611    set of template parameters to a template.  TARGS is the bindings
15612    for those template parameters, as determined thus far; TARGS may
15613    include template arguments for outer levels of template parameters
15614    as well.  PARM is a parameter to a template function, or a
15615    subcomponent of that parameter; ARG is the corresponding argument.
15616    This function attempts to match PARM with ARG in a manner
15617    consistent with the existing assignments in TARGS.  If more values
15618    are deduced, then TARGS is updated.
15619
15620    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15621    parameter STRICT is a bitwise or of the following flags:
15622
15623      UNIFY_ALLOW_NONE:
15624        Require an exact match between PARM and ARG.
15625      UNIFY_ALLOW_MORE_CV_QUAL:
15626        Allow the deduced ARG to be more cv-qualified (by qualification
15627        conversion) than ARG.
15628      UNIFY_ALLOW_LESS_CV_QUAL:
15629        Allow the deduced ARG to be less cv-qualified than ARG.
15630      UNIFY_ALLOW_DERIVED:
15631        Allow the deduced ARG to be a template base class of ARG,
15632        or a pointer to a template base class of the type pointed to by
15633        ARG.
15634      UNIFY_ALLOW_INTEGER:
15635        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15636        case for more information.
15637      UNIFY_ALLOW_OUTER_LEVEL:
15638        This is the outermost level of a deduction. Used to determine validity
15639        of qualification conversions. A valid qualification conversion must
15640        have const qualified pointers leading up to the inner type which
15641        requires additional CV quals, except at the outer level, where const
15642        is not required [conv.qual]. It would be normal to set this flag in
15643        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15644      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15645        This is the outermost level of a deduction, and PARM can be more CV
15646        qualified at this point.
15647      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15648        This is the outermost level of a deduction, and PARM can be less CV
15649        qualified at this point.  */
15650
15651 static int
15652 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15653        bool explain_p)
15654 {
15655   int idx;
15656   tree targ;
15657   tree tparm;
15658   int strict_in = strict;
15659
15660   /* I don't think this will do the right thing with respect to types.
15661      But the only case I've seen it in so far has been array bounds, where
15662      signedness is the only information lost, and I think that will be
15663      okay.  */
15664   while (TREE_CODE (parm) == NOP_EXPR)
15665     parm = TREE_OPERAND (parm, 0);
15666
15667   if (arg == error_mark_node)
15668     return unify_invalid (explain_p);
15669   if (arg == unknown_type_node
15670       || arg == init_list_type_node)
15671     /* We can't deduce anything from this, but we might get all the
15672        template args from other function args.  */
15673     return unify_success (explain_p);
15674
15675   /* If PARM uses template parameters, then we can't bail out here,
15676      even if ARG == PARM, since we won't record unifications for the
15677      template parameters.  We might need them if we're trying to
15678      figure out which of two things is more specialized.  */
15679   if (arg == parm && !uses_template_parms (parm))
15680     return unify_success (explain_p);
15681
15682   /* Handle init lists early, so the rest of the function can assume
15683      we're dealing with a type. */
15684   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15685     {
15686       tree elt, elttype;
15687       unsigned i;
15688       tree orig_parm = parm;
15689
15690       /* Replace T with std::initializer_list<T> for deduction.  */
15691       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15692           && flag_deduce_init_list)
15693         parm = listify (parm);
15694
15695       if (!is_std_init_list (parm))
15696         /* We can only deduce from an initializer list argument if the
15697            parameter is std::initializer_list; otherwise this is a
15698            non-deduced context. */
15699         return unify_success (explain_p);
15700
15701       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15702
15703       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15704         {
15705           int elt_strict = strict;
15706
15707           if (elt == error_mark_node)
15708             return unify_invalid (explain_p);
15709
15710           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15711             {
15712               tree type = TREE_TYPE (elt);
15713               /* It should only be possible to get here for a call.  */
15714               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15715               elt_strict |= maybe_adjust_types_for_deduction
15716                 (DEDUCE_CALL, &elttype, &type, elt);
15717               elt = type;
15718             }
15719
15720           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15721                                    explain_p);
15722         }
15723
15724       /* If the std::initializer_list<T> deduction worked, replace the
15725          deduced A with std::initializer_list<A>.  */
15726       if (orig_parm != parm)
15727         {
15728           idx = TEMPLATE_TYPE_IDX (orig_parm);
15729           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15730           targ = listify (targ);
15731           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15732         }
15733       return unify_success (explain_p);
15734     }
15735
15736   /* Immediately reject some pairs that won't unify because of
15737      cv-qualification mismatches.  */
15738   if (TREE_CODE (arg) == TREE_CODE (parm)
15739       && TYPE_P (arg)
15740       /* It is the elements of the array which hold the cv quals of an array
15741          type, and the elements might be template type parms. We'll check
15742          when we recurse.  */
15743       && TREE_CODE (arg) != ARRAY_TYPE
15744       /* We check the cv-qualifiers when unifying with template type
15745          parameters below.  We want to allow ARG `const T' to unify with
15746          PARM `T' for example, when computing which of two templates
15747          is more specialized, for example.  */
15748       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15749       && !check_cv_quals_for_unify (strict_in, arg, parm))
15750     return unify_cv_qual_mismatch (explain_p, parm, arg);
15751
15752   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15753       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15754     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15755   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15756   strict &= ~UNIFY_ALLOW_DERIVED;
15757   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15758   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15759
15760   switch (TREE_CODE (parm))
15761     {
15762     case TYPENAME_TYPE:
15763     case SCOPE_REF:
15764     case UNBOUND_CLASS_TEMPLATE:
15765       /* In a type which contains a nested-name-specifier, template
15766          argument values cannot be deduced for template parameters used
15767          within the nested-name-specifier.  */
15768       return unify_success (explain_p);
15769
15770     case TEMPLATE_TYPE_PARM:
15771     case TEMPLATE_TEMPLATE_PARM:
15772     case BOUND_TEMPLATE_TEMPLATE_PARM:
15773       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15774       if (tparm == error_mark_node)
15775         return unify_invalid (explain_p);
15776
15777       if (TEMPLATE_TYPE_LEVEL (parm)
15778           != template_decl_level (tparm))
15779         /* The PARM is not one we're trying to unify.  Just check
15780            to see if it matches ARG.  */
15781         {
15782           if (TREE_CODE (arg) == TREE_CODE (parm)
15783               && same_type_p (parm, arg))
15784             return unify_success (explain_p);
15785           else
15786             return unify_type_mismatch (explain_p, parm, arg);
15787         }
15788       idx = TEMPLATE_TYPE_IDX (parm);
15789       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15790       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15791
15792       /* Check for mixed types and values.  */
15793       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15794            && TREE_CODE (tparm) != TYPE_DECL)
15795           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15796               && TREE_CODE (tparm) != TEMPLATE_DECL))
15797         gcc_unreachable ();
15798
15799       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15800         {
15801           /* ARG must be constructed from a template class or a template
15802              template parameter.  */
15803           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15804               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15805             return unify_template_deduction_failure (explain_p, parm, arg);
15806
15807           {
15808             tree parmvec = TYPE_TI_ARGS (parm);
15809             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15810             tree full_argvec = add_to_template_args (targs, argvec);
15811             tree parm_parms 
15812               = DECL_INNERMOST_TEMPLATE_PARMS
15813                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15814             int i, len;
15815             int parm_variadic_p = 0;
15816
15817             /* The resolution to DR150 makes clear that default
15818                arguments for an N-argument may not be used to bind T
15819                to a template template parameter with fewer than N
15820                parameters.  It is not safe to permit the binding of
15821                default arguments as an extension, as that may change
15822                the meaning of a conforming program.  Consider:
15823
15824                   struct Dense { static const unsigned int dim = 1; };
15825
15826                   template <template <typename> class View,
15827                             typename Block>
15828                   void operator+(float, View<Block> const&);
15829
15830                   template <typename Block,
15831                             unsigned int Dim = Block::dim>
15832                   struct Lvalue_proxy { operator float() const; };
15833
15834                   void
15835                   test_1d (void) {
15836                     Lvalue_proxy<Dense> p;
15837                     float b;
15838                     b + p;
15839                   }
15840
15841               Here, if Lvalue_proxy is permitted to bind to View, then
15842               the global operator+ will be used; if they are not, the
15843               Lvalue_proxy will be converted to float.  */
15844             if (coerce_template_parms (parm_parms,
15845                                        full_argvec,
15846                                        TYPE_TI_TEMPLATE (parm),
15847                                        (explain_p
15848                                         ? tf_warning_or_error
15849                                         : tf_none),
15850                                        /*require_all_args=*/true,
15851                                        /*use_default_args=*/false)
15852                 == error_mark_node)
15853               return 1;
15854
15855             /* Deduce arguments T, i from TT<T> or TT<i>.
15856                We check each element of PARMVEC and ARGVEC individually
15857                rather than the whole TREE_VEC since they can have
15858                different number of elements.  */
15859
15860             parmvec = expand_template_argument_pack (parmvec);
15861             argvec = expand_template_argument_pack (argvec);
15862
15863             len = TREE_VEC_LENGTH (parmvec);
15864
15865             /* Check if the parameters end in a pack, making them
15866                variadic.  */
15867             if (len > 0
15868                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15869               parm_variadic_p = 1;
15870             
15871             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15872               return unify_too_few_arguments (explain_p,
15873                                               TREE_VEC_LENGTH (argvec), len);
15874
15875              for (i = 0; i < len - parm_variadic_p; ++i)
15876               {
15877                 RECUR_AND_CHECK_FAILURE (tparms, targs,
15878                                          TREE_VEC_ELT (parmvec, i),
15879                                          TREE_VEC_ELT (argvec, i),
15880                                          UNIFY_ALLOW_NONE, explain_p);
15881               }
15882
15883             if (parm_variadic_p
15884                 && unify_pack_expansion (tparms, targs,
15885                                          parmvec, argvec,
15886                                          UNIFY_ALLOW_NONE,
15887                                          /*call_args_p=*/false,
15888                                          /*subr=*/false, explain_p))
15889               return 1;
15890           }
15891           arg = TYPE_TI_TEMPLATE (arg);
15892
15893           /* Fall through to deduce template name.  */
15894         }
15895
15896       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15897           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15898         {
15899           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15900
15901           /* Simple cases: Value already set, does match or doesn't.  */
15902           if (targ != NULL_TREE && template_args_equal (targ, arg))
15903             return unify_success (explain_p);
15904           else if (targ)
15905             return unify_inconsistency (explain_p, parm, targ, arg);
15906         }
15907       else
15908         {
15909           /* If PARM is `const T' and ARG is only `int', we don't have
15910              a match unless we are allowing additional qualification.
15911              If ARG is `const int' and PARM is just `T' that's OK;
15912              that binds `const int' to `T'.  */
15913           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15914                                          arg, parm))
15915             return unify_cv_qual_mismatch (explain_p, parm, arg);
15916
15917           /* Consider the case where ARG is `const volatile int' and
15918              PARM is `const T'.  Then, T should be `volatile int'.  */
15919           arg = cp_build_qualified_type_real
15920             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15921           if (arg == error_mark_node)
15922             return unify_invalid (explain_p);
15923
15924           /* Simple cases: Value already set, does match or doesn't.  */
15925           if (targ != NULL_TREE && same_type_p (targ, arg))
15926             return unify_success (explain_p);
15927           else if (targ)
15928             return unify_inconsistency (explain_p, parm, targ, arg);
15929
15930           /* Make sure that ARG is not a variable-sized array.  (Note
15931              that were talking about variable-sized arrays (like
15932              `int[n]'), rather than arrays of unknown size (like
15933              `int[]').)  We'll get very confused by such a type since
15934              the bound of the array is not constant, and therefore
15935              not mangleable.  Besides, such types are not allowed in
15936              ISO C++, so we can do as we please here.  We do allow
15937              them for 'auto' deduction, since that isn't ABI-exposed.  */
15938           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
15939             return unify_vla_arg (explain_p, arg);
15940
15941           /* Strip typedefs as in convert_template_argument.  */
15942           arg = canonicalize_type_argument (arg, tf_none);
15943         }
15944
15945       /* If ARG is a parameter pack or an expansion, we cannot unify
15946          against it unless PARM is also a parameter pack.  */
15947       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15948           && !template_parameter_pack_p (parm))
15949         return unify_parameter_pack_mismatch (explain_p, parm, arg);
15950
15951       /* If the argument deduction results is a METHOD_TYPE,
15952          then there is a problem.
15953          METHOD_TYPE doesn't map to any real C++ type the result of
15954          the deduction can not be of that type.  */
15955       if (TREE_CODE (arg) == METHOD_TYPE)
15956         return unify_method_type_error (explain_p, arg);
15957
15958       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15959       return unify_success (explain_p);
15960
15961     case TEMPLATE_PARM_INDEX:
15962       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15963       if (tparm == error_mark_node)
15964         return unify_invalid (explain_p);
15965
15966       if (TEMPLATE_PARM_LEVEL (parm)
15967           != template_decl_level (tparm))
15968         {
15969           /* The PARM is not one we're trying to unify.  Just check
15970              to see if it matches ARG.  */
15971           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
15972                          && cp_tree_equal (parm, arg));
15973           if (result)
15974             unify_expression_unequal (explain_p, parm, arg);
15975           return result;
15976         }
15977
15978       idx = TEMPLATE_PARM_IDX (parm);
15979       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15980
15981       if (targ)
15982         {
15983           int x = !cp_tree_equal (targ, arg);
15984           if (x)
15985             unify_inconsistency (explain_p, parm, targ, arg);
15986           return x;
15987         }
15988
15989       /* [temp.deduct.type] If, in the declaration of a function template
15990          with a non-type template-parameter, the non-type
15991          template-parameter is used in an expression in the function
15992          parameter-list and, if the corresponding template-argument is
15993          deduced, the template-argument type shall match the type of the
15994          template-parameter exactly, except that a template-argument
15995          deduced from an array bound may be of any integral type.
15996          The non-type parameter might use already deduced type parameters.  */
15997       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15998       if (!TREE_TYPE (arg))
15999         /* Template-parameter dependent expression.  Just accept it for now.
16000            It will later be processed in convert_template_argument.  */
16001         ;
16002       else if (same_type_p (TREE_TYPE (arg), tparm))
16003         /* OK */;
16004       else if ((strict & UNIFY_ALLOW_INTEGER)
16005                && (TREE_CODE (tparm) == INTEGER_TYPE
16006                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16007         /* Convert the ARG to the type of PARM; the deduced non-type
16008            template argument must exactly match the types of the
16009            corresponding parameter.  */
16010         arg = fold (build_nop (tparm, arg));
16011       else if (uses_template_parms (tparm))
16012         /* We haven't deduced the type of this parameter yet.  Try again
16013            later.  */
16014         return unify_success (explain_p);
16015       else
16016         return unify_type_mismatch (explain_p, tparm, arg);
16017
16018       /* If ARG is a parameter pack or an expansion, we cannot unify
16019          against it unless PARM is also a parameter pack.  */
16020       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16021           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16022         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16023
16024       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16025       return unify_success (explain_p);
16026
16027     case PTRMEM_CST:
16028      {
16029         /* A pointer-to-member constant can be unified only with
16030          another constant.  */
16031       if (TREE_CODE (arg) != PTRMEM_CST)
16032         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16033
16034       /* Just unify the class member. It would be useless (and possibly
16035          wrong, depending on the strict flags) to unify also
16036          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16037          arg refer to the same variable, even if through different
16038          classes. For instance:
16039
16040          struct A { int x; };
16041          struct B : A { };
16042
16043          Unification of &A::x and &B::x must succeed.  */
16044       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16045                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16046      }
16047
16048     case POINTER_TYPE:
16049       {
16050         if (TREE_CODE (arg) != POINTER_TYPE)
16051           return unify_type_mismatch (explain_p, parm, arg);
16052
16053         /* [temp.deduct.call]
16054
16055            A can be another pointer or pointer to member type that can
16056            be converted to the deduced A via a qualification
16057            conversion (_conv.qual_).
16058
16059            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16060            This will allow for additional cv-qualification of the
16061            pointed-to types if appropriate.  */
16062
16063         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16064           /* The derived-to-base conversion only persists through one
16065              level of pointers.  */
16066           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16067
16068         return unify (tparms, targs, TREE_TYPE (parm),
16069                       TREE_TYPE (arg), strict, explain_p);
16070       }
16071
16072     case REFERENCE_TYPE:
16073       if (TREE_CODE (arg) != REFERENCE_TYPE)
16074         return unify_type_mismatch (explain_p, parm, arg);
16075       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16076                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16077
16078     case ARRAY_TYPE:
16079       if (TREE_CODE (arg) != ARRAY_TYPE)
16080         return unify_type_mismatch (explain_p, parm, arg);
16081       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16082           != (TYPE_DOMAIN (arg) == NULL_TREE))
16083         return unify_type_mismatch (explain_p, parm, arg);
16084       if (TYPE_DOMAIN (parm) != NULL_TREE)
16085         {
16086           tree parm_max;
16087           tree arg_max;
16088           bool parm_cst;
16089           bool arg_cst;
16090
16091           /* Our representation of array types uses "N - 1" as the
16092              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16093              not an integer constant.  We cannot unify arbitrarily
16094              complex expressions, so we eliminate the MINUS_EXPRs
16095              here.  */
16096           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16097           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16098           if (!parm_cst)
16099             {
16100               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16101               parm_max = TREE_OPERAND (parm_max, 0);
16102             }
16103           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16104           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16105           if (!arg_cst)
16106             {
16107               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16108                  trying to unify the type of a variable with the type
16109                  of a template parameter.  For example:
16110
16111                    template <unsigned int N>
16112                    void f (char (&) [N]);
16113                    int g(); 
16114                    void h(int i) {
16115                      char a[g(i)];
16116                      f(a); 
16117                    }
16118
16119                 Here, the type of the ARG will be "int [g(i)]", and
16120                 may be a SAVE_EXPR, etc.  */
16121               if (TREE_CODE (arg_max) != MINUS_EXPR)
16122                 return unify_vla_arg (explain_p, arg);
16123               arg_max = TREE_OPERAND (arg_max, 0);
16124             }
16125
16126           /* If only one of the bounds used a MINUS_EXPR, compensate
16127              by adding one to the other bound.  */
16128           if (parm_cst && !arg_cst)
16129             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16130                                     integer_type_node,
16131                                     parm_max,
16132                                     integer_one_node);
16133           else if (arg_cst && !parm_cst)
16134             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16135                                    integer_type_node,
16136                                    arg_max,
16137                                    integer_one_node);
16138
16139           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16140                                    UNIFY_ALLOW_INTEGER, explain_p);
16141         }
16142       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16143                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16144
16145     case REAL_TYPE:
16146     case COMPLEX_TYPE:
16147     case VECTOR_TYPE:
16148     case INTEGER_TYPE:
16149     case BOOLEAN_TYPE:
16150     case ENUMERAL_TYPE:
16151     case VOID_TYPE:
16152       if (TREE_CODE (arg) != TREE_CODE (parm))
16153         return unify_type_mismatch (explain_p, parm, arg);
16154
16155       /* We have already checked cv-qualification at the top of the
16156          function.  */
16157       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16158         return unify_type_mismatch (explain_p, parm, arg);
16159
16160       /* As far as unification is concerned, this wins.  Later checks
16161          will invalidate it if necessary.  */
16162       return unify_success (explain_p);
16163
16164       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16165       /* Type INTEGER_CST can come from ordinary constant template args.  */
16166     case INTEGER_CST:
16167       while (TREE_CODE (arg) == NOP_EXPR)
16168         arg = TREE_OPERAND (arg, 0);
16169
16170       if (TREE_CODE (arg) != INTEGER_CST)
16171         return unify_template_argument_mismatch (explain_p, parm, arg);
16172       return (tree_int_cst_equal (parm, arg)
16173               ? unify_success (explain_p)
16174               : unify_template_argument_mismatch (explain_p, parm, arg));
16175
16176     case TREE_VEC:
16177       {
16178         int i;
16179         if (TREE_CODE (arg) != TREE_VEC)
16180           return unify_template_argument_mismatch (explain_p, parm, arg);
16181         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
16182           return unify_arity (explain_p, TREE_VEC_LENGTH (arg),
16183                               TREE_VEC_LENGTH (parm));
16184         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
16185           RECUR_AND_CHECK_FAILURE (tparms, targs,
16186                                    TREE_VEC_ELT (parm, i),
16187                                    TREE_VEC_ELT (arg, i),
16188                                    UNIFY_ALLOW_NONE, explain_p);
16189         return unify_success (explain_p);
16190       }
16191
16192     case RECORD_TYPE:
16193     case UNION_TYPE:
16194       if (TREE_CODE (arg) != TREE_CODE (parm))
16195         return unify_type_mismatch (explain_p, parm, arg);
16196
16197       if (TYPE_PTRMEMFUNC_P (parm))
16198         {
16199           if (!TYPE_PTRMEMFUNC_P (arg))
16200             return unify_type_mismatch (explain_p, parm, arg);
16201
16202           return unify (tparms, targs,
16203                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16204                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16205                         strict, explain_p);
16206         }
16207
16208       if (CLASSTYPE_TEMPLATE_INFO (parm))
16209         {
16210           tree t = NULL_TREE;
16211
16212           if (strict_in & UNIFY_ALLOW_DERIVED)
16213             {
16214               /* First, we try to unify the PARM and ARG directly.  */
16215               t = try_class_unification (tparms, targs,
16216                                          parm, arg, explain_p);
16217
16218               if (!t)
16219                 {
16220                   /* Fallback to the special case allowed in
16221                      [temp.deduct.call]:
16222
16223                        If P is a class, and P has the form
16224                        template-id, then A can be a derived class of
16225                        the deduced A.  Likewise, if P is a pointer to
16226                        a class of the form template-id, A can be a
16227                        pointer to a derived class pointed to by the
16228                        deduced A.  */
16229                   enum template_base_result r;
16230                   r = get_template_base (tparms, targs, parm, arg,
16231                                          explain_p, &t);
16232
16233                   if (!t)
16234                     return unify_no_common_base (explain_p, r, parm, arg);
16235                 }
16236             }
16237           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16238                    && (CLASSTYPE_TI_TEMPLATE (parm)
16239                        == CLASSTYPE_TI_TEMPLATE (arg)))
16240             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16241                Then, we should unify `int' and `U'.  */
16242             t = arg;
16243           else
16244             /* There's no chance of unification succeeding.  */
16245             return unify_type_mismatch (explain_p, parm, arg);
16246
16247           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16248                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16249         }
16250       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16251         return unify_type_mismatch (explain_p, parm, arg);
16252       return unify_success (explain_p);
16253
16254     case METHOD_TYPE:
16255     case FUNCTION_TYPE:
16256       {
16257         unsigned int nargs;
16258         tree *args;
16259         tree a;
16260         unsigned int i;
16261
16262         if (TREE_CODE (arg) != TREE_CODE (parm))
16263           return unify_type_mismatch (explain_p, parm, arg);
16264
16265         /* CV qualifications for methods can never be deduced, they must
16266            match exactly.  We need to check them explicitly here,
16267            because type_unification_real treats them as any other
16268            cv-qualified parameter.  */
16269         if (TREE_CODE (parm) == METHOD_TYPE
16270             && (!check_cv_quals_for_unify
16271                 (UNIFY_ALLOW_NONE,
16272                  class_of_this_parm (arg),
16273                  class_of_this_parm (parm))))
16274           return unify_cv_qual_mismatch (explain_p, parm, arg);
16275
16276         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16277                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16278
16279         nargs = list_length (TYPE_ARG_TYPES (arg));
16280         args = XALLOCAVEC (tree, nargs);
16281         for (a = TYPE_ARG_TYPES (arg), i = 0;
16282              a != NULL_TREE && a != void_list_node;
16283              a = TREE_CHAIN (a), ++i)
16284           args[i] = TREE_VALUE (a);
16285         nargs = i;
16286
16287         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16288                                       args, nargs, 1, DEDUCE_EXACT,
16289                                       LOOKUP_NORMAL, explain_p);
16290       }
16291
16292     case OFFSET_TYPE:
16293       /* Unify a pointer to member with a pointer to member function, which
16294          deduces the type of the member as a function type. */
16295       if (TYPE_PTRMEMFUNC_P (arg))
16296         {
16297           tree method_type;
16298           tree fntype;
16299
16300           /* Check top-level cv qualifiers */
16301           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16302             return unify_cv_qual_mismatch (explain_p, parm, arg);
16303
16304           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16305                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16306                                    UNIFY_ALLOW_NONE, explain_p);
16307
16308           /* Determine the type of the function we are unifying against. */
16309           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16310           fntype =
16311             build_function_type (TREE_TYPE (method_type),
16312                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16313
16314           /* Extract the cv-qualifiers of the member function from the
16315              implicit object parameter and place them on the function
16316              type to be restored later. */
16317           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16318           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16319         }
16320
16321       if (TREE_CODE (arg) != OFFSET_TYPE)
16322         return unify_type_mismatch (explain_p, parm, arg);
16323       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16324                                TYPE_OFFSET_BASETYPE (arg),
16325                                UNIFY_ALLOW_NONE, explain_p);
16326       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16327                     strict, explain_p);
16328
16329     case CONST_DECL:
16330       if (DECL_TEMPLATE_PARM_P (parm))
16331         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16332       if (arg != integral_constant_value (parm))
16333         return unify_template_argument_mismatch (explain_p, parm, arg);
16334       return unify_success (explain_p);
16335
16336     case FIELD_DECL:
16337     case TEMPLATE_DECL:
16338       /* Matched cases are handled by the ARG == PARM test above.  */
16339       return unify_template_argument_mismatch (explain_p, parm, arg);
16340
16341     case VAR_DECL:
16342       /* A non-type template parameter that is a variable should be a
16343          an integral constant, in which case, it whould have been
16344          folded into its (constant) value. So we should not be getting
16345          a variable here.  */
16346       gcc_unreachable ();
16347
16348     case TYPE_ARGUMENT_PACK:
16349     case NONTYPE_ARGUMENT_PACK:
16350       {
16351         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
16352         tree packed_args = ARGUMENT_PACK_ARGS (arg);
16353         int i, len = TREE_VEC_LENGTH (packed_parms);
16354         int argslen = TREE_VEC_LENGTH (packed_args);
16355         int parm_variadic_p = 0;
16356
16357         for (i = 0; i < len; ++i)
16358           {
16359             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
16360               {
16361                 if (i == len - 1)
16362                   /* We can unify against something with a trailing
16363                      parameter pack.  */
16364                   parm_variadic_p = 1;
16365                 else
16366                   /* Since there is something following the pack
16367                      expansion, we cannot unify this template argument
16368                      list.  */
16369                   return unify_success (explain_p);
16370               }
16371           }
16372           
16373
16374         /* If we don't have enough arguments to satisfy the parameters
16375            (not counting the pack expression at the end), or we have
16376            too many arguments for a parameter list that doesn't end in
16377            a pack expression, we can't unify.  */
16378         if (argslen < (len - parm_variadic_p))
16379           return unify_too_few_arguments (explain_p, argslen, len);
16380         if (argslen > len && !parm_variadic_p)
16381           return unify_too_many_arguments (explain_p, argslen, len);
16382
16383         /* Unify all of the parameters that precede the (optional)
16384            pack expression.  */
16385         for (i = 0; i < len - parm_variadic_p; ++i)
16386           {
16387             RECUR_AND_CHECK_FAILURE (tparms, targs,
16388                                      TREE_VEC_ELT (packed_parms, i),
16389                                      TREE_VEC_ELT (packed_args, i),
16390                                      strict, explain_p);
16391           }
16392
16393         if (parm_variadic_p)
16394           return unify_pack_expansion (tparms, targs, 
16395                                        packed_parms, packed_args,
16396                                        strict, /*call_args_p=*/false,
16397                                        /*subr=*/false, explain_p);
16398         return unify_success (explain_p);
16399       }
16400
16401       break;
16402
16403     case TYPEOF_TYPE:
16404     case DECLTYPE_TYPE:
16405     case UNDERLYING_TYPE:
16406       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16407          or UNDERLYING_TYPE nodes.  */
16408       return unify_success (explain_p);
16409
16410     case ERROR_MARK:
16411       /* Unification fails if we hit an error node.  */
16412       return unify_invalid (explain_p);
16413
16414     default:
16415       /* An unresolved overload is a nondeduced context.  */
16416       if (type_unknown_p (parm))
16417         return unify_success (explain_p);
16418       gcc_assert (EXPR_P (parm));
16419
16420       /* We must be looking at an expression.  This can happen with
16421          something like:
16422
16423            template <int I>
16424            void foo(S<I>, S<I + 2>);
16425
16426          This is a "nondeduced context":
16427
16428            [deduct.type]
16429
16430            The nondeduced contexts are:
16431
16432            --A type that is a template-id in which one or more of
16433              the template-arguments is an expression that references
16434              a template-parameter.
16435
16436          In these cases, we assume deduction succeeded, but don't
16437          actually infer any unifications.  */
16438
16439       if (!uses_template_parms (parm)
16440           && !template_args_equal (parm, arg))
16441         return unify_expression_unequal (explain_p, parm, arg);
16442       else
16443         return unify_success (explain_p);
16444     }
16445 }
16446 #undef RECUR_AND_CHECK_FAILURE
16447 \f
16448 /* Note that DECL can be defined in this translation unit, if
16449    required.  */
16450
16451 static void
16452 mark_definable (tree decl)
16453 {
16454   tree clone;
16455   DECL_NOT_REALLY_EXTERN (decl) = 1;
16456   FOR_EACH_CLONE (clone, decl)
16457     DECL_NOT_REALLY_EXTERN (clone) = 1;
16458 }
16459
16460 /* Called if RESULT is explicitly instantiated, or is a member of an
16461    explicitly instantiated class.  */
16462
16463 void
16464 mark_decl_instantiated (tree result, int extern_p)
16465 {
16466   SET_DECL_EXPLICIT_INSTANTIATION (result);
16467
16468   /* If this entity has already been written out, it's too late to
16469      make any modifications.  */
16470   if (TREE_ASM_WRITTEN (result))
16471     return;
16472
16473   if (TREE_CODE (result) != FUNCTION_DECL)
16474     /* The TREE_PUBLIC flag for function declarations will have been
16475        set correctly by tsubst.  */
16476     TREE_PUBLIC (result) = 1;
16477
16478   /* This might have been set by an earlier implicit instantiation.  */
16479   DECL_COMDAT (result) = 0;
16480
16481   if (extern_p)
16482     DECL_NOT_REALLY_EXTERN (result) = 0;
16483   else
16484     {
16485       mark_definable (result);
16486       /* Always make artificials weak.  */
16487       if (DECL_ARTIFICIAL (result) && flag_weak)
16488         comdat_linkage (result);
16489       /* For WIN32 we also want to put explicit instantiations in
16490          linkonce sections.  */
16491       else if (TREE_PUBLIC (result))
16492         maybe_make_one_only (result);
16493     }
16494
16495   /* If EXTERN_P, then this function will not be emitted -- unless
16496      followed by an explicit instantiation, at which point its linkage
16497      will be adjusted.  If !EXTERN_P, then this function will be
16498      emitted here.  In neither circumstance do we want
16499      import_export_decl to adjust the linkage.  */
16500   DECL_INTERFACE_KNOWN (result) = 1;
16501 }
16502
16503 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16504    important template arguments.  If any are missing, we check whether
16505    they're important by using error_mark_node for substituting into any
16506    args that were used for partial ordering (the ones between ARGS and END)
16507    and seeing if it bubbles up.  */
16508
16509 static bool
16510 check_undeduced_parms (tree targs, tree args, tree end)
16511 {
16512   bool found = false;
16513   int i;
16514   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16515     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16516       {
16517         found = true;
16518         TREE_VEC_ELT (targs, i) = error_mark_node;
16519       }
16520   if (found)
16521     {
16522       for (; args != end; args = TREE_CHAIN (args))
16523         {
16524           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16525           if (substed == error_mark_node)
16526             return true;
16527         }
16528     }
16529   return false;
16530 }
16531
16532 /* Given two function templates PAT1 and PAT2, return:
16533
16534    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16535    -1 if PAT2 is more specialized than PAT1.
16536    0 if neither is more specialized.
16537
16538    LEN indicates the number of parameters we should consider
16539    (defaulted parameters should not be considered).
16540
16541    The 1998 std underspecified function template partial ordering, and
16542    DR214 addresses the issue.  We take pairs of arguments, one from
16543    each of the templates, and deduce them against each other.  One of
16544    the templates will be more specialized if all the *other*
16545    template's arguments deduce against its arguments and at least one
16546    of its arguments *does* *not* deduce against the other template's
16547    corresponding argument.  Deduction is done as for class templates.
16548    The arguments used in deduction have reference and top level cv
16549    qualifiers removed.  Iff both arguments were originally reference
16550    types *and* deduction succeeds in both directions, the template
16551    with the more cv-qualified argument wins for that pairing (if
16552    neither is more cv-qualified, they both are equal).  Unlike regular
16553    deduction, after all the arguments have been deduced in this way,
16554    we do *not* verify the deduced template argument values can be
16555    substituted into non-deduced contexts.
16556
16557    The logic can be a bit confusing here, because we look at deduce1 and
16558    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16559    can find template arguments for pat1 to make arg1 look like arg2, that
16560    means that arg2 is at least as specialized as arg1.  */
16561
16562 int
16563 more_specialized_fn (tree pat1, tree pat2, int len)
16564 {
16565   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16566   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16567   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16568   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16569   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16570   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16571   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16572   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16573   tree origs1, origs2;
16574   bool lose1 = false;
16575   bool lose2 = false;
16576
16577   /* Remove the this parameter from non-static member functions.  If
16578      one is a non-static member function and the other is not a static
16579      member function, remove the first parameter from that function
16580      also.  This situation occurs for operator functions where we
16581      locate both a member function (with this pointer) and non-member
16582      operator (with explicit first operand).  */
16583   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16584     {
16585       len--; /* LEN is the number of significant arguments for DECL1 */
16586       args1 = TREE_CHAIN (args1);
16587       if (!DECL_STATIC_FUNCTION_P (decl2))
16588         args2 = TREE_CHAIN (args2);
16589     }
16590   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16591     {
16592       args2 = TREE_CHAIN (args2);
16593       if (!DECL_STATIC_FUNCTION_P (decl1))
16594         {
16595           len--;
16596           args1 = TREE_CHAIN (args1);
16597         }
16598     }
16599
16600   /* If only one is a conversion operator, they are unordered.  */
16601   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16602     return 0;
16603
16604   /* Consider the return type for a conversion function */
16605   if (DECL_CONV_FN_P (decl1))
16606     {
16607       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16608       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16609       len++;
16610     }
16611
16612   processing_template_decl++;
16613
16614   origs1 = args1;
16615   origs2 = args2;
16616
16617   while (len--
16618          /* Stop when an ellipsis is seen.  */
16619          && args1 != NULL_TREE && args2 != NULL_TREE)
16620     {
16621       tree arg1 = TREE_VALUE (args1);
16622       tree arg2 = TREE_VALUE (args2);
16623       int deduce1, deduce2;
16624       int quals1 = -1;
16625       int quals2 = -1;
16626
16627       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16628           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16629         {
16630           /* When both arguments are pack expansions, we need only
16631              unify the patterns themselves.  */
16632           arg1 = PACK_EXPANSION_PATTERN (arg1);
16633           arg2 = PACK_EXPANSION_PATTERN (arg2);
16634
16635           /* This is the last comparison we need to do.  */
16636           len = 0;
16637         }
16638
16639       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16640         {
16641           arg1 = TREE_TYPE (arg1);
16642           quals1 = cp_type_quals (arg1);
16643         }
16644
16645       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16646         {
16647           arg2 = TREE_TYPE (arg2);
16648           quals2 = cp_type_quals (arg2);
16649         }
16650
16651       if ((quals1 < 0) != (quals2 < 0))
16652         {
16653           /* Only of the args is a reference, see if we should apply
16654              array/function pointer decay to it.  This is not part of
16655              DR214, but is, IMHO, consistent with the deduction rules
16656              for the function call itself, and with our earlier
16657              implementation of the underspecified partial ordering
16658              rules.  (nathan).  */
16659           if (quals1 >= 0)
16660             {
16661               switch (TREE_CODE (arg1))
16662                 {
16663                 case ARRAY_TYPE:
16664                   arg1 = TREE_TYPE (arg1);
16665                   /* FALLTHROUGH. */
16666                 case FUNCTION_TYPE:
16667                   arg1 = build_pointer_type (arg1);
16668                   break;
16669
16670                 default:
16671                   break;
16672                 }
16673             }
16674           else
16675             {
16676               switch (TREE_CODE (arg2))
16677                 {
16678                 case ARRAY_TYPE:
16679                   arg2 = TREE_TYPE (arg2);
16680                   /* FALLTHROUGH. */
16681                 case FUNCTION_TYPE:
16682                   arg2 = build_pointer_type (arg2);
16683                   break;
16684
16685                 default:
16686                   break;
16687                 }
16688             }
16689         }
16690
16691       arg1 = TYPE_MAIN_VARIANT (arg1);
16692       arg2 = TYPE_MAIN_VARIANT (arg2);
16693
16694       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16695         {
16696           int i, len2 = list_length (args2);
16697           tree parmvec = make_tree_vec (1);
16698           tree argvec = make_tree_vec (len2);
16699           tree ta = args2;
16700
16701           /* Setup the parameter vector, which contains only ARG1.  */
16702           TREE_VEC_ELT (parmvec, 0) = arg1;
16703
16704           /* Setup the argument vector, which contains the remaining
16705              arguments.  */
16706           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16707             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16708
16709           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16710                                            argvec, UNIFY_ALLOW_NONE, 
16711                                            /*call_args_p=*/false, 
16712                                            /*subr=*/0, /*explain_p=*/false)
16713                      == 0);
16714
16715           /* We cannot deduce in the other direction, because ARG1 is
16716              a pack expansion but ARG2 is not.  */
16717           deduce2 = 0;
16718         }
16719       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16720         {
16721           int i, len1 = list_length (args1);
16722           tree parmvec = make_tree_vec (1);
16723           tree argvec = make_tree_vec (len1);
16724           tree ta = args1;
16725
16726           /* Setup the parameter vector, which contains only ARG1.  */
16727           TREE_VEC_ELT (parmvec, 0) = arg2;
16728
16729           /* Setup the argument vector, which contains the remaining
16730              arguments.  */
16731           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16732             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16733
16734           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16735                                            argvec, UNIFY_ALLOW_NONE, 
16736                                            /*call_args_p=*/false, 
16737                                            /*subr=*/0, /*explain_p=*/false)
16738                      == 0);
16739
16740           /* We cannot deduce in the other direction, because ARG2 is
16741              a pack expansion but ARG1 is not.*/
16742           deduce1 = 0;
16743         }
16744
16745       else
16746         {
16747           /* The normal case, where neither argument is a pack
16748              expansion.  */
16749           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16750                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16751                      == 0);
16752           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16753                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16754                      == 0);
16755         }
16756
16757       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16758          arg2, then arg2 is not as specialized as arg1.  */
16759       if (!deduce1)
16760         lose2 = true;
16761       if (!deduce2)
16762         lose1 = true;
16763
16764       /* "If, for a given type, deduction succeeds in both directions
16765          (i.e., the types are identical after the transformations above)
16766          and if the type from the argument template is more cv-qualified
16767          than the type from the parameter template (as described above)
16768          that type is considered to be more specialized than the other. If
16769          neither type is more cv-qualified than the other then neither type
16770          is more specialized than the other."  */
16771
16772       if (deduce1 && deduce2
16773           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16774         {
16775           if ((quals1 & quals2) == quals2)
16776             lose2 = true;
16777           if ((quals1 & quals2) == quals1)
16778             lose1 = true;
16779         }
16780
16781       if (lose1 && lose2)
16782         /* We've failed to deduce something in either direction.
16783            These must be unordered.  */
16784         break;
16785
16786       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16787           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16788         /* We have already processed all of the arguments in our
16789            handing of the pack expansion type.  */
16790         len = 0;
16791
16792       args1 = TREE_CHAIN (args1);
16793       args2 = TREE_CHAIN (args2);
16794     }
16795
16796   /* "In most cases, all template parameters must have values in order for
16797      deduction to succeed, but for partial ordering purposes a template
16798      parameter may remain without a value provided it is not used in the
16799      types being used for partial ordering."
16800
16801      Thus, if we are missing any of the targs1 we need to substitute into
16802      origs1, then pat2 is not as specialized as pat1.  This can happen when
16803      there is a nondeduced context.  */
16804   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16805     lose2 = true;
16806   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16807     lose1 = true;
16808
16809   processing_template_decl--;
16810
16811   /* All things being equal, if the next argument is a pack expansion
16812      for one function but not for the other, prefer the
16813      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16814   if (lose1 == lose2
16815       && args1 && TREE_VALUE (args1)
16816       && args2 && TREE_VALUE (args2))
16817     {
16818       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16819       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16820     }
16821
16822   if (lose1 == lose2)
16823     return 0;
16824   else if (!lose1)
16825     return 1;
16826   else
16827     return -1;
16828 }
16829
16830 /* Determine which of two partial specializations is more specialized.
16831
16832    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16833    to the first partial specialization.  The TREE_VALUE is the
16834    innermost set of template parameters for the partial
16835    specialization.  PAT2 is similar, but for the second template.
16836
16837    Return 1 if the first partial specialization is more specialized;
16838    -1 if the second is more specialized; 0 if neither is more
16839    specialized.
16840
16841    See [temp.class.order] for information about determining which of
16842    two templates is more specialized.  */
16843
16844 static int
16845 more_specialized_class (tree pat1, tree pat2)
16846 {
16847   tree targs;
16848   tree tmpl1, tmpl2;
16849   int winner = 0;
16850   bool any_deductions = false;
16851
16852   tmpl1 = TREE_TYPE (pat1);
16853   tmpl2 = TREE_TYPE (pat2);
16854
16855   /* Just like what happens for functions, if we are ordering between
16856      different class template specializations, we may encounter dependent
16857      types in the arguments, and we need our dependency check functions
16858      to behave correctly.  */
16859   ++processing_template_decl;
16860   targs = get_class_bindings (TREE_VALUE (pat1),
16861                               CLASSTYPE_TI_ARGS (tmpl1),
16862                               CLASSTYPE_TI_ARGS (tmpl2));
16863   if (targs)
16864     {
16865       --winner;
16866       any_deductions = true;
16867     }
16868
16869   targs = get_class_bindings (TREE_VALUE (pat2),
16870                               CLASSTYPE_TI_ARGS (tmpl2),
16871                               CLASSTYPE_TI_ARGS (tmpl1));
16872   if (targs)
16873     {
16874       ++winner;
16875       any_deductions = true;
16876     }
16877   --processing_template_decl;
16878
16879   /* In the case of a tie where at least one of the class templates
16880      has a parameter pack at the end, the template with the most
16881      non-packed parameters wins.  */
16882   if (winner == 0
16883       && any_deductions
16884       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16885           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16886     {
16887       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16888       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16889       int len1 = TREE_VEC_LENGTH (args1);
16890       int len2 = TREE_VEC_LENGTH (args2);
16891
16892       /* We don't count the pack expansion at the end.  */
16893       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16894         --len1;
16895       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16896         --len2;
16897
16898       if (len1 > len2)
16899         return 1;
16900       else if (len1 < len2)
16901         return -1;
16902     }
16903
16904   return winner;
16905 }
16906
16907 /* Return the template arguments that will produce the function signature
16908    DECL from the function template FN, with the explicit template
16909    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16910    also match.  Return NULL_TREE if no satisfactory arguments could be
16911    found.  */
16912
16913 static tree
16914 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16915 {
16916   int ntparms = DECL_NTPARMS (fn);
16917   tree targs = make_tree_vec (ntparms);
16918   tree decl_type;
16919   tree decl_arg_types;
16920   tree *args;
16921   unsigned int nargs, ix;
16922   tree arg;
16923
16924   /* Substitute the explicit template arguments into the type of DECL.
16925      The call to fn_type_unification will handle substitution into the
16926      FN.  */
16927   decl_type = TREE_TYPE (decl);
16928   if (explicit_args && uses_template_parms (decl_type))
16929     {
16930       tree tmpl;
16931       tree converted_args;
16932
16933       if (DECL_TEMPLATE_INFO (decl))
16934         tmpl = DECL_TI_TEMPLATE (decl);
16935       else
16936         /* We can get here for some invalid specializations.  */
16937         return NULL_TREE;
16938
16939       converted_args
16940         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16941                                  explicit_args, NULL_TREE,
16942                                  tf_none,
16943                                  /*require_all_args=*/false,
16944                                  /*use_default_args=*/false);
16945       if (converted_args == error_mark_node)
16946         return NULL_TREE;
16947
16948       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16949       if (decl_type == error_mark_node)
16950         return NULL_TREE;
16951     }
16952
16953   /* Never do unification on the 'this' parameter.  */
16954   decl_arg_types = skip_artificial_parms_for (decl, 
16955                                               TYPE_ARG_TYPES (decl_type));
16956
16957   nargs = list_length (decl_arg_types);
16958   args = XALLOCAVEC (tree, nargs);
16959   for (arg = decl_arg_types, ix = 0;
16960        arg != NULL_TREE && arg != void_list_node;
16961        arg = TREE_CHAIN (arg), ++ix)
16962     args[ix] = TREE_VALUE (arg);
16963
16964   if (fn_type_unification (fn, explicit_args, targs,
16965                            args, ix,
16966                            (check_rettype || DECL_CONV_FN_P (fn)
16967                             ? TREE_TYPE (decl_type) : NULL_TREE),
16968                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
16969     return NULL_TREE;
16970
16971   return targs;
16972 }
16973
16974 /* Return the innermost template arguments that, when applied to a
16975    template specialization whose innermost template parameters are
16976    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16977    ARGS.
16978
16979    For example, suppose we have:
16980
16981      template <class T, class U> struct S {};
16982      template <class T> struct S<T*, int> {};
16983
16984    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16985    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16986    int}.  The resulting vector will be {double}, indicating that `T'
16987    is bound to `double'.  */
16988
16989 static tree
16990 get_class_bindings (tree tparms, tree spec_args, tree args)
16991 {
16992   int i, ntparms = TREE_VEC_LENGTH (tparms);
16993   tree deduced_args;
16994   tree innermost_deduced_args;
16995
16996   innermost_deduced_args = make_tree_vec (ntparms);
16997   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16998     {
16999       deduced_args = copy_node (args);
17000       SET_TMPL_ARGS_LEVEL (deduced_args,
17001                            TMPL_ARGS_DEPTH (deduced_args),
17002                            innermost_deduced_args);
17003     }
17004   else
17005     deduced_args = innermost_deduced_args;
17006
17007   if (unify (tparms, deduced_args,
17008              INNERMOST_TEMPLATE_ARGS (spec_args),
17009              INNERMOST_TEMPLATE_ARGS (args),
17010              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17011     return NULL_TREE;
17012
17013   for (i =  0; i < ntparms; ++i)
17014     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17015       return NULL_TREE;
17016
17017   /* Verify that nondeduced template arguments agree with the type
17018      obtained from argument deduction.
17019
17020      For example:
17021
17022        struct A { typedef int X; };
17023        template <class T, class U> struct C {};
17024        template <class T> struct C<T, typename T::X> {};
17025
17026      Then with the instantiation `C<A, int>', we can deduce that
17027      `T' is `A' but unify () does not check whether `typename T::X'
17028      is `int'.  */
17029   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17030   if (spec_args == error_mark_node
17031       /* We only need to check the innermost arguments; the other
17032          arguments will always agree.  */
17033       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17034                               INNERMOST_TEMPLATE_ARGS (args)))
17035     return NULL_TREE;
17036
17037   /* Now that we have bindings for all of the template arguments,
17038      ensure that the arguments deduced for the template template
17039      parameters have compatible template parameter lists.  See the use
17040      of template_template_parm_bindings_ok_p in fn_type_unification
17041      for more information.  */
17042   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17043     return NULL_TREE;
17044
17045   return deduced_args;
17046 }
17047
17048 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17049    Return the TREE_LIST node with the most specialized template, if
17050    any.  If there is no most specialized template, the error_mark_node
17051    is returned.
17052
17053    Note that this function does not look at, or modify, the
17054    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17055    returned is one of the elements of INSTANTIATIONS, callers may
17056    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17057    and retrieve it from the value returned.  */
17058
17059 tree
17060 most_specialized_instantiation (tree templates)
17061 {
17062   tree fn, champ;
17063
17064   ++processing_template_decl;
17065
17066   champ = templates;
17067   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17068     {
17069       int fate = 0;
17070
17071       if (get_bindings (TREE_VALUE (champ),
17072                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17073                         NULL_TREE, /*check_ret=*/true))
17074         fate--;
17075
17076       if (get_bindings (TREE_VALUE (fn),
17077                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17078                         NULL_TREE, /*check_ret=*/true))
17079         fate++;
17080
17081       if (fate == -1)
17082         champ = fn;
17083       else if (!fate)
17084         {
17085           /* Equally specialized, move to next function.  If there
17086              is no next function, nothing's most specialized.  */
17087           fn = TREE_CHAIN (fn);
17088           champ = fn;
17089           if (!fn)
17090             break;
17091         }
17092     }
17093
17094   if (champ)
17095     /* Now verify that champ is better than everything earlier in the
17096        instantiation list.  */
17097     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17098       if (get_bindings (TREE_VALUE (champ),
17099                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17100                         NULL_TREE, /*check_ret=*/true)
17101           || !get_bindings (TREE_VALUE (fn),
17102                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17103                             NULL_TREE, /*check_ret=*/true))
17104         {
17105           champ = NULL_TREE;
17106           break;
17107         }
17108
17109   processing_template_decl--;
17110
17111   if (!champ)
17112     return error_mark_node;
17113
17114   return champ;
17115 }
17116
17117 /* If DECL is a specialization of some template, return the most
17118    general such template.  Otherwise, returns NULL_TREE.
17119
17120    For example, given:
17121
17122      template <class T> struct S { template <class U> void f(U); };
17123
17124    if TMPL is `template <class U> void S<int>::f(U)' this will return
17125    the full template.  This function will not trace past partial
17126    specializations, however.  For example, given in addition:
17127
17128      template <class T> struct S<T*> { template <class U> void f(U); };
17129
17130    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17131    `template <class T> template <class U> S<T*>::f(U)'.  */
17132
17133 tree
17134 most_general_template (tree decl)
17135 {
17136   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17137      an immediate specialization.  */
17138   if (TREE_CODE (decl) == FUNCTION_DECL)
17139     {
17140       if (DECL_TEMPLATE_INFO (decl)) {
17141         decl = DECL_TI_TEMPLATE (decl);
17142
17143         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17144            template friend.  */
17145         if (TREE_CODE (decl) != TEMPLATE_DECL)
17146           return NULL_TREE;
17147       } else
17148         return NULL_TREE;
17149     }
17150
17151   /* Look for more and more general templates.  */
17152   while (DECL_TEMPLATE_INFO (decl))
17153     {
17154       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17155          (See cp-tree.h for details.)  */
17156       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17157         break;
17158
17159       if (CLASS_TYPE_P (TREE_TYPE (decl))
17160           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17161         break;
17162
17163       /* Stop if we run into an explicitly specialized class template.  */
17164       if (!DECL_NAMESPACE_SCOPE_P (decl)
17165           && DECL_CONTEXT (decl)
17166           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17167         break;
17168
17169       decl = DECL_TI_TEMPLATE (decl);
17170     }
17171
17172   return decl;
17173 }
17174
17175 /* Return the most specialized of the class template partial
17176    specializations of TMPL which can produce TYPE, a specialization of
17177    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17178    a _TYPE node corresponding to the partial specialization, while the
17179    TREE_PURPOSE is the set of template arguments that must be
17180    substituted into the TREE_TYPE in order to generate TYPE.
17181
17182    If the choice of partial specialization is ambiguous, a diagnostic
17183    is issued, and the error_mark_node is returned.  If there are no
17184    partial specializations of TMPL matching TYPE, then NULL_TREE is
17185    returned.  */
17186
17187 static tree
17188 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17189 {
17190   tree list = NULL_TREE;
17191   tree t;
17192   tree champ;
17193   int fate;
17194   bool ambiguous_p;
17195   tree args;
17196   tree outer_args = NULL_TREE;
17197
17198   tmpl = most_general_template (tmpl);
17199   args = CLASSTYPE_TI_ARGS (type);
17200
17201   /* For determining which partial specialization to use, only the
17202      innermost args are interesting.  */
17203   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17204     {
17205       outer_args = strip_innermost_template_args (args, 1);
17206       args = INNERMOST_TEMPLATE_ARGS (args);
17207     }
17208
17209   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17210     {
17211       tree partial_spec_args;
17212       tree spec_args;
17213       tree parms = TREE_VALUE (t);
17214
17215       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17216
17217       ++processing_template_decl;
17218
17219       if (outer_args)
17220         {
17221           int i;
17222
17223           /* Discard the outer levels of args, and then substitute in the
17224              template args from the enclosing class.  */
17225           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17226           partial_spec_args = tsubst_template_args
17227             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17228
17229           /* PARMS already refers to just the innermost parms, but the
17230              template parms in partial_spec_args had their levels lowered
17231              by tsubst, so we need to do the same for the parm list.  We
17232              can't just tsubst the TREE_VEC itself, as tsubst wants to
17233              treat a TREE_VEC as an argument vector.  */
17234           parms = copy_node (parms);
17235           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17236             TREE_VEC_ELT (parms, i) =
17237               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17238
17239         }
17240
17241       partial_spec_args =
17242           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17243                                  add_to_template_args (outer_args,
17244                                                        partial_spec_args),
17245                                  tmpl, tf_none,
17246                                  /*require_all_args=*/true,
17247                                  /*use_default_args=*/true);
17248
17249       --processing_template_decl;
17250
17251       if (partial_spec_args == error_mark_node)
17252         return error_mark_node;
17253
17254       spec_args = get_class_bindings (parms,
17255                                       partial_spec_args,
17256                                       args);
17257       if (spec_args)
17258         {
17259           if (outer_args)
17260             spec_args = add_to_template_args (outer_args, spec_args);
17261           list = tree_cons (spec_args, TREE_VALUE (t), list);
17262           TREE_TYPE (list) = TREE_TYPE (t);
17263         }
17264     }
17265
17266   if (! list)
17267     return NULL_TREE;
17268
17269   ambiguous_p = false;
17270   t = list;
17271   champ = t;
17272   t = TREE_CHAIN (t);
17273   for (; t; t = TREE_CHAIN (t))
17274     {
17275       fate = more_specialized_class (champ, t);
17276       if (fate == 1)
17277         ;
17278       else
17279         {
17280           if (fate == 0)
17281             {
17282               t = TREE_CHAIN (t);
17283               if (! t)
17284                 {
17285                   ambiguous_p = true;
17286                   break;
17287                 }
17288             }
17289           champ = t;
17290         }
17291     }
17292
17293   if (!ambiguous_p)
17294     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17295       {
17296         fate = more_specialized_class (champ, t);
17297         if (fate != 1)
17298           {
17299             ambiguous_p = true;
17300             break;
17301           }
17302       }
17303
17304   if (ambiguous_p)
17305     {
17306       const char *str;
17307       char *spaces = NULL;
17308       if (!(complain & tf_error))
17309         return error_mark_node;
17310       error ("ambiguous class template instantiation for %q#T", type);
17311       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17312       for (t = list; t; t = TREE_CHAIN (t))
17313         {
17314           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17315           spaces = spaces ? spaces : get_spaces (str);
17316         }
17317       free (spaces);
17318       return error_mark_node;
17319     }
17320
17321   return champ;
17322 }
17323
17324 /* Explicitly instantiate DECL.  */
17325
17326 void
17327 do_decl_instantiation (tree decl, tree storage)
17328 {
17329   tree result = NULL_TREE;
17330   int extern_p = 0;
17331
17332   if (!decl || decl == error_mark_node)
17333     /* An error occurred, for which grokdeclarator has already issued
17334        an appropriate message.  */
17335     return;
17336   else if (! DECL_LANG_SPECIFIC (decl))
17337     {
17338       error ("explicit instantiation of non-template %q#D", decl);
17339       return;
17340     }
17341   else if (TREE_CODE (decl) == VAR_DECL)
17342     {
17343       /* There is an asymmetry here in the way VAR_DECLs and
17344          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17345          the latter, the DECL we get back will be marked as a
17346          template instantiation, and the appropriate
17347          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17348          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17349          should handle VAR_DECLs as it currently handles
17350          FUNCTION_DECLs.  */
17351       if (!DECL_CLASS_SCOPE_P (decl))
17352         {
17353           error ("%qD is not a static data member of a class template", decl);
17354           return;
17355         }
17356       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17357       if (!result || TREE_CODE (result) != VAR_DECL)
17358         {
17359           error ("no matching template for %qD found", decl);
17360           return;
17361         }
17362       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17363         {
17364           error ("type %qT for explicit instantiation %qD does not match "
17365                  "declared type %qT", TREE_TYPE (result), decl,
17366                  TREE_TYPE (decl));
17367           return;
17368         }
17369     }
17370   else if (TREE_CODE (decl) != FUNCTION_DECL)
17371     {
17372       error ("explicit instantiation of %q#D", decl);
17373       return;
17374     }
17375   else
17376     result = decl;
17377
17378   /* Check for various error cases.  Note that if the explicit
17379      instantiation is valid the RESULT will currently be marked as an
17380      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17381      until we get here.  */
17382
17383   if (DECL_TEMPLATE_SPECIALIZATION (result))
17384     {
17385       /* DR 259 [temp.spec].
17386
17387          Both an explicit instantiation and a declaration of an explicit
17388          specialization shall not appear in a program unless the explicit
17389          instantiation follows a declaration of the explicit specialization.
17390
17391          For a given set of template parameters, if an explicit
17392          instantiation of a template appears after a declaration of an
17393          explicit specialization for that template, the explicit
17394          instantiation has no effect.  */
17395       return;
17396     }
17397   else if (DECL_EXPLICIT_INSTANTIATION (result))
17398     {
17399       /* [temp.spec]
17400
17401          No program shall explicitly instantiate any template more
17402          than once.
17403
17404          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17405          the first instantiation was `extern' and the second is not,
17406          and EXTERN_P for the opposite case.  */
17407       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17408         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17409       /* If an "extern" explicit instantiation follows an ordinary
17410          explicit instantiation, the template is instantiated.  */
17411       if (extern_p)
17412         return;
17413     }
17414   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17415     {
17416       error ("no matching template for %qD found", result);
17417       return;
17418     }
17419   else if (!DECL_TEMPLATE_INFO (result))
17420     {
17421       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17422       return;
17423     }
17424
17425   if (storage == NULL_TREE)
17426     ;
17427   else if (storage == ridpointers[(int) RID_EXTERN])
17428     {
17429       if (!in_system_header && (cxx_dialect == cxx98))
17430         pedwarn (input_location, OPT_pedantic, 
17431                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17432                  "instantiations");
17433       extern_p = 1;
17434     }
17435   else
17436     error ("storage class %qD applied to template instantiation", storage);
17437
17438   check_explicit_instantiation_namespace (result);
17439   mark_decl_instantiated (result, extern_p);
17440   if (! extern_p)
17441     instantiate_decl (result, /*defer_ok=*/1,
17442                       /*expl_inst_class_mem_p=*/false);
17443 }
17444
17445 static void
17446 mark_class_instantiated (tree t, int extern_p)
17447 {
17448   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17449   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17450   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17451   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17452   if (! extern_p)
17453     {
17454       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17455       rest_of_type_compilation (t, 1);
17456     }
17457 }
17458
17459 /* Called from do_type_instantiation through binding_table_foreach to
17460    do recursive instantiation for the type bound in ENTRY.  */
17461 static void
17462 bt_instantiate_type_proc (binding_entry entry, void *data)
17463 {
17464   tree storage = *(tree *) data;
17465
17466   if (MAYBE_CLASS_TYPE_P (entry->type)
17467       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17468     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17469 }
17470
17471 /* Called from do_type_instantiation to instantiate a member
17472    (a member function or a static member variable) of an
17473    explicitly instantiated class template.  */
17474 static void
17475 instantiate_class_member (tree decl, int extern_p)
17476 {
17477   mark_decl_instantiated (decl, extern_p);
17478   if (! extern_p)
17479     instantiate_decl (decl, /*defer_ok=*/1,
17480                       /*expl_inst_class_mem_p=*/true);
17481 }
17482
17483 /* Perform an explicit instantiation of template class T.  STORAGE, if
17484    non-null, is the RID for extern, inline or static.  COMPLAIN is
17485    nonzero if this is called from the parser, zero if called recursively,
17486    since the standard is unclear (as detailed below).  */
17487
17488 void
17489 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17490 {
17491   int extern_p = 0;
17492   int nomem_p = 0;
17493   int static_p = 0;
17494   int previous_instantiation_extern_p = 0;
17495
17496   if (TREE_CODE (t) == TYPE_DECL)
17497     t = TREE_TYPE (t);
17498
17499   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17500     {
17501       error ("explicit instantiation of non-template type %qT", t);
17502       return;
17503     }
17504
17505   complete_type (t);
17506
17507   if (!COMPLETE_TYPE_P (t))
17508     {
17509       if (complain & tf_error)
17510         error ("explicit instantiation of %q#T before definition of template",
17511                t);
17512       return;
17513     }
17514
17515   if (storage != NULL_TREE)
17516     {
17517       if (!in_system_header)
17518         {
17519           if (storage == ridpointers[(int) RID_EXTERN])
17520             {
17521               if (cxx_dialect == cxx98)
17522                 pedwarn (input_location, OPT_pedantic, 
17523                          "ISO C++ 1998 forbids the use of %<extern%> on "
17524                          "explicit instantiations");
17525             }
17526           else
17527             pedwarn (input_location, OPT_pedantic, 
17528                      "ISO C++ forbids the use of %qE"
17529                      " on explicit instantiations", storage);
17530         }
17531
17532       if (storage == ridpointers[(int) RID_INLINE])
17533         nomem_p = 1;
17534       else if (storage == ridpointers[(int) RID_EXTERN])
17535         extern_p = 1;
17536       else if (storage == ridpointers[(int) RID_STATIC])
17537         static_p = 1;
17538       else
17539         {
17540           error ("storage class %qD applied to template instantiation",
17541                  storage);
17542           extern_p = 0;
17543         }
17544     }
17545
17546   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17547     {
17548       /* DR 259 [temp.spec].
17549
17550          Both an explicit instantiation and a declaration of an explicit
17551          specialization shall not appear in a program unless the explicit
17552          instantiation follows a declaration of the explicit specialization.
17553
17554          For a given set of template parameters, if an explicit
17555          instantiation of a template appears after a declaration of an
17556          explicit specialization for that template, the explicit
17557          instantiation has no effect.  */
17558       return;
17559     }
17560   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17561     {
17562       /* [temp.spec]
17563
17564          No program shall explicitly instantiate any template more
17565          than once.
17566
17567          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17568          instantiation was `extern'.  If EXTERN_P then the second is.
17569          These cases are OK.  */
17570       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17571
17572       if (!previous_instantiation_extern_p && !extern_p
17573           && (complain & tf_error))
17574         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17575
17576       /* If we've already instantiated the template, just return now.  */
17577       if (!CLASSTYPE_INTERFACE_ONLY (t))
17578         return;
17579     }
17580
17581   check_explicit_instantiation_namespace (TYPE_NAME (t));
17582   mark_class_instantiated (t, extern_p);
17583
17584   if (nomem_p)
17585     return;
17586
17587   {
17588     tree tmp;
17589
17590     /* In contrast to implicit instantiation, where only the
17591        declarations, and not the definitions, of members are
17592        instantiated, we have here:
17593
17594          [temp.explicit]
17595
17596          The explicit instantiation of a class template specialization
17597          implies the instantiation of all of its members not
17598          previously explicitly specialized in the translation unit
17599          containing the explicit instantiation.
17600
17601        Of course, we can't instantiate member template classes, since
17602        we don't have any arguments for them.  Note that the standard
17603        is unclear on whether the instantiation of the members are
17604        *explicit* instantiations or not.  However, the most natural
17605        interpretation is that it should be an explicit instantiation.  */
17606
17607     if (! static_p)
17608       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17609         if (TREE_CODE (tmp) == FUNCTION_DECL
17610             && DECL_TEMPLATE_INSTANTIATION (tmp))
17611           instantiate_class_member (tmp, extern_p);
17612
17613     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17614       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17615         instantiate_class_member (tmp, extern_p);
17616
17617     if (CLASSTYPE_NESTED_UTDS (t))
17618       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17619                              bt_instantiate_type_proc, &storage);
17620   }
17621 }
17622
17623 /* Given a function DECL, which is a specialization of TMPL, modify
17624    DECL to be a re-instantiation of TMPL with the same template
17625    arguments.  TMPL should be the template into which tsubst'ing
17626    should occur for DECL, not the most general template.
17627
17628    One reason for doing this is a scenario like this:
17629
17630      template <class T>
17631      void f(const T&, int i);
17632
17633      void g() { f(3, 7); }
17634
17635      template <class T>
17636      void f(const T& t, const int i) { }
17637
17638    Note that when the template is first instantiated, with
17639    instantiate_template, the resulting DECL will have no name for the
17640    first parameter, and the wrong type for the second.  So, when we go
17641    to instantiate the DECL, we regenerate it.  */
17642
17643 static void
17644 regenerate_decl_from_template (tree decl, tree tmpl)
17645 {
17646   /* The arguments used to instantiate DECL, from the most general
17647      template.  */
17648   tree args;
17649   tree code_pattern;
17650
17651   args = DECL_TI_ARGS (decl);
17652   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17653
17654   /* Make sure that we can see identifiers, and compute access
17655      correctly.  */
17656   push_access_scope (decl);
17657
17658   if (TREE_CODE (decl) == FUNCTION_DECL)
17659     {
17660       tree decl_parm;
17661       tree pattern_parm;
17662       tree specs;
17663       int args_depth;
17664       int parms_depth;
17665
17666       args_depth = TMPL_ARGS_DEPTH (args);
17667       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17668       if (args_depth > parms_depth)
17669         args = get_innermost_template_args (args, parms_depth);
17670
17671       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17672                                               args, tf_error, NULL_TREE,
17673                                               /*defer_ok*/false);
17674       if (specs)
17675         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17676                                                     specs);
17677
17678       /* Merge parameter declarations.  */
17679       decl_parm = skip_artificial_parms_for (decl,
17680                                              DECL_ARGUMENTS (decl));
17681       pattern_parm
17682         = skip_artificial_parms_for (code_pattern,
17683                                      DECL_ARGUMENTS (code_pattern));
17684       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17685         {
17686           tree parm_type;
17687           tree attributes;
17688           
17689           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17690             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17691           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17692                               NULL_TREE);
17693           parm_type = type_decays_to (parm_type);
17694           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17695             TREE_TYPE (decl_parm) = parm_type;
17696           attributes = DECL_ATTRIBUTES (pattern_parm);
17697           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17698             {
17699               DECL_ATTRIBUTES (decl_parm) = attributes;
17700               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17701             }
17702           decl_parm = DECL_CHAIN (decl_parm);
17703           pattern_parm = DECL_CHAIN (pattern_parm);
17704         }
17705       /* Merge any parameters that match with the function parameter
17706          pack.  */
17707       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17708         {
17709           int i, len;
17710           tree expanded_types;
17711           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17712              the parameters in this function parameter pack.  */
17713           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17714                                                  args, tf_error, NULL_TREE);
17715           len = TREE_VEC_LENGTH (expanded_types);
17716           for (i = 0; i < len; i++)
17717             {
17718               tree parm_type;
17719               tree attributes;
17720           
17721               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17722                 /* Rename the parameter to include the index.  */
17723                 DECL_NAME (decl_parm) = 
17724                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17725               parm_type = TREE_VEC_ELT (expanded_types, i);
17726               parm_type = type_decays_to (parm_type);
17727               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17728                 TREE_TYPE (decl_parm) = parm_type;
17729               attributes = DECL_ATTRIBUTES (pattern_parm);
17730               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17731                 {
17732                   DECL_ATTRIBUTES (decl_parm) = attributes;
17733                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17734                 }
17735               decl_parm = DECL_CHAIN (decl_parm);
17736             }
17737         }
17738       /* Merge additional specifiers from the CODE_PATTERN.  */
17739       if (DECL_DECLARED_INLINE_P (code_pattern)
17740           && !DECL_DECLARED_INLINE_P (decl))
17741         DECL_DECLARED_INLINE_P (decl) = 1;
17742     }
17743   else if (TREE_CODE (decl) == VAR_DECL)
17744     {
17745       DECL_INITIAL (decl) =
17746         tsubst_expr (DECL_INITIAL (code_pattern), args,
17747                      tf_error, DECL_TI_TEMPLATE (decl),
17748                      /*integral_constant_expression_p=*/false);
17749       if (VAR_HAD_UNKNOWN_BOUND (decl))
17750         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17751                                    tf_error, DECL_TI_TEMPLATE (decl));
17752     }
17753   else
17754     gcc_unreachable ();
17755
17756   pop_access_scope (decl);
17757 }
17758
17759 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17760    substituted to get DECL.  */
17761
17762 tree
17763 template_for_substitution (tree decl)
17764 {
17765   tree tmpl = DECL_TI_TEMPLATE (decl);
17766
17767   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17768      for the instantiation.  This is not always the most general
17769      template.  Consider, for example:
17770
17771         template <class T>
17772         struct S { template <class U> void f();
17773                    template <> void f<int>(); };
17774
17775      and an instantiation of S<double>::f<int>.  We want TD to be the
17776      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17777   while (/* An instantiation cannot have a definition, so we need a
17778             more general template.  */
17779          DECL_TEMPLATE_INSTANTIATION (tmpl)
17780            /* We must also deal with friend templates.  Given:
17781
17782                 template <class T> struct S {
17783                   template <class U> friend void f() {};
17784                 };
17785
17786               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17787               so far as the language is concerned, but that's still
17788               where we get the pattern for the instantiation from.  On
17789               other hand, if the definition comes outside the class, say:
17790
17791                 template <class T> struct S {
17792                   template <class U> friend void f();
17793                 };
17794                 template <class U> friend void f() {}
17795
17796               we don't need to look any further.  That's what the check for
17797               DECL_INITIAL is for.  */
17798           || (TREE_CODE (decl) == FUNCTION_DECL
17799               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17800               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17801     {
17802       /* The present template, TD, should not be a definition.  If it
17803          were a definition, we should be using it!  Note that we
17804          cannot restructure the loop to just keep going until we find
17805          a template with a definition, since that might go too far if
17806          a specialization was declared, but not defined.  */
17807       gcc_assert (TREE_CODE (decl) != VAR_DECL
17808                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17809
17810       /* Fetch the more general template.  */
17811       tmpl = DECL_TI_TEMPLATE (tmpl);
17812     }
17813
17814   return tmpl;
17815 }
17816
17817 /* Returns true if we need to instantiate this template instance even if we
17818    know we aren't going to emit it..  */
17819
17820 bool
17821 always_instantiate_p (tree decl)
17822 {
17823   /* We always instantiate inline functions so that we can inline them.  An
17824      explicit instantiation declaration prohibits implicit instantiation of
17825      non-inline functions.  With high levels of optimization, we would
17826      normally inline non-inline functions -- but we're not allowed to do
17827      that for "extern template" functions.  Therefore, we check
17828      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17829   return ((TREE_CODE (decl) == FUNCTION_DECL
17830            && DECL_DECLARED_INLINE_P (decl))
17831           /* And we need to instantiate static data members so that
17832              their initializers are available in integral constant
17833              expressions.  */
17834           || (TREE_CODE (decl) == VAR_DECL
17835               && decl_maybe_constant_var_p (decl)));
17836 }
17837
17838 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17839    instantiate it now, modifying TREE_TYPE (fn).  */
17840
17841 void
17842 maybe_instantiate_noexcept (tree fn)
17843 {
17844   tree fntype, spec, noex, clone;
17845
17846   if (DECL_CLONED_FUNCTION_P (fn))
17847     fn = DECL_CLONED_FUNCTION (fn);
17848   fntype = TREE_TYPE (fn);
17849   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17850
17851   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17852     return;
17853
17854   noex = TREE_PURPOSE (spec);
17855
17856   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17857     {
17858       push_tinst_level (fn);
17859       push_access_scope (fn);
17860       input_location = DECL_SOURCE_LOCATION (fn);
17861       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17862                                     DEFERRED_NOEXCEPT_ARGS (noex),
17863                                     tf_warning_or_error, fn, /*function_p=*/false,
17864                                     /*integral_constant_expression_p=*/true);
17865       pop_access_scope (fn);
17866       pop_tinst_level ();
17867       spec = build_noexcept_spec (noex, tf_warning_or_error);
17868       if (spec == error_mark_node)
17869         spec = noexcept_false_spec;
17870     }
17871   else
17872     {
17873       /* This is an implicitly declared function, so NOEX is a list of
17874          other functions to evaluate and merge.  */
17875       tree elt;
17876       spec = noexcept_true_spec;
17877       for (elt = noex; elt; elt = OVL_NEXT (elt))
17878         {
17879           tree fn = OVL_CURRENT (elt);
17880           tree subspec;
17881           maybe_instantiate_noexcept (fn);
17882           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17883           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17884         }
17885     }
17886
17887   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17888
17889   FOR_EACH_CLONE (clone, fn)
17890     {
17891       if (TREE_TYPE (clone) == fntype)
17892         TREE_TYPE (clone) = TREE_TYPE (fn);
17893       else
17894         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
17895     }
17896 }
17897
17898 /* Produce the definition of D, a _DECL generated from a template.  If
17899    DEFER_OK is nonzero, then we don't have to actually do the
17900    instantiation now; we just have to do it sometime.  Normally it is
17901    an error if this is an explicit instantiation but D is undefined.
17902    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17903    explicitly instantiated class template.  */
17904
17905 tree
17906 instantiate_decl (tree d, int defer_ok,
17907                   bool expl_inst_class_mem_p)
17908 {
17909   tree tmpl = DECL_TI_TEMPLATE (d);
17910   tree gen_args;
17911   tree args;
17912   tree td;
17913   tree code_pattern;
17914   tree spec;
17915   tree gen_tmpl;
17916   bool pattern_defined;
17917   int need_push;
17918   location_t saved_loc = input_location;
17919   bool external_p;
17920
17921   /* This function should only be used to instantiate templates for
17922      functions and static member variables.  */
17923   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17924               || TREE_CODE (d) == VAR_DECL);
17925
17926   /* Variables are never deferred; if instantiation is required, they
17927      are instantiated right away.  That allows for better code in the
17928      case that an expression refers to the value of the variable --
17929      if the variable has a constant value the referring expression can
17930      take advantage of that fact.  */
17931   if (TREE_CODE (d) == VAR_DECL
17932       || DECL_DECLARED_CONSTEXPR_P (d))
17933     defer_ok = 0;
17934
17935   /* Don't instantiate cloned functions.  Instead, instantiate the
17936      functions they cloned.  */
17937   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17938     d = DECL_CLONED_FUNCTION (d);
17939
17940   if (DECL_TEMPLATE_INSTANTIATED (d)
17941       || DECL_TEMPLATE_SPECIALIZATION (d))
17942     /* D has already been instantiated or explicitly specialized, so
17943        there's nothing for us to do here.
17944
17945        It might seem reasonable to check whether or not D is an explicit
17946        instantiation, and, if so, stop here.  But when an explicit
17947        instantiation is deferred until the end of the compilation,
17948        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17949        the instantiation.  */
17950     return d;
17951
17952   /* Check to see whether we know that this template will be
17953      instantiated in some other file, as with "extern template"
17954      extension.  */
17955   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17956
17957   /* In general, we do not instantiate such templates.  */
17958   if (external_p && !always_instantiate_p (d))
17959     return d;
17960
17961   gen_tmpl = most_general_template (tmpl);
17962   gen_args = DECL_TI_ARGS (d);
17963
17964   if (tmpl != gen_tmpl)
17965     /* We should already have the extra args.  */
17966     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17967                 == TMPL_ARGS_DEPTH (gen_args));
17968   /* And what's in the hash table should match D.  */
17969   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17970               || spec == NULL_TREE);
17971
17972   /* This needs to happen before any tsubsting.  */
17973   if (! push_tinst_level (d))
17974     return d;
17975
17976   timevar_push (TV_TEMPLATE_INST);
17977
17978   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17979      for the instantiation.  */
17980   td = template_for_substitution (d);
17981   code_pattern = DECL_TEMPLATE_RESULT (td);
17982
17983   /* We should never be trying to instantiate a member of a class
17984      template or partial specialization.  */
17985   gcc_assert (d != code_pattern);
17986
17987   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17988       || DECL_TEMPLATE_SPECIALIZATION (td))
17989     /* In the case of a friend template whose definition is provided
17990        outside the class, we may have too many arguments.  Drop the
17991        ones we don't need.  The same is true for specializations.  */
17992     args = get_innermost_template_args
17993       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17994   else
17995     args = gen_args;
17996
17997   if (TREE_CODE (d) == FUNCTION_DECL)
17998     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
17999                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18000   else
18001     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18002
18003   /* We may be in the middle of deferred access check.  Disable it now.  */
18004   push_deferring_access_checks (dk_no_deferred);
18005
18006   /* Unless an explicit instantiation directive has already determined
18007      the linkage of D, remember that a definition is available for
18008      this entity.  */
18009   if (pattern_defined
18010       && !DECL_INTERFACE_KNOWN (d)
18011       && !DECL_NOT_REALLY_EXTERN (d))
18012     mark_definable (d);
18013
18014   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18015   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18016   input_location = DECL_SOURCE_LOCATION (d);
18017
18018   /* If D is a member of an explicitly instantiated class template,
18019      and no definition is available, treat it like an implicit
18020      instantiation.  */
18021   if (!pattern_defined && expl_inst_class_mem_p
18022       && DECL_EXPLICIT_INSTANTIATION (d))
18023     {
18024       /* Leave linkage flags alone on instantiations with anonymous
18025          visibility.  */
18026       if (TREE_PUBLIC (d))
18027         {
18028           DECL_NOT_REALLY_EXTERN (d) = 0;
18029           DECL_INTERFACE_KNOWN (d) = 0;
18030         }
18031       SET_DECL_IMPLICIT_INSTANTIATION (d);
18032     }
18033
18034   if (TREE_CODE (d) == FUNCTION_DECL)
18035     maybe_instantiate_noexcept (d);
18036
18037   /* Recheck the substitutions to obtain any warning messages
18038      about ignoring cv qualifiers.  Don't do this for artificial decls,
18039      as it breaks the context-sensitive substitution for lambda op(). */
18040   if (!defer_ok && !DECL_ARTIFICIAL (d))
18041     {
18042       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18043       tree type = TREE_TYPE (gen);
18044
18045       /* Make sure that we can see identifiers, and compute access
18046          correctly.  D is already the target FUNCTION_DECL with the
18047          right context.  */
18048       push_access_scope (d);
18049
18050       if (TREE_CODE (gen) == FUNCTION_DECL)
18051         {
18052           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18053           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18054                                           d, /*defer_ok*/true);
18055           /* Don't simply tsubst the function type, as that will give
18056              duplicate warnings about poor parameter qualifications.
18057              The function arguments are the same as the decl_arguments
18058              without the top level cv qualifiers.  */
18059           type = TREE_TYPE (type);
18060         }
18061       tsubst (type, gen_args, tf_warning_or_error, d);
18062
18063       pop_access_scope (d);
18064     }
18065
18066   /* Defer all other templates, unless we have been explicitly
18067      forbidden from doing so.  */
18068   if (/* If there is no definition, we cannot instantiate the
18069          template.  */
18070       ! pattern_defined
18071       /* If it's OK to postpone instantiation, do so.  */
18072       || defer_ok
18073       /* If this is a static data member that will be defined
18074          elsewhere, we don't want to instantiate the entire data
18075          member, but we do want to instantiate the initializer so that
18076          we can substitute that elsewhere.  */
18077       || (external_p && TREE_CODE (d) == VAR_DECL))
18078     {
18079       /* The definition of the static data member is now required so
18080          we must substitute the initializer.  */
18081       if (TREE_CODE (d) == VAR_DECL
18082           && !DECL_INITIAL (d)
18083           && DECL_INITIAL (code_pattern))
18084         {
18085           tree ns;
18086           tree init;
18087           bool const_init = false;
18088
18089           ns = decl_namespace_context (d);
18090           push_nested_namespace (ns);
18091           push_nested_class (DECL_CONTEXT (d));
18092           init = tsubst_expr (DECL_INITIAL (code_pattern),
18093                               args,
18094                               tf_warning_or_error, NULL_TREE,
18095                               /*integral_constant_expression_p=*/false);
18096           /* Make sure the initializer is still constant, in case of
18097              circular dependency (template/instantiate6.C). */
18098           const_init
18099             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18100           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18101                           /*asmspec_tree=*/NULL_TREE,
18102                           LOOKUP_ONLYCONVERTING);
18103           pop_nested_class ();
18104           pop_nested_namespace (ns);
18105         }
18106
18107       /* We restore the source position here because it's used by
18108          add_pending_template.  */
18109       input_location = saved_loc;
18110
18111       if (at_eof && !pattern_defined
18112           && DECL_EXPLICIT_INSTANTIATION (d)
18113           && DECL_NOT_REALLY_EXTERN (d))
18114         /* [temp.explicit]
18115
18116            The definition of a non-exported function template, a
18117            non-exported member function template, or a non-exported
18118            member function or static data member of a class template
18119            shall be present in every translation unit in which it is
18120            explicitly instantiated.  */
18121         permerror (input_location,  "explicit instantiation of %qD "
18122                    "but no definition available", d);
18123
18124       /* If we're in unevaluated context, we just wanted to get the
18125          constant value; this isn't an odr use, so don't queue
18126          a full instantiation.  */
18127       if (cp_unevaluated_operand != 0)
18128         goto out;
18129       /* ??? Historically, we have instantiated inline functions, even
18130          when marked as "extern template".  */
18131       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18132         add_pending_template (d);
18133       goto out;
18134     }
18135   /* Tell the repository that D is available in this translation unit
18136      -- and see if it is supposed to be instantiated here.  */
18137   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18138     {
18139       /* In a PCH file, despite the fact that the repository hasn't
18140          requested instantiation in the PCH it is still possible that
18141          an instantiation will be required in a file that includes the
18142          PCH.  */
18143       if (pch_file)
18144         add_pending_template (d);
18145       /* Instantiate inline functions so that the inliner can do its
18146          job, even though we'll not be emitting a copy of this
18147          function.  */
18148       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18149         goto out;
18150     }
18151
18152   need_push = !cfun || !global_bindings_p ();
18153   if (need_push)
18154     push_to_top_level ();
18155
18156   /* Mark D as instantiated so that recursive calls to
18157      instantiate_decl do not try to instantiate it again.  */
18158   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18159
18160   /* Regenerate the declaration in case the template has been modified
18161      by a subsequent redeclaration.  */
18162   regenerate_decl_from_template (d, td);
18163
18164   /* We already set the file and line above.  Reset them now in case
18165      they changed as a result of calling regenerate_decl_from_template.  */
18166   input_location = DECL_SOURCE_LOCATION (d);
18167
18168   if (TREE_CODE (d) == VAR_DECL)
18169     {
18170       tree init;
18171       bool const_init = false;
18172
18173       /* Clear out DECL_RTL; whatever was there before may not be right
18174          since we've reset the type of the declaration.  */
18175       SET_DECL_RTL (d, NULL);
18176       DECL_IN_AGGR_P (d) = 0;
18177
18178       /* The initializer is placed in DECL_INITIAL by
18179          regenerate_decl_from_template so we don't need to
18180          push/pop_access_scope again here.  Pull it out so that
18181          cp_finish_decl can process it.  */
18182       init = DECL_INITIAL (d);
18183       DECL_INITIAL (d) = NULL_TREE;
18184       DECL_INITIALIZED_P (d) = 0;
18185
18186       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18187          initializer.  That function will defer actual emission until
18188          we have a chance to determine linkage.  */
18189       DECL_EXTERNAL (d) = 0;
18190
18191       /* Enter the scope of D so that access-checking works correctly.  */
18192       push_nested_class (DECL_CONTEXT (d));
18193       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18194       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18195       pop_nested_class ();
18196     }
18197   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18198     synthesize_method (d);
18199   else if (TREE_CODE (d) == FUNCTION_DECL)
18200     {
18201       htab_t saved_local_specializations;
18202       tree subst_decl;
18203       tree tmpl_parm;
18204       tree spec_parm;
18205
18206       /* Save away the current list, in case we are instantiating one
18207          template from within the body of another.  */
18208       saved_local_specializations = local_specializations;
18209
18210       /* Set up the list of local specializations.  */
18211       local_specializations = htab_create (37,
18212                                            hash_local_specialization,
18213                                            eq_local_specializations,
18214                                            NULL);
18215
18216       /* Set up context.  */
18217       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18218
18219       /* Create substitution entries for the parameters.  */
18220       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18221       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18222       spec_parm = DECL_ARGUMENTS (d);
18223       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18224         {
18225           register_local_specialization (spec_parm, tmpl_parm);
18226           spec_parm = skip_artificial_parms_for (d, spec_parm);
18227           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18228         }
18229       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18230         {
18231           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18232             {
18233               register_local_specialization (spec_parm, tmpl_parm);
18234               spec_parm = DECL_CHAIN (spec_parm);
18235             }
18236           else
18237             {
18238               /* Register the (value) argument pack as a specialization of
18239                  TMPL_PARM, then move on.  */
18240               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18241               register_local_specialization (argpack, tmpl_parm);
18242             }
18243         }
18244       gcc_assert (!spec_parm);
18245
18246       /* Substitute into the body of the function.  */
18247       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18248                    tf_warning_or_error, tmpl,
18249                    /*integral_constant_expression_p=*/false);
18250
18251       /* Set the current input_location to the end of the function
18252          so that finish_function knows where we are.  */
18253       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18254
18255       /* We don't need the local specializations any more.  */
18256       htab_delete (local_specializations);
18257       local_specializations = saved_local_specializations;
18258
18259       /* Finish the function.  */
18260       d = finish_function (0);
18261       expand_or_defer_fn (d);
18262     }
18263
18264   /* We're not deferring instantiation any more.  */
18265   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18266
18267   if (need_push)
18268     pop_from_top_level ();
18269
18270 out:
18271   input_location = saved_loc;
18272   pop_deferring_access_checks ();
18273   pop_tinst_level ();
18274
18275   timevar_pop (TV_TEMPLATE_INST);
18276
18277   return d;
18278 }
18279
18280 /* Run through the list of templates that we wish we could
18281    instantiate, and instantiate any we can.  RETRIES is the
18282    number of times we retry pending template instantiation.  */
18283
18284 void
18285 instantiate_pending_templates (int retries)
18286 {
18287   int reconsider;
18288   location_t saved_loc = input_location;
18289
18290   /* Instantiating templates may trigger vtable generation.  This in turn
18291      may require further template instantiations.  We place a limit here
18292      to avoid infinite loop.  */
18293   if (pending_templates && retries >= max_tinst_depth)
18294     {
18295       tree decl = pending_templates->tinst->decl;
18296
18297       error ("template instantiation depth exceeds maximum of %d"
18298              " instantiating %q+D, possibly from virtual table generation"
18299              " (use -ftemplate-depth= to increase the maximum)",
18300              max_tinst_depth, decl);
18301       if (TREE_CODE (decl) == FUNCTION_DECL)
18302         /* Pretend that we defined it.  */
18303         DECL_INITIAL (decl) = error_mark_node;
18304       return;
18305     }
18306
18307   do
18308     {
18309       struct pending_template **t = &pending_templates;
18310       struct pending_template *last = NULL;
18311       reconsider = 0;
18312       while (*t)
18313         {
18314           tree instantiation = reopen_tinst_level ((*t)->tinst);
18315           bool complete = false;
18316
18317           if (TYPE_P (instantiation))
18318             {
18319               tree fn;
18320
18321               if (!COMPLETE_TYPE_P (instantiation))
18322                 {
18323                   instantiate_class_template (instantiation);
18324                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18325                     for (fn = TYPE_METHODS (instantiation);
18326                          fn;
18327                          fn = TREE_CHAIN (fn))
18328                       if (! DECL_ARTIFICIAL (fn))
18329                         instantiate_decl (fn,
18330                                           /*defer_ok=*/0,
18331                                           /*expl_inst_class_mem_p=*/false);
18332                   if (COMPLETE_TYPE_P (instantiation))
18333                     reconsider = 1;
18334                 }
18335
18336               complete = COMPLETE_TYPE_P (instantiation);
18337             }
18338           else
18339             {
18340               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18341                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18342                 {
18343                   instantiation
18344                     = instantiate_decl (instantiation,
18345                                         /*defer_ok=*/0,
18346                                         /*expl_inst_class_mem_p=*/false);
18347                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18348                     reconsider = 1;
18349                 }
18350
18351               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18352                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18353             }
18354
18355           if (complete)
18356             /* If INSTANTIATION has been instantiated, then we don't
18357                need to consider it again in the future.  */
18358             *t = (*t)->next;
18359           else
18360             {
18361               last = *t;
18362               t = &(*t)->next;
18363             }
18364           tinst_depth = 0;
18365           current_tinst_level = NULL;
18366         }
18367       last_pending_template = last;
18368     }
18369   while (reconsider);
18370
18371   input_location = saved_loc;
18372 }
18373
18374 /* Substitute ARGVEC into T, which is a list of initializers for
18375    either base class or a non-static data member.  The TREE_PURPOSEs
18376    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18377    instantiate_decl.  */
18378
18379 static tree
18380 tsubst_initializer_list (tree t, tree argvec)
18381 {
18382   tree inits = NULL_TREE;
18383
18384   for (; t; t = TREE_CHAIN (t))
18385     {
18386       tree decl;
18387       tree init;
18388       tree expanded_bases = NULL_TREE;
18389       tree expanded_arguments = NULL_TREE;
18390       int i, len = 1;
18391
18392       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18393         {
18394           tree expr;
18395           tree arg;
18396
18397           /* Expand the base class expansion type into separate base
18398              classes.  */
18399           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18400                                                  tf_warning_or_error,
18401                                                  NULL_TREE);
18402           if (expanded_bases == error_mark_node)
18403             continue;
18404           
18405           /* We'll be building separate TREE_LISTs of arguments for
18406              each base.  */
18407           len = TREE_VEC_LENGTH (expanded_bases);
18408           expanded_arguments = make_tree_vec (len);
18409           for (i = 0; i < len; i++)
18410             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18411
18412           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18413              expand each argument in the TREE_VALUE of t.  */
18414           expr = make_node (EXPR_PACK_EXPANSION);
18415           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18416             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18417
18418           if (TREE_VALUE (t) == void_type_node)
18419             /* VOID_TYPE_NODE is used to indicate
18420                value-initialization.  */
18421             {
18422               for (i = 0; i < len; i++)
18423                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18424             }
18425           else
18426             {
18427               /* Substitute parameter packs into each argument in the
18428                  TREE_LIST.  */
18429               in_base_initializer = 1;
18430               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18431                 {
18432                   tree expanded_exprs;
18433
18434                   /* Expand the argument.  */
18435                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18436                   expanded_exprs 
18437                     = tsubst_pack_expansion (expr, argvec,
18438                                              tf_warning_or_error,
18439                                              NULL_TREE);
18440                   if (expanded_exprs == error_mark_node)
18441                     continue;
18442
18443                   /* Prepend each of the expanded expressions to the
18444                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18445                   for (i = 0; i < len; i++)
18446                     {
18447                       TREE_VEC_ELT (expanded_arguments, i) = 
18448                         tree_cons (NULL_TREE, 
18449                                    TREE_VEC_ELT (expanded_exprs, i),
18450                                    TREE_VEC_ELT (expanded_arguments, i));
18451                     }
18452                 }
18453               in_base_initializer = 0;
18454
18455               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18456                  since we built them backwards.  */
18457               for (i = 0; i < len; i++)
18458                 {
18459                   TREE_VEC_ELT (expanded_arguments, i) = 
18460                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18461                 }
18462             }
18463         }
18464
18465       for (i = 0; i < len; ++i)
18466         {
18467           if (expanded_bases)
18468             {
18469               decl = TREE_VEC_ELT (expanded_bases, i);
18470               decl = expand_member_init (decl);
18471               init = TREE_VEC_ELT (expanded_arguments, i);
18472             }
18473           else
18474             {
18475               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18476                                   tf_warning_or_error, NULL_TREE);
18477
18478               decl = expand_member_init (decl);
18479               if (decl && !DECL_P (decl))
18480                 in_base_initializer = 1;
18481
18482               init = TREE_VALUE (t);
18483               if (init != void_type_node)
18484                 init = tsubst_expr (init, argvec,
18485                                     tf_warning_or_error, NULL_TREE,
18486                                     /*integral_constant_expression_p=*/false);
18487               in_base_initializer = 0;
18488             }
18489
18490           if (decl)
18491             {
18492               init = build_tree_list (decl, init);
18493               TREE_CHAIN (init) = inits;
18494               inits = init;
18495             }
18496         }
18497     }
18498   return inits;
18499 }
18500
18501 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18502
18503 static void
18504 set_current_access_from_decl (tree decl)
18505 {
18506   if (TREE_PRIVATE (decl))
18507     current_access_specifier = access_private_node;
18508   else if (TREE_PROTECTED (decl))
18509     current_access_specifier = access_protected_node;
18510   else
18511     current_access_specifier = access_public_node;
18512 }
18513
18514 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18515    is the instantiation (which should have been created with
18516    start_enum) and ARGS are the template arguments to use.  */
18517
18518 static void
18519 tsubst_enum (tree tag, tree newtag, tree args)
18520 {
18521   tree e;
18522
18523   if (SCOPED_ENUM_P (newtag))
18524     begin_scope (sk_scoped_enum, newtag);
18525
18526   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18527     {
18528       tree value;
18529       tree decl;
18530
18531       decl = TREE_VALUE (e);
18532       /* Note that in a template enum, the TREE_VALUE is the
18533          CONST_DECL, not the corresponding INTEGER_CST.  */
18534       value = tsubst_expr (DECL_INITIAL (decl),
18535                            args, tf_warning_or_error, NULL_TREE,
18536                            /*integral_constant_expression_p=*/true);
18537
18538       /* Give this enumeration constant the correct access.  */
18539       set_current_access_from_decl (decl);
18540
18541       /* Actually build the enumerator itself.  */
18542       build_enumerator
18543         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18544     }
18545
18546   if (SCOPED_ENUM_P (newtag))
18547     finish_scope ();
18548
18549   finish_enum_value_list (newtag);
18550   finish_enum (newtag);
18551
18552   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18553     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18554 }
18555
18556 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18557    its type -- but without substituting the innermost set of template
18558    arguments.  So, innermost set of template parameters will appear in
18559    the type.  */
18560
18561 tree
18562 get_mostly_instantiated_function_type (tree decl)
18563 {
18564   tree fn_type;
18565   tree tmpl;
18566   tree targs;
18567   tree tparms;
18568   int parm_depth;
18569
18570   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18571   targs = DECL_TI_ARGS (decl);
18572   tparms = DECL_TEMPLATE_PARMS (tmpl);
18573   parm_depth = TMPL_PARMS_DEPTH (tparms);
18574
18575   /* There should be as many levels of arguments as there are levels
18576      of parameters.  */
18577   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18578
18579   fn_type = TREE_TYPE (tmpl);
18580
18581   if (parm_depth == 1)
18582     /* No substitution is necessary.  */
18583     ;
18584   else
18585     {
18586       int i;
18587       tree partial_args;
18588
18589       /* Replace the innermost level of the TARGS with NULL_TREEs to
18590          let tsubst know not to substitute for those parameters.  */
18591       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18592       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18593         SET_TMPL_ARGS_LEVEL (partial_args, i,
18594                              TMPL_ARGS_LEVEL (targs, i));
18595       SET_TMPL_ARGS_LEVEL (partial_args,
18596                            TMPL_ARGS_DEPTH (targs),
18597                            make_tree_vec (DECL_NTPARMS (tmpl)));
18598
18599       /* Make sure that we can see identifiers, and compute access
18600          correctly.  */
18601       push_access_scope (decl);
18602
18603       ++processing_template_decl;
18604       /* Now, do the (partial) substitution to figure out the
18605          appropriate function type.  */
18606       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18607       --processing_template_decl;
18608
18609       /* Substitute into the template parameters to obtain the real
18610          innermost set of parameters.  This step is important if the
18611          innermost set of template parameters contains value
18612          parameters whose types depend on outer template parameters.  */
18613       TREE_VEC_LENGTH (partial_args)--;
18614       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18615
18616       pop_access_scope (decl);
18617     }
18618
18619   return fn_type;
18620 }
18621
18622 /* Return truthvalue if we're processing a template different from
18623    the last one involved in diagnostics.  */
18624 int
18625 problematic_instantiation_changed (void)
18626 {
18627   return current_tinst_level != last_error_tinst_level;
18628 }
18629
18630 /* Remember current template involved in diagnostics.  */
18631 void
18632 record_last_problematic_instantiation (void)
18633 {
18634   last_error_tinst_level = current_tinst_level;
18635 }
18636
18637 struct tinst_level *
18638 current_instantiation (void)
18639 {
18640   return current_tinst_level;
18641 }
18642
18643 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18644    type. Return zero for ok, nonzero for disallowed. Issue error and
18645    warning messages under control of COMPLAIN.  */
18646
18647 static int
18648 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18649 {
18650   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18651     return 0;
18652   else if (POINTER_TYPE_P (type))
18653     return 0;
18654   else if (TYPE_PTR_TO_MEMBER_P (type))
18655     return 0;
18656   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18657     return 0;
18658   else if (TREE_CODE (type) == TYPENAME_TYPE)
18659     return 0;
18660   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18661     return 0;
18662
18663   if (complain & tf_error)
18664     error ("%q#T is not a valid type for a template constant parameter", type);
18665   return 1;
18666 }
18667
18668 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18669    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18670
18671 static bool
18672 dependent_type_p_r (tree type)
18673 {
18674   tree scope;
18675
18676   /* [temp.dep.type]
18677
18678      A type is dependent if it is:
18679
18680      -- a template parameter. Template template parameters are types
18681         for us (since TYPE_P holds true for them) so we handle
18682         them here.  */
18683   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18684       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18685     return true;
18686   /* -- a qualified-id with a nested-name-specifier which contains a
18687         class-name that names a dependent type or whose unqualified-id
18688         names a dependent type.  */
18689   if (TREE_CODE (type) == TYPENAME_TYPE)
18690     return true;
18691   /* -- a cv-qualified type where the cv-unqualified type is
18692         dependent.  */
18693   type = TYPE_MAIN_VARIANT (type);
18694   /* -- a compound type constructed from any dependent type.  */
18695   if (TYPE_PTR_TO_MEMBER_P (type))
18696     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18697             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18698                                            (type)));
18699   else if (TREE_CODE (type) == POINTER_TYPE
18700            || TREE_CODE (type) == REFERENCE_TYPE)
18701     return dependent_type_p (TREE_TYPE (type));
18702   else if (TREE_CODE (type) == FUNCTION_TYPE
18703            || TREE_CODE (type) == METHOD_TYPE)
18704     {
18705       tree arg_type;
18706
18707       if (dependent_type_p (TREE_TYPE (type)))
18708         return true;
18709       for (arg_type = TYPE_ARG_TYPES (type);
18710            arg_type;
18711            arg_type = TREE_CHAIN (arg_type))
18712         if (dependent_type_p (TREE_VALUE (arg_type)))
18713           return true;
18714       return false;
18715     }
18716   /* -- an array type constructed from any dependent type or whose
18717         size is specified by a constant expression that is
18718         value-dependent.
18719
18720         We checked for type- and value-dependence of the bounds in
18721         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18722   if (TREE_CODE (type) == ARRAY_TYPE)
18723     {
18724       if (TYPE_DOMAIN (type)
18725           && dependent_type_p (TYPE_DOMAIN (type)))
18726         return true;
18727       return dependent_type_p (TREE_TYPE (type));
18728     }
18729
18730   /* -- a template-id in which either the template name is a template
18731      parameter ...  */
18732   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18733     return true;
18734   /* ... or any of the template arguments is a dependent type or
18735         an expression that is type-dependent or value-dependent.  */
18736   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18737            && (any_dependent_template_arguments_p
18738                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18739     return true;
18740
18741   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18742      dependent; if the argument of the `typeof' expression is not
18743      type-dependent, then it should already been have resolved.  */
18744   if (TREE_CODE (type) == TYPEOF_TYPE
18745       || TREE_CODE (type) == DECLTYPE_TYPE
18746       || TREE_CODE (type) == UNDERLYING_TYPE)
18747     return true;
18748
18749   /* A template argument pack is dependent if any of its packed
18750      arguments are.  */
18751   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18752     {
18753       tree args = ARGUMENT_PACK_ARGS (type);
18754       int i, len = TREE_VEC_LENGTH (args);
18755       for (i = 0; i < len; ++i)
18756         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18757           return true;
18758     }
18759
18760   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18761      be template parameters.  */
18762   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18763     return true;
18764
18765   /* The standard does not specifically mention types that are local
18766      to template functions or local classes, but they should be
18767      considered dependent too.  For example:
18768
18769        template <int I> void f() {
18770          enum E { a = I };
18771          S<sizeof (E)> s;
18772        }
18773
18774      The size of `E' cannot be known until the value of `I' has been
18775      determined.  Therefore, `E' must be considered dependent.  */
18776   scope = TYPE_CONTEXT (type);
18777   if (scope && TYPE_P (scope))
18778     return dependent_type_p (scope);
18779   /* Don't use type_dependent_expression_p here, as it can lead
18780      to infinite recursion trying to determine whether a lambda
18781      nested in a lambda is dependent (c++/47687).  */
18782   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18783            && DECL_LANG_SPECIFIC (scope)
18784            && DECL_TEMPLATE_INFO (scope)
18785            && (any_dependent_template_arguments_p
18786                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18787     return true;
18788
18789   /* Other types are non-dependent.  */
18790   return false;
18791 }
18792
18793 /* Returns TRUE if TYPE is dependent, in the sense of
18794    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18795
18796 bool
18797 dependent_type_p (tree type)
18798 {
18799   /* If there are no template parameters in scope, then there can't be
18800      any dependent types.  */
18801   if (!processing_template_decl)
18802     {
18803       /* If we are not processing a template, then nobody should be
18804          providing us with a dependent type.  */
18805       gcc_assert (type);
18806       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18807       return false;
18808     }
18809
18810   /* If the type is NULL, we have not computed a type for the entity
18811      in question; in that case, the type is dependent.  */
18812   if (!type)
18813     return true;
18814
18815   /* Erroneous types can be considered non-dependent.  */
18816   if (type == error_mark_node)
18817     return false;
18818
18819   /* If we have not already computed the appropriate value for TYPE,
18820      do so now.  */
18821   if (!TYPE_DEPENDENT_P_VALID (type))
18822     {
18823       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18824       TYPE_DEPENDENT_P_VALID (type) = 1;
18825     }
18826
18827   return TYPE_DEPENDENT_P (type);
18828 }
18829
18830 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18831    lookup.  In other words, a dependent type that is not the current
18832    instantiation.  */
18833
18834 bool
18835 dependent_scope_p (tree scope)
18836 {
18837   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18838           && !currently_open_class (scope));
18839 }
18840
18841 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18842    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18843    expression.  */
18844
18845 /* Note that this predicate is not appropriate for general expressions;
18846    only constant expressions (that satisfy potential_constant_expression)
18847    can be tested for value dependence.
18848
18849    We should really also have a predicate for "instantiation-dependent".
18850
18851    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18852      (what about instantiation-dependent constant-expressions?)
18853    is_late_template_attribute: defer if instantiation-dependent.
18854    compute_array_index_type: proceed if constant and not t- or v-dependent
18855      if instantiation-dependent, need to remember full expression
18856    uses_template_parms: FIXME - need to audit callers
18857    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18858    dependent_type_p [array_type]: dependent if index type is dependent
18859      (or non-constant?)
18860    static_assert - instantiation-dependent */
18861
18862 bool
18863 value_dependent_expression_p (tree expression)
18864 {
18865   if (!processing_template_decl)
18866     return false;
18867
18868   /* A name declared with a dependent type.  */
18869   if (DECL_P (expression) && type_dependent_expression_p (expression))
18870     return true;
18871
18872   switch (TREE_CODE (expression))
18873     {
18874     case IDENTIFIER_NODE:
18875       /* A name that has not been looked up -- must be dependent.  */
18876       return true;
18877
18878     case TEMPLATE_PARM_INDEX:
18879       /* A non-type template parm.  */
18880       return true;
18881
18882     case CONST_DECL:
18883       /* A non-type template parm.  */
18884       if (DECL_TEMPLATE_PARM_P (expression))
18885         return true;
18886       return value_dependent_expression_p (DECL_INITIAL (expression));
18887
18888     case VAR_DECL:
18889        /* A constant with literal type and is initialized
18890           with an expression that is value-dependent.  */
18891       if (DECL_INITIAL (expression)
18892           && decl_constant_var_p (expression)
18893           && value_dependent_expression_p (DECL_INITIAL (expression)))
18894         return true;
18895       return false;
18896
18897     case DYNAMIC_CAST_EXPR:
18898     case STATIC_CAST_EXPR:
18899     case CONST_CAST_EXPR:
18900     case REINTERPRET_CAST_EXPR:
18901     case CAST_EXPR:
18902       /* These expressions are value-dependent if the type to which
18903          the cast occurs is dependent or the expression being casted
18904          is value-dependent.  */
18905       {
18906         tree type = TREE_TYPE (expression);
18907
18908         if (dependent_type_p (type))
18909           return true;
18910
18911         /* A functional cast has a list of operands.  */
18912         expression = TREE_OPERAND (expression, 0);
18913         if (!expression)
18914           {
18915             /* If there are no operands, it must be an expression such
18916                as "int()". This should not happen for aggregate types
18917                because it would form non-constant expressions.  */
18918             gcc_assert (cxx_dialect >= cxx0x
18919                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18920
18921             return false;
18922           }
18923
18924         if (TREE_CODE (expression) == TREE_LIST)
18925           return any_value_dependent_elements_p (expression);
18926
18927         return value_dependent_expression_p (expression);
18928       }
18929
18930     case SIZEOF_EXPR:
18931     case ALIGNOF_EXPR:
18932     case TYPEID_EXPR:
18933       /* A `sizeof' expression is value-dependent if the operand is
18934          type-dependent or is a pack expansion.  */
18935       expression = TREE_OPERAND (expression, 0);
18936       if (PACK_EXPANSION_P (expression))
18937         return true;
18938       else if (TYPE_P (expression))
18939         return dependent_type_p (expression);
18940       return type_dependent_expression_p (expression);
18941
18942     case AT_ENCODE_EXPR:
18943       /* An 'encode' expression is value-dependent if the operand is
18944          type-dependent.  */
18945       expression = TREE_OPERAND (expression, 0);
18946       return dependent_type_p (expression);
18947
18948     case NOEXCEPT_EXPR:
18949       expression = TREE_OPERAND (expression, 0);
18950       return type_dependent_expression_p (expression);
18951
18952     case SCOPE_REF:
18953       {
18954         tree name = TREE_OPERAND (expression, 1);
18955         return value_dependent_expression_p (name);
18956       }
18957
18958     case COMPONENT_REF:
18959       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18960               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18961
18962     case NONTYPE_ARGUMENT_PACK:
18963       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18964          is value-dependent.  */
18965       {
18966         tree values = ARGUMENT_PACK_ARGS (expression);
18967         int i, len = TREE_VEC_LENGTH (values);
18968         
18969         for (i = 0; i < len; ++i)
18970           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18971             return true;
18972         
18973         return false;
18974       }
18975
18976     case TRAIT_EXPR:
18977       {
18978         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18979         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18980                 || (type2 ? dependent_type_p (type2) : false));
18981       }
18982
18983     case MODOP_EXPR:
18984       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18985               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18986
18987     case ARRAY_REF:
18988       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18989               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
18990
18991     case ADDR_EXPR:
18992       {
18993         tree op = TREE_OPERAND (expression, 0);
18994         return (value_dependent_expression_p (op)
18995                 || has_value_dependent_address (op));
18996       }
18997
18998     case CALL_EXPR:
18999       {
19000         tree fn = get_callee_fndecl (expression);
19001         int i, nargs;
19002         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19003           return true;
19004         nargs = call_expr_nargs (expression);
19005         for (i = 0; i < nargs; ++i)
19006           {
19007             tree op = CALL_EXPR_ARG (expression, i);
19008             /* In a call to a constexpr member function, look through the
19009                implicit ADDR_EXPR on the object argument so that it doesn't
19010                cause the call to be considered value-dependent.  We also
19011                look through it in potential_constant_expression.  */
19012             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19013                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19014                 && TREE_CODE (op) == ADDR_EXPR)
19015               op = TREE_OPERAND (op, 0);
19016             if (value_dependent_expression_p (op))
19017               return true;
19018           }
19019         return false;
19020       }
19021
19022     case TEMPLATE_ID_EXPR:
19023       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19024          type-dependent.  */
19025       return type_dependent_expression_p (expression);
19026
19027     case CONSTRUCTOR:
19028       {
19029         unsigned ix;
19030         tree val;
19031         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19032           if (value_dependent_expression_p (val))
19033             return true;
19034         return false;
19035       }
19036
19037     default:
19038       /* A constant expression is value-dependent if any subexpression is
19039          value-dependent.  */
19040       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19041         {
19042         case tcc_reference:
19043         case tcc_unary:
19044         case tcc_comparison:
19045         case tcc_binary:
19046         case tcc_expression:
19047         case tcc_vl_exp:
19048           {
19049             int i, len = cp_tree_operand_length (expression);
19050
19051             for (i = 0; i < len; i++)
19052               {
19053                 tree t = TREE_OPERAND (expression, i);
19054
19055                 /* In some cases, some of the operands may be missing.l
19056                    (For example, in the case of PREDECREMENT_EXPR, the
19057                    amount to increment by may be missing.)  That doesn't
19058                    make the expression dependent.  */
19059                 if (t && value_dependent_expression_p (t))
19060                   return true;
19061               }
19062           }
19063           break;
19064         default:
19065           break;
19066         }
19067       break;
19068     }
19069
19070   /* The expression is not value-dependent.  */
19071   return false;
19072 }
19073
19074 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19075    [temp.dep.expr].  Note that an expression with no type is
19076    considered dependent.  Other parts of the compiler arrange for an
19077    expression with type-dependent subexpressions to have no type, so
19078    this function doesn't have to be fully recursive.  */
19079
19080 bool
19081 type_dependent_expression_p (tree expression)
19082 {
19083   if (!processing_template_decl)
19084     return false;
19085
19086   if (expression == error_mark_node)
19087     return false;
19088
19089   /* An unresolved name is always dependent.  */
19090   if (TREE_CODE (expression) == IDENTIFIER_NODE
19091       || TREE_CODE (expression) == USING_DECL)
19092     return true;
19093
19094   /* Some expression forms are never type-dependent.  */
19095   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19096       || TREE_CODE (expression) == SIZEOF_EXPR
19097       || TREE_CODE (expression) == ALIGNOF_EXPR
19098       || TREE_CODE (expression) == AT_ENCODE_EXPR
19099       || TREE_CODE (expression) == NOEXCEPT_EXPR
19100       || TREE_CODE (expression) == TRAIT_EXPR
19101       || TREE_CODE (expression) == TYPEID_EXPR
19102       || TREE_CODE (expression) == DELETE_EXPR
19103       || TREE_CODE (expression) == VEC_DELETE_EXPR
19104       || TREE_CODE (expression) == THROW_EXPR)
19105     return false;
19106
19107   /* The types of these expressions depends only on the type to which
19108      the cast occurs.  */
19109   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19110       || TREE_CODE (expression) == STATIC_CAST_EXPR
19111       || TREE_CODE (expression) == CONST_CAST_EXPR
19112       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19113       || TREE_CODE (expression) == CAST_EXPR)
19114     return dependent_type_p (TREE_TYPE (expression));
19115
19116   /* The types of these expressions depends only on the type created
19117      by the expression.  */
19118   if (TREE_CODE (expression) == NEW_EXPR
19119       || TREE_CODE (expression) == VEC_NEW_EXPR)
19120     {
19121       /* For NEW_EXPR tree nodes created inside a template, either
19122          the object type itself or a TREE_LIST may appear as the
19123          operand 1.  */
19124       tree type = TREE_OPERAND (expression, 1);
19125       if (TREE_CODE (type) == TREE_LIST)
19126         /* This is an array type.  We need to check array dimensions
19127            as well.  */
19128         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19129                || value_dependent_expression_p
19130                     (TREE_OPERAND (TREE_VALUE (type), 1));
19131       else
19132         return dependent_type_p (type);
19133     }
19134
19135   if (TREE_CODE (expression) == SCOPE_REF)
19136     {
19137       tree scope = TREE_OPERAND (expression, 0);
19138       tree name = TREE_OPERAND (expression, 1);
19139
19140       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19141          contains an identifier associated by name lookup with one or more
19142          declarations declared with a dependent type, or...a
19143          nested-name-specifier or qualified-id that names a member of an
19144          unknown specialization.  */
19145       return (type_dependent_expression_p (name)
19146               || dependent_scope_p (scope));
19147     }
19148
19149   if (TREE_CODE (expression) == FUNCTION_DECL
19150       && DECL_LANG_SPECIFIC (expression)
19151       && DECL_TEMPLATE_INFO (expression)
19152       && (any_dependent_template_arguments_p
19153           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19154     return true;
19155
19156   if (TREE_CODE (expression) == TEMPLATE_DECL
19157       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19158     return false;
19159
19160   if (TREE_CODE (expression) == STMT_EXPR)
19161     expression = stmt_expr_value_expr (expression);
19162
19163   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19164     {
19165       tree elt;
19166       unsigned i;
19167
19168       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19169         {
19170           if (type_dependent_expression_p (elt))
19171             return true;
19172         }
19173       return false;
19174     }
19175
19176   /* A static data member of the current instantiation with incomplete
19177      array type is type-dependent, as the definition and specializations
19178      can have different bounds.  */
19179   if (TREE_CODE (expression) == VAR_DECL
19180       && DECL_CLASS_SCOPE_P (expression)
19181       && dependent_type_p (DECL_CONTEXT (expression))
19182       && VAR_HAD_UNKNOWN_BOUND (expression))
19183     return true;
19184
19185   if (TREE_TYPE (expression) == unknown_type_node)
19186     {
19187       if (TREE_CODE (expression) == ADDR_EXPR)
19188         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19189       if (TREE_CODE (expression) == COMPONENT_REF
19190           || TREE_CODE (expression) == OFFSET_REF)
19191         {
19192           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19193             return true;
19194           expression = TREE_OPERAND (expression, 1);
19195           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19196             return false;
19197         }
19198       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19199       if (TREE_CODE (expression) == SCOPE_REF)
19200         return false;
19201
19202       if (TREE_CODE (expression) == BASELINK)
19203         expression = BASELINK_FUNCTIONS (expression);
19204
19205       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19206         {
19207           if (any_dependent_template_arguments_p
19208               (TREE_OPERAND (expression, 1)))
19209             return true;
19210           expression = TREE_OPERAND (expression, 0);
19211         }
19212       gcc_assert (TREE_CODE (expression) == OVERLOAD
19213                   || TREE_CODE (expression) == FUNCTION_DECL);
19214
19215       while (expression)
19216         {
19217           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19218             return true;
19219           expression = OVL_NEXT (expression);
19220         }
19221       return false;
19222     }
19223
19224   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19225
19226   return (dependent_type_p (TREE_TYPE (expression)));
19227 }
19228
19229 /* Like type_dependent_expression_p, but it also works while not processing
19230    a template definition, i.e. during substitution or mangling.  */
19231
19232 bool
19233 type_dependent_expression_p_push (tree expr)
19234 {
19235   bool b;
19236   ++processing_template_decl;
19237   b = type_dependent_expression_p (expr);
19238   --processing_template_decl;
19239   return b;
19240 }
19241
19242 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19243
19244 bool
19245 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19246 {
19247   unsigned int i;
19248   tree arg;
19249
19250   FOR_EACH_VEC_ELT (tree, args, i, arg)
19251     {
19252       if (type_dependent_expression_p (arg))
19253         return true;
19254     }
19255   return false;
19256 }
19257
19258 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19259    expressions) contains any type-dependent expressions.  */
19260
19261 bool
19262 any_type_dependent_elements_p (const_tree list)
19263 {
19264   for (; list; list = TREE_CHAIN (list))
19265     if (value_dependent_expression_p (TREE_VALUE (list)))
19266       return true;
19267
19268   return false;
19269 }
19270
19271 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19272    expressions) contains any value-dependent expressions.  */
19273
19274 bool
19275 any_value_dependent_elements_p (const_tree list)
19276 {
19277   for (; list; list = TREE_CHAIN (list))
19278     if (value_dependent_expression_p (TREE_VALUE (list)))
19279       return true;
19280
19281   return false;
19282 }
19283
19284 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19285
19286 bool
19287 dependent_template_arg_p (tree arg)
19288 {
19289   if (!processing_template_decl)
19290     return false;
19291
19292   /* Assume a template argument that was wrongly written by the user
19293      is dependent. This is consistent with what
19294      any_dependent_template_arguments_p [that calls this function]
19295      does.  */
19296   if (!arg || arg == error_mark_node)
19297     return true;
19298
19299   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19300     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19301
19302   if (TREE_CODE (arg) == TEMPLATE_DECL
19303       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19304     return dependent_template_p (arg);
19305   else if (ARGUMENT_PACK_P (arg))
19306     {
19307       tree args = ARGUMENT_PACK_ARGS (arg);
19308       int i, len = TREE_VEC_LENGTH (args);
19309       for (i = 0; i < len; ++i)
19310         {
19311           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19312             return true;
19313         }
19314
19315       return false;
19316     }
19317   else if (TYPE_P (arg))
19318     return dependent_type_p (arg);
19319   else
19320     return (type_dependent_expression_p (arg)
19321             || value_dependent_expression_p (arg));
19322 }
19323
19324 /* Returns true if ARGS (a collection of template arguments) contains
19325    any types that require structural equality testing.  */
19326
19327 bool
19328 any_template_arguments_need_structural_equality_p (tree args)
19329 {
19330   int i;
19331   int j;
19332
19333   if (!args)
19334     return false;
19335   if (args == error_mark_node)
19336     return true;
19337
19338   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19339     {
19340       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19341       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19342         {
19343           tree arg = TREE_VEC_ELT (level, j);
19344           tree packed_args = NULL_TREE;
19345           int k, len = 1;
19346
19347           if (ARGUMENT_PACK_P (arg))
19348             {
19349               /* Look inside the argument pack.  */
19350               packed_args = ARGUMENT_PACK_ARGS (arg);
19351               len = TREE_VEC_LENGTH (packed_args);
19352             }
19353
19354           for (k = 0; k < len; ++k)
19355             {
19356               if (packed_args)
19357                 arg = TREE_VEC_ELT (packed_args, k);
19358
19359               if (error_operand_p (arg))
19360                 return true;
19361               else if (TREE_CODE (arg) == TEMPLATE_DECL
19362                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19363                 continue;
19364               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19365                 return true;
19366               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19367                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19368                 return true;
19369             }
19370         }
19371     }
19372
19373   return false;
19374 }
19375
19376 /* Returns true if ARGS (a collection of template arguments) contains
19377    any dependent arguments.  */
19378
19379 bool
19380 any_dependent_template_arguments_p (const_tree args)
19381 {
19382   int i;
19383   int j;
19384
19385   if (!args)
19386     return false;
19387   if (args == error_mark_node)
19388     return true;
19389
19390   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19391     {
19392       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19393       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19394         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19395           return true;
19396     }
19397
19398   return false;
19399 }
19400
19401 /* Returns TRUE if the template TMPL is dependent.  */
19402
19403 bool
19404 dependent_template_p (tree tmpl)
19405 {
19406   if (TREE_CODE (tmpl) == OVERLOAD)
19407     {
19408       while (tmpl)
19409         {
19410           if (dependent_template_p (OVL_CURRENT (tmpl)))
19411             return true;
19412           tmpl = OVL_NEXT (tmpl);
19413         }
19414       return false;
19415     }
19416
19417   /* Template template parameters are dependent.  */
19418   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19419       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19420     return true;
19421   /* So are names that have not been looked up.  */
19422   if (TREE_CODE (tmpl) == SCOPE_REF
19423       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19424     return true;
19425   /* So are member templates of dependent classes.  */
19426   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19427     return dependent_type_p (DECL_CONTEXT (tmpl));
19428   return false;
19429 }
19430
19431 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19432
19433 bool
19434 dependent_template_id_p (tree tmpl, tree args)
19435 {
19436   return (dependent_template_p (tmpl)
19437           || any_dependent_template_arguments_p (args));
19438 }
19439
19440 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19441    is dependent.  */
19442
19443 bool
19444 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19445 {
19446   int i;
19447
19448   if (!processing_template_decl)
19449     return false;
19450
19451   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19452     {
19453       tree decl = TREE_VEC_ELT (declv, i);
19454       tree init = TREE_VEC_ELT (initv, i);
19455       tree cond = TREE_VEC_ELT (condv, i);
19456       tree incr = TREE_VEC_ELT (incrv, i);
19457
19458       if (type_dependent_expression_p (decl))
19459         return true;
19460
19461       if (init && type_dependent_expression_p (init))
19462         return true;
19463
19464       if (type_dependent_expression_p (cond))
19465         return true;
19466
19467       if (COMPARISON_CLASS_P (cond)
19468           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19469               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19470         return true;
19471
19472       if (TREE_CODE (incr) == MODOP_EXPR)
19473         {
19474           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19475               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19476             return true;
19477         }
19478       else if (type_dependent_expression_p (incr))
19479         return true;
19480       else if (TREE_CODE (incr) == MODIFY_EXPR)
19481         {
19482           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19483             return true;
19484           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19485             {
19486               tree t = TREE_OPERAND (incr, 1);
19487               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19488                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19489                 return true;
19490             }
19491         }
19492     }
19493
19494   return false;
19495 }
19496
19497 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19498    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19499    no such TYPE can be found.  Note that this function peers inside
19500    uninstantiated templates and therefore should be used only in
19501    extremely limited situations.  ONLY_CURRENT_P restricts this
19502    peering to the currently open classes hierarchy (which is required
19503    when comparing types).  */
19504
19505 tree
19506 resolve_typename_type (tree type, bool only_current_p)
19507 {
19508   tree scope;
19509   tree name;
19510   tree decl;
19511   int quals;
19512   tree pushed_scope;
19513   tree result;
19514
19515   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19516
19517   scope = TYPE_CONTEXT (type);
19518   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19519      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19520      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19521      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19522      identifier  of the TYPENAME_TYPE anymore.
19523      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19524      TYPENAME_TYPE instead, we avoid messing up with a possible
19525      typedef variant case.  */
19526   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19527
19528   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19529      it first before we can figure out what NAME refers to.  */
19530   if (TREE_CODE (scope) == TYPENAME_TYPE)
19531     scope = resolve_typename_type (scope, only_current_p);
19532   /* If we don't know what SCOPE refers to, then we cannot resolve the
19533      TYPENAME_TYPE.  */
19534   if (TREE_CODE (scope) == TYPENAME_TYPE)
19535     return type;
19536   /* If the SCOPE is a template type parameter, we have no way of
19537      resolving the name.  */
19538   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19539     return type;
19540   /* If the SCOPE is not the current instantiation, there's no reason
19541      to look inside it.  */
19542   if (only_current_p && !currently_open_class (scope))
19543     return type;
19544   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19545   if (typedef_variant_p (type))
19546     return type;
19547   /* If SCOPE isn't the template itself, it will not have a valid
19548      TYPE_FIELDS list.  */
19549   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19550     /* scope is either the template itself or a compatible instantiation
19551        like X<T>, so look up the name in the original template.  */
19552     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19553   else
19554     /* scope is a partial instantiation, so we can't do the lookup or we
19555        will lose the template arguments.  */
19556     return type;
19557   /* Enter the SCOPE so that name lookup will be resolved as if we
19558      were in the class definition.  In particular, SCOPE will no
19559      longer be considered a dependent type.  */
19560   pushed_scope = push_scope (scope);
19561   /* Look up the declaration.  */
19562   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19563
19564   result = NULL_TREE;
19565   
19566   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19567      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19568   if (!decl)
19569     /*nop*/;
19570   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19571            && TREE_CODE (decl) == TYPE_DECL)
19572     {
19573       result = TREE_TYPE (decl);
19574       if (result == error_mark_node)
19575         result = NULL_TREE;
19576     }
19577   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19578            && DECL_CLASS_TEMPLATE_P (decl))
19579     {
19580       tree tmpl;
19581       tree args;
19582       /* Obtain the template and the arguments.  */
19583       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19584       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19585       /* Instantiate the template.  */
19586       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19587                                       /*entering_scope=*/0,
19588                                       tf_error | tf_user);
19589       if (result == error_mark_node)
19590         result = NULL_TREE;
19591     }
19592   
19593   /* Leave the SCOPE.  */
19594   if (pushed_scope)
19595     pop_scope (pushed_scope);
19596
19597   /* If we failed to resolve it, return the original typename.  */
19598   if (!result)
19599     return type;
19600   
19601   /* If lookup found a typename type, resolve that too.  */
19602   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19603     {
19604       /* Ill-formed programs can cause infinite recursion here, so we
19605          must catch that.  */
19606       TYPENAME_IS_RESOLVING_P (type) = 1;
19607       result = resolve_typename_type (result, only_current_p);
19608       TYPENAME_IS_RESOLVING_P (type) = 0;
19609     }
19610   
19611   /* Qualify the resulting type.  */
19612   quals = cp_type_quals (type);
19613   if (quals)
19614     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19615
19616   return result;
19617 }
19618
19619 /* EXPR is an expression which is not type-dependent.  Return a proxy
19620    for EXPR that can be used to compute the types of larger
19621    expressions containing EXPR.  */
19622
19623 tree
19624 build_non_dependent_expr (tree expr)
19625 {
19626   tree inner_expr;
19627
19628 #ifdef ENABLE_CHECKING
19629   /* Try to get a constant value for all non-type-dependent expressions in
19630       order to expose bugs in *_dependent_expression_p and constexpr.  */
19631   if (cxx_dialect >= cxx0x)
19632     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19633 #endif
19634
19635   /* Preserve OVERLOADs; the functions must be available to resolve
19636      types.  */
19637   inner_expr = expr;
19638   if (TREE_CODE (inner_expr) == STMT_EXPR)
19639     inner_expr = stmt_expr_value_expr (inner_expr);
19640   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19641     inner_expr = TREE_OPERAND (inner_expr, 0);
19642   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19643     inner_expr = TREE_OPERAND (inner_expr, 1);
19644   if (is_overloaded_fn (inner_expr)
19645       || TREE_CODE (inner_expr) == OFFSET_REF)
19646     return expr;
19647   /* There is no need to return a proxy for a variable.  */
19648   if (TREE_CODE (expr) == VAR_DECL)
19649     return expr;
19650   /* Preserve string constants; conversions from string constants to
19651      "char *" are allowed, even though normally a "const char *"
19652      cannot be used to initialize a "char *".  */
19653   if (TREE_CODE (expr) == STRING_CST)
19654     return expr;
19655   /* Preserve arithmetic constants, as an optimization -- there is no
19656      reason to create a new node.  */
19657   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19658     return expr;
19659   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19660      There is at least one place where we want to know that a
19661      particular expression is a throw-expression: when checking a ?:
19662      expression, there are special rules if the second or third
19663      argument is a throw-expression.  */
19664   if (TREE_CODE (expr) == THROW_EXPR)
19665     return expr;
19666
19667   if (TREE_CODE (expr) == COND_EXPR)
19668     return build3 (COND_EXPR,
19669                    TREE_TYPE (expr),
19670                    TREE_OPERAND (expr, 0),
19671                    (TREE_OPERAND (expr, 1)
19672                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19673                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19674                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19675   if (TREE_CODE (expr) == COMPOUND_EXPR
19676       && !COMPOUND_EXPR_OVERLOADED (expr))
19677     return build2 (COMPOUND_EXPR,
19678                    TREE_TYPE (expr),
19679                    TREE_OPERAND (expr, 0),
19680                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19681
19682   /* If the type is unknown, it can't really be non-dependent */
19683   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19684
19685   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19686   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19687 }
19688
19689 /* ARGS is a vector of expressions as arguments to a function call.
19690    Replace the arguments with equivalent non-dependent expressions.
19691    This modifies ARGS in place.  */
19692
19693 void
19694 make_args_non_dependent (VEC(tree,gc) *args)
19695 {
19696   unsigned int ix;
19697   tree arg;
19698
19699   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19700     {
19701       tree newarg = build_non_dependent_expr (arg);
19702       if (newarg != arg)
19703         VEC_replace (tree, args, ix, newarg);
19704     }
19705 }
19706
19707 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19708    with a level one deeper than the actual template parms.  */
19709
19710 tree
19711 make_auto (void)
19712 {
19713   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19714   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19715                                TYPE_DECL, get_identifier ("auto"), au);
19716   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19717   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19718     (0, processing_template_decl + 1, processing_template_decl + 1,
19719      0, TYPE_NAME (au), NULL_TREE);
19720   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19721   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19722   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19723
19724   return au;
19725 }
19726
19727 /* Given type ARG, return std::initializer_list<ARG>.  */
19728
19729 static tree
19730 listify (tree arg)
19731 {
19732   tree std_init_list = namespace_binding
19733     (get_identifier ("initializer_list"), std_node);
19734   tree argvec;
19735   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19736     {    
19737       error ("deducing from brace-enclosed initializer list requires "
19738              "#include <initializer_list>");
19739       return error_mark_node;
19740     }
19741   argvec = make_tree_vec (1);
19742   TREE_VEC_ELT (argvec, 0) = arg;
19743   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19744                                 NULL_TREE, 0, tf_warning_or_error);
19745 }
19746
19747 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19748
19749 static tree
19750 listify_autos (tree type, tree auto_node)
19751 {
19752   tree init_auto = listify (auto_node);
19753   tree argvec = make_tree_vec (1);
19754   TREE_VEC_ELT (argvec, 0) = init_auto;
19755   if (processing_template_decl)
19756     argvec = add_to_template_args (current_template_args (), argvec);
19757   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19758 }
19759
19760 /* walk_tree helper for do_auto_deduction.  */
19761
19762 static tree
19763 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19764                  void *type)
19765 {
19766   /* Is this a variable with the type we're looking for?  */
19767   if (DECL_P (*tp)
19768       && TREE_TYPE (*tp) == type)
19769     return *tp;
19770   else
19771     return NULL_TREE;
19772 }
19773
19774 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19775    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19776
19777 tree
19778 do_auto_deduction (tree type, tree init, tree auto_node)
19779 {
19780   tree parms, tparms, targs;
19781   tree args[1];
19782   tree decl;
19783   int val;
19784
19785   if (processing_template_decl
19786       && (TREE_TYPE (init) == NULL_TREE
19787           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19788     /* Not enough information to try this yet.  */
19789     return type;
19790
19791   /* The name of the object being declared shall not appear in the
19792      initializer expression.  */
19793   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19794   if (decl)
19795     {
19796       error ("variable %q#D with %<auto%> type used in its own "
19797              "initializer", decl);
19798       return error_mark_node;
19799     }
19800
19801   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19802      with either a new invented type template parameter U or, if the
19803      initializer is a braced-init-list (8.5.4), with
19804      std::initializer_list<U>.  */
19805   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19806     type = listify_autos (type, auto_node);
19807
19808   init = resolve_nondeduced_context (init);
19809
19810   parms = build_tree_list (NULL_TREE, type);
19811   args[0] = init;
19812   tparms = make_tree_vec (1);
19813   targs = make_tree_vec (1);
19814   TREE_VEC_ELT (tparms, 0)
19815     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19816   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19817                                DEDUCE_CALL, LOOKUP_NORMAL,
19818                                /*explain_p=*/false);
19819   if (val > 0)
19820     {
19821       if (processing_template_decl)
19822         /* Try again at instantiation time.  */
19823         return type;
19824       if (type && type != error_mark_node)
19825         /* If type is error_mark_node a diagnostic must have been
19826            emitted by now.  Also, having a mention to '<type error>'
19827            in the diagnostic is not really useful to the user.  */
19828         error ("unable to deduce %qT from %qE", type, init);
19829       return error_mark_node;
19830     }
19831
19832   /* If the list of declarators contains more than one declarator, the type
19833      of each declared variable is determined as described above. If the
19834      type deduced for the template parameter U is not the same in each
19835      deduction, the program is ill-formed.  */
19836   if (TREE_TYPE (auto_node)
19837       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19838     {
19839       error ("inconsistent deduction for %qT: %qT and then %qT",
19840              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19841       return error_mark_node;
19842     }
19843   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19844
19845   if (processing_template_decl)
19846     targs = add_to_template_args (current_template_args (), targs);
19847   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19848 }
19849
19850 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19851    result.  */
19852
19853 tree
19854 splice_late_return_type (tree type, tree late_return_type)
19855 {
19856   tree argvec;
19857
19858   if (late_return_type == NULL_TREE)
19859     return type;
19860   argvec = make_tree_vec (1);
19861   TREE_VEC_ELT (argvec, 0) = late_return_type;
19862   if (processing_template_parmlist)
19863     /* For a late-specified return type in a template type-parameter, we
19864        need to add a dummy argument level for its parmlist.  */
19865     argvec = add_to_template_args
19866       (make_tree_vec (processing_template_parmlist), argvec);
19867   if (current_template_parms)
19868     argvec = add_to_template_args (current_template_args (), argvec);
19869   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19870 }
19871
19872 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19873
19874 bool
19875 is_auto (const_tree type)
19876 {
19877   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19878       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19879     return true;
19880   else
19881     return false;
19882 }
19883
19884 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19885    appear as a type-specifier for the declaration in question, we don't
19886    have to look through the whole type.  */
19887
19888 tree
19889 type_uses_auto (tree type)
19890 {
19891   enum tree_code code;
19892   if (is_auto (type))
19893     return type;
19894
19895   code = TREE_CODE (type);
19896
19897   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19898       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19899       || code == METHOD_TYPE || code == ARRAY_TYPE)
19900     return type_uses_auto (TREE_TYPE (type));
19901
19902   if (TYPE_PTRMEMFUNC_P (type))
19903     return type_uses_auto (TREE_TYPE (TREE_TYPE
19904                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19905
19906   return NULL_TREE;
19907 }
19908
19909 /* For a given template T, return the vector of typedefs referenced
19910    in T for which access check is needed at T instantiation time.
19911    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19912    Those typedefs were added to T by the function
19913    append_type_to_template_for_access_check.  */
19914
19915 VEC(qualified_typedef_usage_t,gc)*
19916 get_types_needing_access_check (tree t)
19917 {
19918   tree ti;
19919   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19920
19921   if (!t || t == error_mark_node)
19922     return NULL;
19923
19924   if (!(ti = get_template_info (t)))
19925     return NULL;
19926
19927   if (CLASS_TYPE_P (t)
19928       || TREE_CODE (t) == FUNCTION_DECL)
19929     {
19930       if (!TI_TEMPLATE (ti))
19931         return NULL;
19932
19933       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19934     }
19935
19936   return result;
19937 }
19938
19939 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19940    tied to T. That list of typedefs will be access checked at
19941    T instantiation time.
19942    T is either a FUNCTION_DECL or a RECORD_TYPE.
19943    TYPE_DECL is a TYPE_DECL node representing a typedef.
19944    SCOPE is the scope through which TYPE_DECL is accessed.
19945    LOCATION is the location of the usage point of TYPE_DECL.
19946
19947    This function is a subroutine of
19948    append_type_to_template_for_access_check.  */
19949
19950 static void
19951 append_type_to_template_for_access_check_1 (tree t,
19952                                             tree type_decl,
19953                                             tree scope,
19954                                             location_t location)
19955 {
19956   qualified_typedef_usage_t typedef_usage;
19957   tree ti;
19958
19959   if (!t || t == error_mark_node)
19960     return;
19961
19962   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19963                || CLASS_TYPE_P (t))
19964               && type_decl
19965               && TREE_CODE (type_decl) == TYPE_DECL
19966               && scope);
19967
19968   if (!(ti = get_template_info (t)))
19969     return;
19970
19971   gcc_assert (TI_TEMPLATE (ti));
19972
19973   typedef_usage.typedef_decl = type_decl;
19974   typedef_usage.context = scope;
19975   typedef_usage.locus = location;
19976
19977   VEC_safe_push (qualified_typedef_usage_t, gc,
19978                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19979                  &typedef_usage);
19980 }
19981
19982 /* Append TYPE_DECL to the template TEMPL.
19983    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19984    At TEMPL instanciation time, TYPE_DECL will be checked to see
19985    if it can be accessed through SCOPE.
19986    LOCATION is the location of the usage point of TYPE_DECL.
19987
19988    e.g. consider the following code snippet:
19989
19990      class C
19991      {
19992        typedef int myint;
19993      };
19994
19995      template<class U> struct S
19996      {
19997        C::myint mi; // <-- usage point of the typedef C::myint
19998      };
19999
20000      S<char> s;
20001
20002    At S<char> instantiation time, we need to check the access of C::myint
20003    In other words, we need to check the access of the myint typedef through
20004    the C scope. For that purpose, this function will add the myint typedef
20005    and the scope C through which its being accessed to a list of typedefs
20006    tied to the template S. That list will be walked at template instantiation
20007    time and access check performed on each typedefs it contains.
20008    Note that this particular code snippet should yield an error because
20009    myint is private to C.  */
20010
20011 void
20012 append_type_to_template_for_access_check (tree templ,
20013                                           tree type_decl,
20014                                           tree scope,
20015                                           location_t location)
20016 {
20017   qualified_typedef_usage_t *iter;
20018   int i;
20019
20020   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20021
20022   /* Make sure we don't append the type to the template twice.  */
20023   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20024                     get_types_needing_access_check (templ),
20025                     i, iter)
20026     if (iter->typedef_decl == type_decl && scope == iter->context)
20027       return;
20028
20029   append_type_to_template_for_access_check_1 (templ, type_decl,
20030                                               scope, location);
20031 }
20032
20033 /* Set up the hash tables for template instantiations.  */
20034
20035 void
20036 init_template_processing (void)
20037 {
20038   decl_specializations = htab_create_ggc (37,
20039                                           hash_specialization,
20040                                           eq_specializations,
20041                                           ggc_free);
20042   type_specializations = htab_create_ggc (37,
20043                                           hash_specialization,
20044                                           eq_specializations,
20045                                           ggc_free);
20046 }
20047
20048 /* Print stats about the template hash tables for -fstats.  */
20049
20050 void
20051 print_template_statistics (void)
20052 {
20053   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20054            "%f collisions\n", (long) htab_size (decl_specializations),
20055            (long) htab_elements (decl_specializations),
20056            htab_collisions (decl_specializations));
20057   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20058            "%f collisions\n", (long) htab_size (type_specializations),
20059            (long) htab_elements (type_specializations),
20060            htab_collisions (type_specializations));
20061 }
20062
20063 #include "gt-cp-pt.h"