Update gcc-50 to SVN version 225979 (gcc-5-branch)
[dragonfly.git] / contrib / gcc-5.0 / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2015 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* Known bugs or deficiencies include:
23
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "hash-set.h"
32 #include "machmode.h"
33 #include "vec.h"
34 #include "double-int.h"
35 #include "input.h"
36 #include "alias.h"
37 #include "symtab.h"
38 #include "wide-int.h"
39 #include "inchash.h"
40 #include "tree.h"
41 #include "stringpool.h"
42 #include "varasm.h"
43 #include "attribs.h"
44 #include "stor-layout.h"
45 #include "intl.h"
46 #include "flags.h"
47 #include "cp-tree.h"
48 #include "c-family/c-common.h"
49 #include "c-family/c-objc.h"
50 #include "cp-objcp-common.h"
51 #include "tree-inline.h"
52 #include "decl.h"
53 #include "toplev.h"
54 #include "timevar.h"
55 #include "tree-iterator.h"
56 #include "type-utils.h"
57 #include "gimplify.h"
58
59 /* The type of functions taking a tree, and some additional data, and
60    returning an int.  */
61 typedef int (*tree_fn_t) (tree, void*);
62
63 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
64    instantiations have been deferred, either because their definitions
65    were not yet available, or because we were putting off doing the work.  */
66 struct GTY ((chain_next ("%h.next"))) pending_template {
67   struct pending_template *next;
68   struct tinst_level *tinst;
69 };
70
71 static GTY(()) struct pending_template *pending_templates;
72 static GTY(()) struct pending_template *last_pending_template;
73
74 int processing_template_parmlist;
75 static int template_header_count;
76
77 static GTY(()) tree saved_trees;
78 static vec<int> inline_parm_levels;
79
80 static GTY(()) struct tinst_level *current_tinst_level;
81
82 static GTY(()) tree saved_access_scope;
83
84 /* Live only within one (recursive) call to tsubst_expr.  We use
85    this to pass the statement expression node from the STMT_EXPR
86    to the EXPR_STMT that is its result.  */
87 static tree cur_stmt_expr;
88
89 /* True if we've recursed into fn_type_unification too many times.  */
90 static bool excessive_deduction_depth;
91
92 struct GTY((for_user)) spec_entry
93 {
94   tree tmpl;
95   tree args;
96   tree spec;
97 };
98
99 struct spec_hasher : ggc_hasher<spec_entry *>
100 {
101   static hashval_t hash (spec_entry *);
102   static bool equal (spec_entry *, spec_entry *);
103 };
104
105 static GTY (()) hash_table<spec_hasher> *decl_specializations;
106
107 static GTY (()) hash_table<spec_hasher> *type_specializations;
108
109 /* Contains canonical template parameter types. The vector is indexed by
110    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
111    TREE_LIST, whose TREE_VALUEs contain the canonical template
112    parameters of various types and levels.  */
113 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
114
115 #define UNIFY_ALLOW_NONE 0
116 #define UNIFY_ALLOW_MORE_CV_QUAL 1
117 #define UNIFY_ALLOW_LESS_CV_QUAL 2
118 #define UNIFY_ALLOW_DERIVED 4
119 #define UNIFY_ALLOW_INTEGER 8
120 #define UNIFY_ALLOW_OUTER_LEVEL 16
121 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
122 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
123
124 enum template_base_result {
125   tbr_incomplete_type,
126   tbr_ambiguous_baseclass,
127   tbr_success
128 };
129
130 static void push_access_scope (tree);
131 static void pop_access_scope (tree);
132 static bool resolve_overloaded_unification (tree, tree, tree, tree,
133                                             unification_kind_t, int,
134                                             bool);
135 static int try_one_overload (tree, tree, tree, tree, tree,
136                              unification_kind_t, int, bool, bool);
137 static int unify (tree, tree, tree, tree, int, bool);
138 static void add_pending_template (tree);
139 static tree reopen_tinst_level (struct tinst_level *);
140 static tree tsubst_initializer_list (tree, tree);
141 static tree get_partial_spec_bindings (tree, tree, tree, tree);
142 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
143                                    bool, bool);
144 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
145                                               bool, bool);
146 static void tsubst_enum (tree, tree, tree);
147 static tree add_to_template_args (tree, tree);
148 static tree add_outermost_template_args (tree, tree);
149 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
150 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
151                                              tree);
152 static int type_unification_real (tree, tree, tree, const tree *,
153                                   unsigned int, int, unification_kind_t, int,
154                                   vec<deferred_access_check, va_gc> **,
155                                   bool);
156 static void note_template_header (int);
157 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
158 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
159 static tree convert_template_argument (tree, tree, tree,
160                                        tsubst_flags_t, int, tree);
161 static int for_each_template_parm (tree, tree_fn_t, void*,
162                                    hash_set<tree> *, bool);
163 static tree expand_template_argument_pack (tree);
164 static tree build_template_parm_index (int, int, int, tree, tree);
165 static bool inline_needs_template_parms (tree, bool);
166 static void push_inline_template_parms_recursive (tree, int);
167 static tree retrieve_local_specialization (tree);
168 static void register_local_specialization (tree, tree);
169 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
170 static int mark_template_parm (tree, void *);
171 static int template_parm_this_level_p (tree, void *);
172 static tree tsubst_friend_function (tree, tree);
173 static tree tsubst_friend_class (tree, tree);
174 static int can_complete_type_without_circularity (tree);
175 static tree get_bindings (tree, tree, tree, bool);
176 static int template_decl_level (tree);
177 static int check_cv_quals_for_unify (int, tree, tree);
178 static void template_parm_level_and_index (tree, int*, int*);
179 static int unify_pack_expansion (tree, tree, tree,
180                                  tree, unification_kind_t, bool, bool);
181 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
182 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
183 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
184 static void regenerate_decl_from_template (tree, tree);
185 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
189 static bool check_specialization_scope (void);
190 static tree process_partial_specialization (tree);
191 static void set_current_access_from_decl (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193                                                     bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
196                                            tree, tree);
197 static bool template_template_parm_bindings_ok_p (tree, tree);
198 static int template_args_equal (tree, tree);
199 static void tsubst_default_arguments (tree, tsubst_flags_t);
200 static tree for_each_template_parm_r (tree *, int *, void *);
201 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
202 static void copy_default_args_to_explicit_spec (tree);
203 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
204 static bool dependent_template_arg_p (tree);
205 static bool any_template_arguments_need_structural_equality_p (tree);
206 static bool dependent_type_p_r (tree);
207 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
208 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
210 static tree tsubst_decl (tree, tree, tsubst_flags_t);
211 static void perform_typedefs_access_check (tree tmpl, tree targs);
212 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
213                                                         location_t);
214 static tree listify (tree);
215 static tree listify_autos (tree, tree);
216 static tree template_parm_to_arg (tree t);
217 static tree current_template_args (void);
218 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
219 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
220 static bool complex_alias_template_p (const_tree tmpl);
221
222 /* Make the current scope suitable for access checking when we are
223    processing T.  T can be FUNCTION_DECL for instantiated function
224    template, VAR_DECL for static member variable, or TYPE_DECL for
225    alias template (needed by instantiate_decl).  */
226
227 static void
228 push_access_scope (tree t)
229 {
230   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
231               || TREE_CODE (t) == TYPE_DECL);
232
233   if (DECL_FRIEND_CONTEXT (t))
234     push_nested_class (DECL_FRIEND_CONTEXT (t));
235   else if (DECL_CLASS_SCOPE_P (t))
236     push_nested_class (DECL_CONTEXT (t));
237   else
238     push_to_top_level ();
239
240   if (TREE_CODE (t) == FUNCTION_DECL)
241     {
242       saved_access_scope = tree_cons
243         (NULL_TREE, current_function_decl, saved_access_scope);
244       current_function_decl = t;
245     }
246 }
247
248 /* Restore the scope set up by push_access_scope.  T is the node we
249    are processing.  */
250
251 static void
252 pop_access_scope (tree t)
253 {
254   if (TREE_CODE (t) == FUNCTION_DECL)
255     {
256       current_function_decl = TREE_VALUE (saved_access_scope);
257       saved_access_scope = TREE_CHAIN (saved_access_scope);
258     }
259
260   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
261     pop_nested_class ();
262   else
263     pop_from_top_level ();
264 }
265
266 /* Do any processing required when DECL (a member template
267    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
268    to DECL, unless it is a specialization, in which case the DECL
269    itself is returned.  */
270
271 tree
272 finish_member_template_decl (tree decl)
273 {
274   if (decl == error_mark_node)
275     return error_mark_node;
276
277   gcc_assert (DECL_P (decl));
278
279   if (TREE_CODE (decl) == TYPE_DECL)
280     {
281       tree type;
282
283       type = TREE_TYPE (decl);
284       if (type == error_mark_node)
285         return error_mark_node;
286       if (MAYBE_CLASS_TYPE_P (type)
287           && CLASSTYPE_TEMPLATE_INFO (type)
288           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
289         {
290           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
291           check_member_template (tmpl);
292           return tmpl;
293         }
294       return NULL_TREE;
295     }
296   else if (TREE_CODE (decl) == FIELD_DECL)
297     error ("data member %qD cannot be a member template", decl);
298   else if (DECL_TEMPLATE_INFO (decl))
299     {
300       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
301         {
302           check_member_template (DECL_TI_TEMPLATE (decl));
303           return DECL_TI_TEMPLATE (decl);
304         }
305       else
306         return decl;
307     }
308   else
309     error ("invalid member template declaration %qD", decl);
310
311   return error_mark_node;
312 }
313
314 /* Create a template info node.  */
315
316 tree
317 build_template_info (tree template_decl, tree template_args)
318 {
319   tree result = make_node (TEMPLATE_INFO);
320   TI_TEMPLATE (result) = template_decl;
321   TI_ARGS (result) = template_args;
322   return result;
323 }
324
325 /* Return the template info node corresponding to T, whatever T is.  */
326
327 tree
328 get_template_info (const_tree t)
329 {
330   tree tinfo = NULL_TREE;
331
332   if (!t || t == error_mark_node)
333     return NULL;
334
335   if (TREE_CODE (t) == NAMESPACE_DECL)
336     return NULL;
337
338   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
339     tinfo = DECL_TEMPLATE_INFO (t);
340
341   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
342     t = TREE_TYPE (t);
343
344   if (OVERLOAD_TYPE_P (t))
345     tinfo = TYPE_TEMPLATE_INFO (t);
346   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
347     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
348
349   return tinfo;
350 }
351
352 /* Returns the template nesting level of the indicated class TYPE.
353
354    For example, in:
355      template <class T>
356      struct A
357      {
358        template <class U>
359        struct B {};
360      };
361
362    A<T>::B<U> has depth two, while A<T> has depth one.
363    Both A<T>::B<int> and A<int>::B<U> have depth one, if
364    they are instantiations, not specializations.
365
366    This function is guaranteed to return 0 if passed NULL_TREE so
367    that, for example, `template_class_depth (current_class_type)' is
368    always safe.  */
369
370 int
371 template_class_depth (tree type)
372 {
373   int depth;
374
375   for (depth = 0;
376        type && TREE_CODE (type) != NAMESPACE_DECL;
377        type = (TREE_CODE (type) == FUNCTION_DECL)
378          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
379     {
380       tree tinfo = get_template_info (type);
381
382       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
383           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
384         ++depth;
385     }
386
387   return depth;
388 }
389
390 /* Subroutine of maybe_begin_member_template_processing.
391    Returns true if processing DECL needs us to push template parms.  */
392
393 static bool
394 inline_needs_template_parms (tree decl, bool nsdmi)
395 {
396   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
397     return false;
398
399   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
400           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
401 }
402
403 /* Subroutine of maybe_begin_member_template_processing.
404    Push the template parms in PARMS, starting from LEVELS steps into the
405    chain, and ending at the beginning, since template parms are listed
406    innermost first.  */
407
408 static void
409 push_inline_template_parms_recursive (tree parmlist, int levels)
410 {
411   tree parms = TREE_VALUE (parmlist);
412   int i;
413
414   if (levels > 1)
415     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
416
417   ++processing_template_decl;
418   current_template_parms
419     = tree_cons (size_int (processing_template_decl),
420                  parms, current_template_parms);
421   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
422
423   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
424                NULL);
425   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
426     {
427       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
428
429       if (error_operand_p (parm))
430         continue;
431
432       gcc_assert (DECL_P (parm));
433
434       switch (TREE_CODE (parm))
435         {
436         case TYPE_DECL:
437         case TEMPLATE_DECL:
438           pushdecl (parm);
439           break;
440
441         case PARM_DECL:
442           {
443             /* Make a CONST_DECL as is done in process_template_parm.
444                It is ugly that we recreate this here; the original
445                version built in process_template_parm is no longer
446                available.  */
447             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
448                                     CONST_DECL, DECL_NAME (parm),
449                                     TREE_TYPE (parm));
450             DECL_ARTIFICIAL (decl) = 1;
451             TREE_CONSTANT (decl) = 1;
452             TREE_READONLY (decl) = 1;
453             DECL_INITIAL (decl) = DECL_INITIAL (parm);
454             SET_DECL_TEMPLATE_PARM_P (decl);
455             pushdecl (decl);
456           }
457           break;
458
459         default:
460           gcc_unreachable ();
461         }
462     }
463 }
464
465 /* Restore the template parameter context for a member template, a
466    friend template defined in a class definition, or a non-template
467    member of template class.  */
468
469 void
470 maybe_begin_member_template_processing (tree decl)
471 {
472   tree parms;
473   int levels = 0;
474   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
475
476   if (nsdmi)
477     {
478       tree ctx = DECL_CONTEXT (decl);
479       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
480               /* Disregard full specializations (c++/60999).  */
481               && uses_template_parms (ctx)
482               ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
483     }
484
485   if (inline_needs_template_parms (decl, nsdmi))
486     {
487       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
488       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
489
490       if (DECL_TEMPLATE_SPECIALIZATION (decl))
491         {
492           --levels;
493           parms = TREE_CHAIN (parms);
494         }
495
496       push_inline_template_parms_recursive (parms, levels);
497     }
498
499   /* Remember how many levels of template parameters we pushed so that
500      we can pop them later.  */
501   inline_parm_levels.safe_push (levels);
502 }
503
504 /* Undo the effects of maybe_begin_member_template_processing.  */
505
506 void
507 maybe_end_member_template_processing (void)
508 {
509   int i;
510   int last;
511
512   if (inline_parm_levels.length () == 0)
513     return;
514
515   last = inline_parm_levels.pop ();
516   for (i = 0; i < last; ++i)
517     {
518       --processing_template_decl;
519       current_template_parms = TREE_CHAIN (current_template_parms);
520       poplevel (0, 0, 0);
521     }
522 }
523
524 /* Return a new template argument vector which contains all of ARGS,
525    but has as its innermost set of arguments the EXTRA_ARGS.  */
526
527 static tree
528 add_to_template_args (tree args, tree extra_args)
529 {
530   tree new_args;
531   int extra_depth;
532   int i;
533   int j;
534
535   if (args == NULL_TREE || extra_args == error_mark_node)
536     return extra_args;
537
538   extra_depth = TMPL_ARGS_DEPTH (extra_args);
539   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
540
541   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
542     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
543
544   for (j = 1; j <= extra_depth; ++j, ++i)
545     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
546
547   return new_args;
548 }
549
550 /* Like add_to_template_args, but only the outermost ARGS are added to
551    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
552    (EXTRA_ARGS) levels are added.  This function is used to combine
553    the template arguments from a partial instantiation with the
554    template arguments used to attain the full instantiation from the
555    partial instantiation.  */
556
557 static tree
558 add_outermost_template_args (tree args, tree extra_args)
559 {
560   tree new_args;
561
562   /* If there are more levels of EXTRA_ARGS than there are ARGS,
563      something very fishy is going on.  */
564   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
565
566   /* If *all* the new arguments will be the EXTRA_ARGS, just return
567      them.  */
568   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
569     return extra_args;
570
571   /* For the moment, we make ARGS look like it contains fewer levels.  */
572   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
573
574   new_args = add_to_template_args (args, extra_args);
575
576   /* Now, we restore ARGS to its full dimensions.  */
577   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
578
579   return new_args;
580 }
581
582 /* Return the N levels of innermost template arguments from the ARGS.  */
583
584 tree
585 get_innermost_template_args (tree args, int n)
586 {
587   tree new_args;
588   int extra_levels;
589   int i;
590
591   gcc_assert (n >= 0);
592
593   /* If N is 1, just return the innermost set of template arguments.  */
594   if (n == 1)
595     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
596
597   /* If we're not removing anything, just return the arguments we were
598      given.  */
599   extra_levels = TMPL_ARGS_DEPTH (args) - n;
600   gcc_assert (extra_levels >= 0);
601   if (extra_levels == 0)
602     return args;
603
604   /* Make a new set of arguments, not containing the outer arguments.  */
605   new_args = make_tree_vec (n);
606   for (i = 1; i <= n; ++i)
607     SET_TMPL_ARGS_LEVEL (new_args, i,
608                          TMPL_ARGS_LEVEL (args, i + extra_levels));
609
610   return new_args;
611 }
612
613 /* The inverse of get_innermost_template_args: Return all but the innermost
614    EXTRA_LEVELS levels of template arguments from the ARGS.  */
615
616 static tree
617 strip_innermost_template_args (tree args, int extra_levels)
618 {
619   tree new_args;
620   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
621   int i;
622
623   gcc_assert (n >= 0);
624
625   /* If N is 1, just return the outermost set of template arguments.  */
626   if (n == 1)
627     return TMPL_ARGS_LEVEL (args, 1);
628
629   /* If we're not removing anything, just return the arguments we were
630      given.  */
631   gcc_assert (extra_levels >= 0);
632   if (extra_levels == 0)
633     return args;
634
635   /* Make a new set of arguments, not containing the inner arguments.  */
636   new_args = make_tree_vec (n);
637   for (i = 1; i <= n; ++i)
638     SET_TMPL_ARGS_LEVEL (new_args, i,
639                          TMPL_ARGS_LEVEL (args, i));
640
641   return new_args;
642 }
643
644 /* We've got a template header coming up; push to a new level for storing
645    the parms.  */
646
647 void
648 begin_template_parm_list (void)
649 {
650   /* We use a non-tag-transparent scope here, which causes pushtag to
651      put tags in this scope, rather than in the enclosing class or
652      namespace scope.  This is the right thing, since we want
653      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
654      global template class, push_template_decl handles putting the
655      TEMPLATE_DECL into top-level scope.  For a nested template class,
656      e.g.:
657
658        template <class T> struct S1 {
659          template <class T> struct S2 {};
660        };
661
662      pushtag contains special code to call pushdecl_with_scope on the
663      TEMPLATE_DECL for S2.  */
664   begin_scope (sk_template_parms, NULL);
665   ++processing_template_decl;
666   ++processing_template_parmlist;
667   note_template_header (0);
668 }
669
670 /* This routine is called when a specialization is declared.  If it is
671    invalid to declare a specialization here, an error is reported and
672    false is returned, otherwise this routine will return true.  */
673
674 static bool
675 check_specialization_scope (void)
676 {
677   tree scope = current_scope ();
678
679   /* [temp.expl.spec]
680
681      An explicit specialization shall be declared in the namespace of
682      which the template is a member, or, for member templates, in the
683      namespace of which the enclosing class or enclosing class
684      template is a member.  An explicit specialization of a member
685      function, member class or static data member of a class template
686      shall be declared in the namespace of which the class template
687      is a member.  */
688   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
689     {
690       error ("explicit specialization in non-namespace scope %qD", scope);
691       return false;
692     }
693
694   /* [temp.expl.spec]
695
696      In an explicit specialization declaration for a member of a class
697      template or a member template that appears in namespace scope,
698      the member template and some of its enclosing class templates may
699      remain unspecialized, except that the declaration shall not
700      explicitly specialize a class member template if its enclosing
701      class templates are not explicitly specialized as well.  */
702   if (current_template_parms)
703     {
704       error ("enclosing class templates are not explicitly specialized");
705       return false;
706     }
707
708   return true;
709 }
710
711 /* We've just seen template <>.  */
712
713 bool
714 begin_specialization (void)
715 {
716   begin_scope (sk_template_spec, NULL);
717   note_template_header (1);
718   return check_specialization_scope ();
719 }
720
721 /* Called at then end of processing a declaration preceded by
722    template<>.  */
723
724 void
725 end_specialization (void)
726 {
727   finish_scope ();
728   reset_specialization ();
729 }
730
731 /* Any template <>'s that we have seen thus far are not referring to a
732    function specialization.  */
733
734 void
735 reset_specialization (void)
736 {
737   processing_specialization = 0;
738   template_header_count = 0;
739 }
740
741 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
742    it was of the form template <>.  */
743
744 static void
745 note_template_header (int specialization)
746 {
747   processing_specialization = specialization;
748   template_header_count++;
749 }
750
751 /* We're beginning an explicit instantiation.  */
752
753 void
754 begin_explicit_instantiation (void)
755 {
756   gcc_assert (!processing_explicit_instantiation);
757   processing_explicit_instantiation = true;
758 }
759
760
761 void
762 end_explicit_instantiation (void)
763 {
764   gcc_assert (processing_explicit_instantiation);
765   processing_explicit_instantiation = false;
766 }
767
768 /* An explicit specialization or partial specialization of TMPL is being
769    declared.  Check that the namespace in which the specialization is
770    occurring is permissible.  Returns false iff it is invalid to
771    specialize TMPL in the current namespace.  */
772
773 static bool
774 check_specialization_namespace (tree tmpl)
775 {
776   tree tpl_ns = decl_namespace_context (tmpl);
777
778   /* [tmpl.expl.spec]
779
780      An explicit specialization shall be declared in the namespace of
781      which the template is a member, or, for member templates, in the
782      namespace of which the enclosing class or enclosing class
783      template is a member.  An explicit specialization of a member
784      function, member class or static data member of a class template
785      shall be declared in the namespace of which the class template is
786      a member.  */
787   if (current_scope() != DECL_CONTEXT (tmpl)
788       && !at_namespace_scope_p ())
789     {
790       error ("specialization of %qD must appear at namespace scope", tmpl);
791       return false;
792     }
793   if (is_associated_namespace (current_namespace, tpl_ns))
794     /* Same or super-using namespace.  */
795     return true;
796   else
797     {
798       permerror (input_location, "specialization of %qD in different namespace", tmpl);
799       permerror (input_location, "  from definition of %q+#D", tmpl);
800       return false;
801     }
802 }
803
804 /* SPEC is an explicit instantiation.  Check that it is valid to
805    perform this explicit instantiation in the current namespace.  */
806
807 static void
808 check_explicit_instantiation_namespace (tree spec)
809 {
810   tree ns;
811
812   /* DR 275: An explicit instantiation shall appear in an enclosing
813      namespace of its template.  */
814   ns = decl_namespace_context (spec);
815   if (!is_ancestor (current_namespace, ns))
816     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
817                "(which does not enclose namespace %qD)",
818                spec, current_namespace, ns);
819 }
820
821 /* The TYPE is being declared.  If it is a template type, that means it
822    is a partial specialization.  Do appropriate error-checking.  */
823
824 tree
825 maybe_process_partial_specialization (tree type)
826 {
827   tree context;
828
829   if (type == error_mark_node)
830     return error_mark_node;
831
832   /* A lambda that appears in specialization context is not itself a
833      specialization.  */
834   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
835     return type;
836
837   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
838     {
839       error ("name of class shadows template template parameter %qD",
840              TYPE_NAME (type));
841       return error_mark_node;
842     }
843
844   context = TYPE_CONTEXT (type);
845
846   if (TYPE_ALIAS_P (type))
847     {
848       if (TYPE_TEMPLATE_INFO (type)
849           && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
850         error ("specialization of alias template %qD",
851                TYPE_TI_TEMPLATE (type));
852       else
853         error ("explicit specialization of non-template %qT", type);
854       return error_mark_node;
855     }
856   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
857     {
858       /* This is for ordinary explicit specialization and partial
859          specialization of a template class such as:
860
861            template <> class C<int>;
862
863          or:
864
865            template <class T> class C<T*>;
866
867          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
868
869       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
870           && !COMPLETE_TYPE_P (type))
871         {
872           if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
873               && !at_namespace_scope_p ())
874             return error_mark_node;
875           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
876           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
877           if (processing_template_decl)
878             {
879               if (push_template_decl (TYPE_MAIN_DECL (type))
880                   == error_mark_node)
881                 return error_mark_node;
882             }
883         }
884       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
885         error ("specialization of %qT after instantiation", type);
886       else if (errorcount && !processing_specialization
887                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
888                && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
889         /* Trying to define a specialization either without a template<> header
890            or in an inappropriate place.  We've already given an error, so just
891            bail now so we don't actually define the specialization.  */
892         return error_mark_node;
893     }
894   else if (CLASS_TYPE_P (type)
895            && !CLASSTYPE_USE_TEMPLATE (type)
896            && CLASSTYPE_TEMPLATE_INFO (type)
897            && context && CLASS_TYPE_P (context)
898            && CLASSTYPE_TEMPLATE_INFO (context))
899     {
900       /* This is for an explicit specialization of member class
901          template according to [temp.expl.spec/18]:
902
903            template <> template <class U> class C<int>::D;
904
905          The context `C<int>' must be an implicit instantiation.
906          Otherwise this is just a member class template declared
907          earlier like:
908
909            template <> class C<int> { template <class U> class D; };
910            template <> template <class U> class C<int>::D;
911
912          In the first case, `C<int>::D' is a specialization of `C<T>::D'
913          while in the second case, `C<int>::D' is a primary template
914          and `C<T>::D' may not exist.  */
915
916       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
917           && !COMPLETE_TYPE_P (type))
918         {
919           tree t;
920           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
921
922           if (current_namespace
923               != decl_namespace_context (tmpl))
924             {
925               permerror (input_location, "specializing %q#T in different namespace", type);
926               permerror (input_location, "  from definition of %q+#D", tmpl);
927             }
928
929           /* Check for invalid specialization after instantiation:
930
931                template <> template <> class C<int>::D<int>;
932                template <> template <class U> class C<int>::D;  */
933
934           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
935                t; t = TREE_CHAIN (t))
936             {
937               tree inst = TREE_VALUE (t);
938               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
939                   || !COMPLETE_OR_OPEN_TYPE_P (inst))
940                 {
941                   /* We already have a full specialization of this partial
942                      instantiation, or a full specialization has been
943                      looked up but not instantiated.  Reassign it to the
944                      new member specialization template.  */
945                   spec_entry elt;
946                   spec_entry *entry;
947
948                   elt.tmpl = most_general_template (tmpl);
949                   elt.args = CLASSTYPE_TI_ARGS (inst);
950                   elt.spec = inst;
951
952                   type_specializations->remove_elt (&elt);
953
954                   elt.tmpl = tmpl;
955                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
956
957                   spec_entry **slot
958                     = type_specializations->find_slot (&elt, INSERT);
959                   entry = ggc_alloc<spec_entry> ();
960                   *entry = elt;
961                   *slot = entry;
962                 }
963               else
964                 /* But if we've had an implicit instantiation, that's a
965                    problem ([temp.expl.spec]/6).  */
966                 error ("specialization %qT after instantiation %qT",
967                        type, inst);
968             }
969
970           /* Mark TYPE as a specialization.  And as a result, we only
971              have one level of template argument for the innermost
972              class template.  */
973           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
974           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
975           CLASSTYPE_TI_ARGS (type)
976             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
977         }
978     }
979   else if (processing_specialization)
980     {
981        /* Someday C++0x may allow for enum template specialization.  */
982       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
983           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
984         pedwarn (input_location, OPT_Wpedantic, "template specialization "
985                  "of %qD not allowed by ISO C++", type);
986       else
987         {
988           error ("explicit specialization of non-template %qT", type);
989           return error_mark_node;
990         }
991     }
992
993   return type;
994 }
995
996 /* Returns nonzero if we can optimize the retrieval of specializations
997    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
998    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
999
1000 static inline bool
1001 optimize_specialization_lookup_p (tree tmpl)
1002 {
1003   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1004           && DECL_CLASS_SCOPE_P (tmpl)
1005           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1006              parameter.  */
1007           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1008           /* The optimized lookup depends on the fact that the
1009              template arguments for the member function template apply
1010              purely to the containing class, which is not true if the
1011              containing class is an explicit or partial
1012              specialization.  */
1013           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1014           && !DECL_MEMBER_TEMPLATE_P (tmpl)
1015           && !DECL_CONV_FN_P (tmpl)
1016           /* It is possible to have a template that is not a member
1017              template and is not a member of a template class:
1018
1019              template <typename T>
1020              struct S { friend A::f(); };
1021
1022              Here, the friend function is a template, but the context does
1023              not have template information.  The optimized lookup relies
1024              on having ARGS be the template arguments for both the class
1025              and the function template.  */
1026           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1027 }
1028
1029 /* Retrieve the specialization (in the sense of [temp.spec] - a
1030    specialization is either an instantiation or an explicit
1031    specialization) of TMPL for the given template ARGS.  If there is
1032    no such specialization, return NULL_TREE.  The ARGS are a vector of
1033    arguments, or a vector of vectors of arguments, in the case of
1034    templates with more than one level of parameters.
1035
1036    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1037    then we search for a partial specialization matching ARGS.  This
1038    parameter is ignored if TMPL is not a class template.
1039
1040    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1041    result is a NONTYPE_ARGUMENT_PACK.  */
1042
1043 static tree
1044 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1045 {
1046   if (tmpl == NULL_TREE)
1047     return NULL_TREE;
1048
1049   if (args == error_mark_node)
1050     return NULL_TREE;
1051
1052   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1053               || TREE_CODE (tmpl) == FIELD_DECL);
1054
1055   /* There should be as many levels of arguments as there are
1056      levels of parameters.  */
1057   gcc_assert (TMPL_ARGS_DEPTH (args)
1058               == (TREE_CODE (tmpl) == TEMPLATE_DECL
1059                   ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1060                   : template_class_depth (DECL_CONTEXT (tmpl))));
1061
1062   if (optimize_specialization_lookup_p (tmpl))
1063     {
1064       tree class_template;
1065       tree class_specialization;
1066       vec<tree, va_gc> *methods;
1067       tree fns;
1068       int idx;
1069
1070       /* The template arguments actually apply to the containing
1071          class.  Find the class specialization with those
1072          arguments.  */
1073       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1074       class_specialization
1075         = retrieve_specialization (class_template, args, 0);
1076       if (!class_specialization)
1077         return NULL_TREE;
1078       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1079          for the specialization.  */
1080       idx = class_method_index_for_fn (class_specialization, tmpl);
1081       if (idx == -1)
1082         return NULL_TREE;
1083       /* Iterate through the methods with the indicated name, looking
1084          for the one that has an instance of TMPL.  */
1085       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1086       for (fns = (*methods)[idx]; fns; fns = OVL_NEXT (fns))
1087         {
1088           tree fn = OVL_CURRENT (fns);
1089           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1090               /* using-declarations can add base methods to the method vec,
1091                  and we don't want those here.  */
1092               && DECL_CONTEXT (fn) == class_specialization)
1093             return fn;
1094         }
1095       return NULL_TREE;
1096     }
1097   else
1098     {
1099       spec_entry *found;
1100       spec_entry elt;
1101       hash_table<spec_hasher> *specializations;
1102
1103       elt.tmpl = tmpl;
1104       elt.args = args;
1105       elt.spec = NULL_TREE;
1106
1107       if (DECL_CLASS_TEMPLATE_P (tmpl))
1108         specializations = type_specializations;
1109       else
1110         specializations = decl_specializations;
1111
1112       if (hash == 0)
1113         hash = spec_hasher::hash (&elt);
1114       found = specializations->find_with_hash (&elt, hash);
1115       if (found)
1116         return found->spec;
1117     }
1118
1119   return NULL_TREE;
1120 }
1121
1122 /* Like retrieve_specialization, but for local declarations.  */
1123
1124 static tree
1125 retrieve_local_specialization (tree tmpl)
1126 {
1127   if (local_specializations == NULL)
1128     return NULL_TREE;
1129
1130   tree *slot = local_specializations->get (tmpl);
1131   return slot ? *slot : NULL_TREE;
1132 }
1133
1134 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1135
1136 int
1137 is_specialization_of (tree decl, tree tmpl)
1138 {
1139   tree t;
1140
1141   if (TREE_CODE (decl) == FUNCTION_DECL)
1142     {
1143       for (t = decl;
1144            t != NULL_TREE;
1145            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1146         if (t == tmpl)
1147           return 1;
1148     }
1149   else
1150     {
1151       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1152
1153       for (t = TREE_TYPE (decl);
1154            t != NULL_TREE;
1155            t = CLASSTYPE_USE_TEMPLATE (t)
1156              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1157         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1158           return 1;
1159     }
1160
1161   return 0;
1162 }
1163
1164 /* Returns nonzero iff DECL is a specialization of friend declaration
1165    FRIEND_DECL according to [temp.friend].  */
1166
1167 bool
1168 is_specialization_of_friend (tree decl, tree friend_decl)
1169 {
1170   bool need_template = true;
1171   int template_depth;
1172
1173   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1174               || TREE_CODE (decl) == TYPE_DECL);
1175
1176   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1177      of a template class, we want to check if DECL is a specialization
1178      if this.  */
1179   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1180       && DECL_TEMPLATE_INFO (friend_decl)
1181       && !DECL_USE_TEMPLATE (friend_decl))
1182     {
1183       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1184       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1185       need_template = false;
1186     }
1187   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1188            && !PRIMARY_TEMPLATE_P (friend_decl))
1189     need_template = false;
1190
1191   /* There is nothing to do if this is not a template friend.  */
1192   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1193     return false;
1194
1195   if (is_specialization_of (decl, friend_decl))
1196     return true;
1197
1198   /* [temp.friend/6]
1199      A member of a class template may be declared to be a friend of a
1200      non-template class.  In this case, the corresponding member of
1201      every specialization of the class template is a friend of the
1202      class granting friendship.
1203
1204      For example, given a template friend declaration
1205
1206        template <class T> friend void A<T>::f();
1207
1208      the member function below is considered a friend
1209
1210        template <> struct A<int> {
1211          void f();
1212        };
1213
1214      For this type of template friend, TEMPLATE_DEPTH below will be
1215      nonzero.  To determine if DECL is a friend of FRIEND, we first
1216      check if the enclosing class is a specialization of another.  */
1217
1218   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1219   if (template_depth
1220       && DECL_CLASS_SCOPE_P (decl)
1221       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1222                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1223     {
1224       /* Next, we check the members themselves.  In order to handle
1225          a few tricky cases, such as when FRIEND_DECL's are
1226
1227            template <class T> friend void A<T>::g(T t);
1228            template <class T> template <T t> friend void A<T>::h();
1229
1230          and DECL's are
1231
1232            void A<int>::g(int);
1233            template <int> void A<int>::h();
1234
1235          we need to figure out ARGS, the template arguments from
1236          the context of DECL.  This is required for template substitution
1237          of `T' in the function parameter of `g' and template parameter
1238          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1239
1240       tree context = DECL_CONTEXT (decl);
1241       tree args = NULL_TREE;
1242       int current_depth = 0;
1243
1244       while (current_depth < template_depth)
1245         {
1246           if (CLASSTYPE_TEMPLATE_INFO (context))
1247             {
1248               if (current_depth == 0)
1249                 args = TYPE_TI_ARGS (context);
1250               else
1251                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1252               current_depth++;
1253             }
1254           context = TYPE_CONTEXT (context);
1255         }
1256
1257       if (TREE_CODE (decl) == FUNCTION_DECL)
1258         {
1259           bool is_template;
1260           tree friend_type;
1261           tree decl_type;
1262           tree friend_args_type;
1263           tree decl_args_type;
1264
1265           /* Make sure that both DECL and FRIEND_DECL are templates or
1266              non-templates.  */
1267           is_template = DECL_TEMPLATE_INFO (decl)
1268                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1269           if (need_template ^ is_template)
1270             return false;
1271           else if (is_template)
1272             {
1273               /* If both are templates, check template parameter list.  */
1274               tree friend_parms
1275                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1276                                          args, tf_none);
1277               if (!comp_template_parms
1278                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1279                       friend_parms))
1280                 return false;
1281
1282               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1283             }
1284           else
1285             decl_type = TREE_TYPE (decl);
1286
1287           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1288                                               tf_none, NULL_TREE);
1289           if (friend_type == error_mark_node)
1290             return false;
1291
1292           /* Check if return types match.  */
1293           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1294             return false;
1295
1296           /* Check if function parameter types match, ignoring the
1297              `this' parameter.  */
1298           friend_args_type = TYPE_ARG_TYPES (friend_type);
1299           decl_args_type = TYPE_ARG_TYPES (decl_type);
1300           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1301             friend_args_type = TREE_CHAIN (friend_args_type);
1302           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1303             decl_args_type = TREE_CHAIN (decl_args_type);
1304
1305           return compparms (decl_args_type, friend_args_type);
1306         }
1307       else
1308         {
1309           /* DECL is a TYPE_DECL */
1310           bool is_template;
1311           tree decl_type = TREE_TYPE (decl);
1312
1313           /* Make sure that both DECL and FRIEND_DECL are templates or
1314              non-templates.  */
1315           is_template
1316             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1317               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1318
1319           if (need_template ^ is_template)
1320             return false;
1321           else if (is_template)
1322             {
1323               tree friend_parms;
1324               /* If both are templates, check the name of the two
1325                  TEMPLATE_DECL's first because is_friend didn't.  */
1326               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1327                   != DECL_NAME (friend_decl))
1328                 return false;
1329
1330               /* Now check template parameter list.  */
1331               friend_parms
1332                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1333                                          args, tf_none);
1334               return comp_template_parms
1335                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1336                  friend_parms);
1337             }
1338           else
1339             return (DECL_NAME (decl)
1340                     == DECL_NAME (friend_decl));
1341         }
1342     }
1343   return false;
1344 }
1345
1346 /* Register the specialization SPEC as a specialization of TMPL with
1347    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1348    is actually just a friend declaration.  Returns SPEC, or an
1349    equivalent prior declaration, if available.
1350
1351    We also store instantiations of field packs in the hash table, even
1352    though they are not themselves templates, to make lookup easier.  */
1353
1354 static tree
1355 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1356                          hashval_t hash)
1357 {
1358   tree fn;
1359   spec_entry **slot = NULL;
1360   spec_entry elt;
1361
1362   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1363               || (TREE_CODE (tmpl) == FIELD_DECL
1364                   && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1365
1366   if (TREE_CODE (spec) == FUNCTION_DECL
1367       && uses_template_parms (DECL_TI_ARGS (spec)))
1368     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1369        register it; we want the corresponding TEMPLATE_DECL instead.
1370        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1371        the more obvious `uses_template_parms (spec)' to avoid problems
1372        with default function arguments.  In particular, given
1373        something like this:
1374
1375           template <class T> void f(T t1, T t = T())
1376
1377        the default argument expression is not substituted for in an
1378        instantiation unless and until it is actually needed.  */
1379     return spec;
1380
1381   if (optimize_specialization_lookup_p (tmpl))
1382     /* We don't put these specializations in the hash table, but we might
1383        want to give an error about a mismatch.  */
1384     fn = retrieve_specialization (tmpl, args, 0);
1385   else
1386     {
1387       elt.tmpl = tmpl;
1388       elt.args = args;
1389       elt.spec = spec;
1390
1391       if (hash == 0)
1392         hash = spec_hasher::hash (&elt);
1393
1394       slot =
1395         decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1396       if (*slot)
1397         fn = ((spec_entry *) *slot)->spec;
1398       else
1399         fn = NULL_TREE;
1400     }
1401
1402   /* We can sometimes try to re-register a specialization that we've
1403      already got.  In particular, regenerate_decl_from_template calls
1404      duplicate_decls which will update the specialization list.  But,
1405      we'll still get called again here anyhow.  It's more convenient
1406      to simply allow this than to try to prevent it.  */
1407   if (fn == spec)
1408     return spec;
1409   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1410     {
1411       if (DECL_TEMPLATE_INSTANTIATION (fn))
1412         {
1413           if (DECL_ODR_USED (fn)
1414               || DECL_EXPLICIT_INSTANTIATION (fn))
1415             {
1416               error ("specialization of %qD after instantiation",
1417                      fn);
1418               return error_mark_node;
1419             }
1420           else
1421             {
1422               tree clone;
1423               /* This situation should occur only if the first
1424                  specialization is an implicit instantiation, the
1425                  second is an explicit specialization, and the
1426                  implicit instantiation has not yet been used.  That
1427                  situation can occur if we have implicitly
1428                  instantiated a member function and then specialized
1429                  it later.
1430
1431                  We can also wind up here if a friend declaration that
1432                  looked like an instantiation turns out to be a
1433                  specialization:
1434
1435                    template <class T> void foo(T);
1436                    class S { friend void foo<>(int) };
1437                    template <> void foo(int);
1438
1439                  We transform the existing DECL in place so that any
1440                  pointers to it become pointers to the updated
1441                  declaration.
1442
1443                  If there was a definition for the template, but not
1444                  for the specialization, we want this to look as if
1445                  there were no definition, and vice versa.  */
1446               DECL_INITIAL (fn) = NULL_TREE;
1447               duplicate_decls (spec, fn, is_friend);
1448               /* The call to duplicate_decls will have applied
1449                  [temp.expl.spec]:
1450
1451                    An explicit specialization of a function template
1452                    is inline only if it is explicitly declared to be,
1453                    and independently of whether its function template
1454                    is.
1455
1456                 to the primary function; now copy the inline bits to
1457                 the various clones.  */
1458               FOR_EACH_CLONE (clone, fn)
1459                 {
1460                   DECL_DECLARED_INLINE_P (clone)
1461                     = DECL_DECLARED_INLINE_P (fn);
1462                   DECL_SOURCE_LOCATION (clone)
1463                     = DECL_SOURCE_LOCATION (fn);
1464                   DECL_DELETED_FN (clone)
1465                     = DECL_DELETED_FN (fn);
1466                 }
1467               check_specialization_namespace (tmpl);
1468
1469               return fn;
1470             }
1471         }
1472       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1473         {
1474           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1475             /* Dup decl failed, but this is a new definition. Set the
1476                line number so any errors match this new
1477                definition.  */
1478             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1479
1480           return fn;
1481         }
1482     }
1483   else if (fn)
1484     return duplicate_decls (spec, fn, is_friend);
1485
1486   /* A specialization must be declared in the same namespace as the
1487      template it is specializing.  */
1488   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1489       && !check_specialization_namespace (tmpl))
1490     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1491
1492   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1493     {
1494       spec_entry *entry = ggc_alloc<spec_entry> ();
1495       gcc_assert (tmpl && args && spec);
1496       *entry = elt;
1497       *slot = entry;
1498       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1499            && PRIMARY_TEMPLATE_P (tmpl)
1500            && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1501           || variable_template_p (tmpl))
1502         /* If TMPL is a forward declaration of a template function, keep a list
1503            of all specializations in case we need to reassign them to a friend
1504            template later in tsubst_friend_function.
1505
1506            Also keep a list of all variable template instantiations so that
1507            process_partial_specialization can check whether a later partial
1508            specialization would have used it.  */
1509         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1510           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1511     }
1512
1513   return spec;
1514 }
1515
1516 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1517    TMPL and ARGS members, ignores SPEC.  */
1518
1519 int comparing_specializations;
1520
1521 bool
1522 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1523 {
1524   int equal;
1525
1526   ++comparing_specializations;
1527   equal = (e1->tmpl == e2->tmpl
1528            && comp_template_args (e1->args, e2->args));
1529   --comparing_specializations;
1530
1531   return equal;
1532 }
1533
1534 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1535
1536 static hashval_t
1537 hash_tmpl_and_args (tree tmpl, tree args)
1538 {
1539   hashval_t val = DECL_UID (tmpl);
1540   return iterative_hash_template_arg (args, val);
1541 }
1542
1543 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1544    ignoring SPEC.  */
1545
1546 hashval_t
1547 spec_hasher::hash (spec_entry *e)
1548 {
1549   return hash_tmpl_and_args (e->tmpl, e->args);
1550 }
1551
1552 /* Recursively calculate a hash value for a template argument ARG, for use
1553    in the hash tables of template specializations.  */
1554
1555 hashval_t
1556 iterative_hash_template_arg (tree arg, hashval_t val)
1557 {
1558   unsigned HOST_WIDE_INT i;
1559   enum tree_code code;
1560   char tclass;
1561
1562   if (arg == NULL_TREE)
1563     return iterative_hash_object (arg, val);
1564
1565   if (!TYPE_P (arg))
1566     STRIP_NOPS (arg);
1567
1568   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1569     /* We can get one of these when re-hashing a previous entry in the middle
1570        of substituting into a pack expansion.  Just look through it.  */
1571     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1572
1573   code = TREE_CODE (arg);
1574   tclass = TREE_CODE_CLASS (code);
1575
1576   val = iterative_hash_object (code, val);
1577
1578   switch (code)
1579     {
1580     case ERROR_MARK:
1581       return val;
1582
1583     case IDENTIFIER_NODE:
1584       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1585
1586     case TREE_VEC:
1587       {
1588         int i, len = TREE_VEC_LENGTH (arg);
1589         for (i = 0; i < len; ++i)
1590           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1591         return val;
1592       }
1593
1594     case TYPE_PACK_EXPANSION:
1595     case EXPR_PACK_EXPANSION:
1596       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1597       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1598
1599     case TYPE_ARGUMENT_PACK:
1600     case NONTYPE_ARGUMENT_PACK:
1601       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1602
1603     case TREE_LIST:
1604       for (; arg; arg = TREE_CHAIN (arg))
1605         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1606       return val;
1607
1608     case OVERLOAD:
1609       for (; arg; arg = OVL_NEXT (arg))
1610         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1611       return val;
1612
1613     case CONSTRUCTOR:
1614       {
1615         tree field, value;
1616         iterative_hash_template_arg (TREE_TYPE (arg), val);
1617         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1618           {
1619             val = iterative_hash_template_arg (field, val);
1620             val = iterative_hash_template_arg (value, val);
1621           }
1622         return val;
1623       }
1624
1625     case PARM_DECL:
1626       if (!DECL_ARTIFICIAL (arg))
1627         {
1628           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1629           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1630         }
1631       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1632
1633     case TARGET_EXPR:
1634       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1635
1636     case PTRMEM_CST:
1637       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1638       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1639
1640     case TEMPLATE_PARM_INDEX:
1641       val = iterative_hash_template_arg
1642         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1643       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1644       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1645
1646     case TRAIT_EXPR:
1647       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1648       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1649       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1650
1651     case BASELINK:
1652       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1653                                          val);
1654       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1655                                           val);
1656
1657     case MODOP_EXPR:
1658       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1659       code = TREE_CODE (TREE_OPERAND (arg, 1));
1660       val = iterative_hash_object (code, val);
1661       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1662
1663     case LAMBDA_EXPR:
1664       /* A lambda can't appear in a template arg, but don't crash on
1665          erroneous input.  */
1666       gcc_assert (seen_error ());
1667       return val;
1668
1669     case CAST_EXPR:
1670     case IMPLICIT_CONV_EXPR:
1671     case STATIC_CAST_EXPR:
1672     case REINTERPRET_CAST_EXPR:
1673     case CONST_CAST_EXPR:
1674     case DYNAMIC_CAST_EXPR:
1675     case NEW_EXPR:
1676       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1677       /* Now hash operands as usual.  */
1678       break;
1679
1680     default:
1681       break;
1682     }
1683
1684   switch (tclass)
1685     {
1686     case tcc_type:
1687       if (alias_template_specialization_p (arg))
1688         {
1689           // We want an alias specialization that survived strip_typedefs
1690           // to hash differently from its TYPE_CANONICAL, to avoid hash
1691           // collisions that compare as different in template_args_equal.
1692           // These could be dependent specializations that strip_typedefs
1693           // left alone, or untouched specializations because
1694           // coerce_template_parms returns the unconverted template
1695           // arguments if it sees incomplete argument packs.
1696           tree ti = TYPE_TEMPLATE_INFO (arg);
1697           return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1698         }
1699       if (TYPE_CANONICAL (arg))
1700         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1701                                       val);
1702       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1703         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1704       /* Otherwise just compare the types during lookup.  */
1705       return val;
1706
1707     case tcc_declaration:
1708     case tcc_constant:
1709       return iterative_hash_expr (arg, val);
1710
1711     default:
1712       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1713       {
1714         unsigned n = cp_tree_operand_length (arg);
1715         for (i = 0; i < n; ++i)
1716           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1717         return val;
1718       }
1719     }
1720   gcc_unreachable ();
1721   return 0;
1722 }
1723
1724 /* Unregister the specialization SPEC as a specialization of TMPL.
1725    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1726    if the SPEC was listed as a specialization of TMPL.
1727
1728    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1729
1730 bool
1731 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1732 {
1733   spec_entry *entry;
1734   spec_entry elt;
1735
1736   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1737   elt.args = TI_ARGS (tinfo);
1738   elt.spec = NULL_TREE;
1739
1740   entry = decl_specializations->find (&elt);
1741   if (entry != NULL)
1742     {
1743       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1744       gcc_assert (new_spec != NULL_TREE);
1745       entry->spec = new_spec;
1746       return 1;
1747     }
1748
1749   return 0;
1750 }
1751
1752 /* Like register_specialization, but for local declarations.  We are
1753    registering SPEC, an instantiation of TMPL.  */
1754
1755 static void
1756 register_local_specialization (tree spec, tree tmpl)
1757 {
1758   local_specializations->put (tmpl, spec);
1759 }
1760
1761 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1762    specialized class.  */
1763
1764 bool
1765 explicit_class_specialization_p (tree type)
1766 {
1767   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1768     return false;
1769   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1770 }
1771
1772 /* Print the list of functions at FNS, going through all the overloads
1773    for each element of the list.  Alternatively, FNS can not be a
1774    TREE_LIST, in which case it will be printed together with all the
1775    overloads.
1776
1777    MORE and *STR should respectively be FALSE and NULL when the function
1778    is called from the outside.  They are used internally on recursive
1779    calls.  print_candidates manages the two parameters and leaves NULL
1780    in *STR when it ends.  */
1781
1782 static void
1783 print_candidates_1 (tree fns, bool more, const char **str)
1784 {
1785   tree fn, fn2;
1786   char *spaces = NULL;
1787
1788   for (fn = fns; fn; fn = OVL_NEXT (fn))
1789     if (TREE_CODE (fn) == TREE_LIST)
1790       {
1791         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1792           print_candidates_1 (TREE_VALUE (fn2),
1793                               TREE_CHAIN (fn2) || more, str);
1794       }
1795     else
1796       {
1797         tree cand = OVL_CURRENT (fn);
1798         if (!*str)
1799           {
1800             /* Pick the prefix string.  */
1801             if (!more && !OVL_NEXT (fns))
1802               {
1803                 inform (DECL_SOURCE_LOCATION (cand),
1804                         "candidate is: %#D", cand);
1805                 continue;
1806               }
1807
1808             *str = _("candidates are:");
1809             spaces = get_spaces (*str);
1810           }
1811         inform (DECL_SOURCE_LOCATION (cand), "%s %#D", *str, cand);
1812         *str = spaces ? spaces : *str;
1813       }
1814
1815   if (!more)
1816     {
1817       free (spaces);
1818       *str = NULL;
1819     }
1820 }
1821
1822 /* Print the list of candidate FNS in an error message.  FNS can also
1823    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1824
1825 void
1826 print_candidates (tree fns)
1827 {
1828   const char *str = NULL;
1829   print_candidates_1 (fns, false, &str);
1830   gcc_assert (str == NULL);
1831 }
1832
1833 /* Returns the template (one of the functions given by TEMPLATE_ID)
1834    which can be specialized to match the indicated DECL with the
1835    explicit template args given in TEMPLATE_ID.  The DECL may be
1836    NULL_TREE if none is available.  In that case, the functions in
1837    TEMPLATE_ID are non-members.
1838
1839    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1840    specialization of a member template.
1841
1842    The TEMPLATE_COUNT is the number of references to qualifying
1843    template classes that appeared in the name of the function. See
1844    check_explicit_specialization for a more accurate description.
1845
1846    TSK indicates what kind of template declaration (if any) is being
1847    declared.  TSK_TEMPLATE indicates that the declaration given by
1848    DECL, though a FUNCTION_DECL, has template parameters, and is
1849    therefore a template function.
1850
1851    The template args (those explicitly specified and those deduced)
1852    are output in a newly created vector *TARGS_OUT.
1853
1854    If it is impossible to determine the result, an error message is
1855    issued.  The error_mark_node is returned to indicate failure.  */
1856
1857 static tree
1858 determine_specialization (tree template_id,
1859                           tree decl,
1860                           tree* targs_out,
1861                           int need_member_template,
1862                           int template_count,
1863                           tmpl_spec_kind tsk)
1864 {
1865   tree fns;
1866   tree targs;
1867   tree explicit_targs;
1868   tree candidates = NULL_TREE;
1869   /* A TREE_LIST of templates of which DECL may be a specialization.
1870      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1871      corresponding TREE_PURPOSE is the set of template arguments that,
1872      when used to instantiate the template, would produce a function
1873      with the signature of DECL.  */
1874   tree templates = NULL_TREE;
1875   int header_count;
1876   cp_binding_level *b;
1877
1878   *targs_out = NULL_TREE;
1879
1880   if (template_id == error_mark_node || decl == error_mark_node)
1881     return error_mark_node;
1882
1883   /* We shouldn't be specializing a member template of an
1884      unspecialized class template; we already gave an error in
1885      check_specialization_scope, now avoid crashing.  */
1886   if (template_count && DECL_CLASS_SCOPE_P (decl)
1887       && template_class_depth (DECL_CONTEXT (decl)) > 0)
1888     {
1889       gcc_assert (errorcount);
1890       return error_mark_node;
1891     }
1892
1893   fns = TREE_OPERAND (template_id, 0);
1894   explicit_targs = TREE_OPERAND (template_id, 1);
1895
1896   if (fns == error_mark_node)
1897     return error_mark_node;
1898
1899   /* Check for baselinks.  */
1900   if (BASELINK_P (fns))
1901     fns = BASELINK_FUNCTIONS (fns);
1902
1903   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
1904     {
1905       error ("%qD is not a function template", fns);
1906       return error_mark_node;
1907     }
1908   else if (VAR_P (decl) && !variable_template_p (fns))
1909     {
1910       error ("%qD is not a variable template", fns);
1911       return error_mark_node;
1912     }
1913
1914   /* Count the number of template headers specified for this
1915      specialization.  */
1916   header_count = 0;
1917   for (b = current_binding_level;
1918        b->kind == sk_template_parms;
1919        b = b->level_chain)
1920     ++header_count;
1921
1922   if (variable_template_p (fns))
1923     {
1924       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
1925       targs = coerce_template_parms (parms, explicit_targs, fns,
1926                                      tf_warning_or_error,
1927                                      /*req_all*/true, /*use_defarg*/true);
1928       templates = tree_cons (targs, fns, templates);
1929     }
1930   else for (; fns; fns = OVL_NEXT (fns))
1931     {
1932       tree fn = OVL_CURRENT (fns);
1933
1934       if (TREE_CODE (fn) == TEMPLATE_DECL)
1935         {
1936           tree decl_arg_types;
1937           tree fn_arg_types;
1938           tree insttype;
1939
1940           /* In case of explicit specialization, we need to check if
1941              the number of template headers appearing in the specialization
1942              is correct. This is usually done in check_explicit_specialization,
1943              but the check done there cannot be exhaustive when specializing
1944              member functions. Consider the following code:
1945
1946              template <> void A<int>::f(int);
1947              template <> template <> void A<int>::f(int);
1948
1949              Assuming that A<int> is not itself an explicit specialization
1950              already, the first line specializes "f" which is a non-template
1951              member function, whilst the second line specializes "f" which
1952              is a template member function. So both lines are syntactically
1953              correct, and check_explicit_specialization does not reject
1954              them.
1955
1956              Here, we can do better, as we are matching the specialization
1957              against the declarations. We count the number of template
1958              headers, and we check if they match TEMPLATE_COUNT + 1
1959              (TEMPLATE_COUNT is the number of qualifying template classes,
1960              plus there must be another header for the member template
1961              itself).
1962
1963              Notice that if header_count is zero, this is not a
1964              specialization but rather a template instantiation, so there
1965              is no check we can perform here.  */
1966           if (header_count && header_count != template_count + 1)
1967             continue;
1968
1969           /* Check that the number of template arguments at the
1970              innermost level for DECL is the same as for FN.  */
1971           if (current_binding_level->kind == sk_template_parms
1972               && !current_binding_level->explicit_spec_p
1973               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1974                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1975                                       (current_template_parms))))
1976             continue;
1977
1978           /* DECL might be a specialization of FN.  */
1979           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1980           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1981
1982           /* For a non-static member function, we need to make sure
1983              that the const qualification is the same.  Since
1984              get_bindings does not try to merge the "this" parameter,
1985              we must do the comparison explicitly.  */
1986           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1987               && !same_type_p (TREE_VALUE (fn_arg_types),
1988                                TREE_VALUE (decl_arg_types)))
1989             continue;
1990
1991           /* Skip the "this" parameter and, for constructors of
1992              classes with virtual bases, the VTT parameter.  A
1993              full specialization of a constructor will have a VTT
1994              parameter, but a template never will.  */ 
1995           decl_arg_types 
1996             = skip_artificial_parms_for (decl, decl_arg_types);
1997           fn_arg_types 
1998             = skip_artificial_parms_for (fn, fn_arg_types);
1999
2000           /* Function templates cannot be specializations; there are
2001              no partial specializations of functions.  Therefore, if
2002              the type of DECL does not match FN, there is no
2003              match.  */
2004           if (tsk == tsk_template)
2005             {
2006               if (compparms (fn_arg_types, decl_arg_types))
2007                 candidates = tree_cons (NULL_TREE, fn, candidates);
2008               continue;
2009             }
2010
2011           /* See whether this function might be a specialization of this
2012              template.  Suppress access control because we might be trying
2013              to make this specialization a friend, and we have already done
2014              access control for the declaration of the specialization.  */
2015           push_deferring_access_checks (dk_no_check);
2016           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2017           pop_deferring_access_checks ();
2018
2019           if (!targs)
2020             /* We cannot deduce template arguments that when used to
2021                specialize TMPL will produce DECL.  */
2022             continue;
2023
2024           /* Make sure that the deduced arguments actually work.  */
2025           insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
2026           if (insttype == error_mark_node)
2027             continue;
2028           fn_arg_types
2029             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2030           if (!compparms (fn_arg_types, decl_arg_types))
2031             continue;
2032
2033           /* Save this template, and the arguments deduced.  */
2034           templates = tree_cons (targs, fn, templates);
2035         }
2036       else if (need_member_template)
2037         /* FN is an ordinary member function, and we need a
2038            specialization of a member template.  */
2039         ;
2040       else if (TREE_CODE (fn) != FUNCTION_DECL)
2041         /* We can get IDENTIFIER_NODEs here in certain erroneous
2042            cases.  */
2043         ;
2044       else if (!DECL_FUNCTION_MEMBER_P (fn))
2045         /* This is just an ordinary non-member function.  Nothing can
2046            be a specialization of that.  */
2047         ;
2048       else if (DECL_ARTIFICIAL (fn))
2049         /* Cannot specialize functions that are created implicitly.  */
2050         ;
2051       else
2052         {
2053           tree decl_arg_types;
2054
2055           /* This is an ordinary member function.  However, since
2056              we're here, we can assume its enclosing class is a
2057              template class.  For example,
2058
2059                template <typename T> struct S { void f(); };
2060                template <> void S<int>::f() {}
2061
2062              Here, S<int>::f is a non-template, but S<int> is a
2063              template class.  If FN has the same type as DECL, we
2064              might be in business.  */
2065
2066           if (!DECL_TEMPLATE_INFO (fn))
2067             /* Its enclosing class is an explicit specialization
2068                of a template class.  This is not a candidate.  */
2069             continue;
2070
2071           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2072                             TREE_TYPE (TREE_TYPE (fn))))
2073             /* The return types differ.  */
2074             continue;
2075
2076           /* Adjust the type of DECL in case FN is a static member.  */
2077           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2078           if (DECL_STATIC_FUNCTION_P (fn)
2079               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2080             decl_arg_types = TREE_CHAIN (decl_arg_types);
2081
2082           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2083                          decl_arg_types))
2084             /* They match!  */
2085             candidates = tree_cons (NULL_TREE, fn, candidates);
2086         }
2087     }
2088
2089   if (templates && TREE_CHAIN (templates))
2090     {
2091       /* We have:
2092
2093            [temp.expl.spec]
2094
2095            It is possible for a specialization with a given function
2096            signature to be instantiated from more than one function
2097            template.  In such cases, explicit specification of the
2098            template arguments must be used to uniquely identify the
2099            function template specialization being specialized.
2100
2101          Note that here, there's no suggestion that we're supposed to
2102          determine which of the candidate templates is most
2103          specialized.  However, we, also have:
2104
2105            [temp.func.order]
2106
2107            Partial ordering of overloaded function template
2108            declarations is used in the following contexts to select
2109            the function template to which a function template
2110            specialization refers:
2111
2112            -- when an explicit specialization refers to a function
2113               template.
2114
2115          So, we do use the partial ordering rules, at least for now.
2116          This extension can only serve to make invalid programs valid,
2117          so it's safe.  And, there is strong anecdotal evidence that
2118          the committee intended the partial ordering rules to apply;
2119          the EDG front end has that behavior, and John Spicer claims
2120          that the committee simply forgot to delete the wording in
2121          [temp.expl.spec].  */
2122       tree tmpl = most_specialized_instantiation (templates);
2123       if (tmpl != error_mark_node)
2124         {
2125           templates = tmpl;
2126           TREE_CHAIN (templates) = NULL_TREE;
2127         }
2128     }
2129
2130   if (templates == NULL_TREE && candidates == NULL_TREE)
2131     {
2132       error ("template-id %qD for %q+D does not match any template "
2133              "declaration", template_id, decl);
2134       if (header_count && header_count != template_count + 1)
2135         inform (input_location, "saw %d %<template<>%>, need %d for "
2136                 "specializing a member function template",
2137                 header_count, template_count + 1);
2138       return error_mark_node;
2139     }
2140   else if ((templates && TREE_CHAIN (templates))
2141            || (candidates && TREE_CHAIN (candidates))
2142            || (templates && candidates))
2143     {
2144       error ("ambiguous template specialization %qD for %q+D",
2145              template_id, decl);
2146       candidates = chainon (candidates, templates);
2147       print_candidates (candidates);
2148       return error_mark_node;
2149     }
2150
2151   /* We have one, and exactly one, match.  */
2152   if (candidates)
2153     {
2154       tree fn = TREE_VALUE (candidates);
2155       *targs_out = copy_node (DECL_TI_ARGS (fn));
2156       /* DECL is a re-declaration or partial instantiation of a template
2157          function.  */
2158       if (TREE_CODE (fn) == TEMPLATE_DECL)
2159         return fn;
2160       /* It was a specialization of an ordinary member function in a
2161          template class.  */
2162       return DECL_TI_TEMPLATE (fn);
2163     }
2164
2165   /* It was a specialization of a template.  */
2166   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2167   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2168     {
2169       *targs_out = copy_node (targs);
2170       SET_TMPL_ARGS_LEVEL (*targs_out,
2171                            TMPL_ARGS_DEPTH (*targs_out),
2172                            TREE_PURPOSE (templates));
2173     }
2174   else
2175     *targs_out = TREE_PURPOSE (templates);
2176   return TREE_VALUE (templates);
2177 }
2178
2179 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2180    but with the default argument values filled in from those in the
2181    TMPL_TYPES.  */
2182
2183 static tree
2184 copy_default_args_to_explicit_spec_1 (tree spec_types,
2185                                       tree tmpl_types)
2186 {
2187   tree new_spec_types;
2188
2189   if (!spec_types)
2190     return NULL_TREE;
2191
2192   if (spec_types == void_list_node)
2193     return void_list_node;
2194
2195   /* Substitute into the rest of the list.  */
2196   new_spec_types =
2197     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2198                                           TREE_CHAIN (tmpl_types));
2199
2200   /* Add the default argument for this parameter.  */
2201   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2202                          TREE_VALUE (spec_types),
2203                          new_spec_types);
2204 }
2205
2206 /* DECL is an explicit specialization.  Replicate default arguments
2207    from the template it specializes.  (That way, code like:
2208
2209      template <class T> void f(T = 3);
2210      template <> void f(double);
2211      void g () { f (); }
2212
2213    works, as required.)  An alternative approach would be to look up
2214    the correct default arguments at the call-site, but this approach
2215    is consistent with how implicit instantiations are handled.  */
2216
2217 static void
2218 copy_default_args_to_explicit_spec (tree decl)
2219 {
2220   tree tmpl;
2221   tree spec_types;
2222   tree tmpl_types;
2223   tree new_spec_types;
2224   tree old_type;
2225   tree new_type;
2226   tree t;
2227   tree object_type = NULL_TREE;
2228   tree in_charge = NULL_TREE;
2229   tree vtt = NULL_TREE;
2230
2231   /* See if there's anything we need to do.  */
2232   tmpl = DECL_TI_TEMPLATE (decl);
2233   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2234   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2235     if (TREE_PURPOSE (t))
2236       break;
2237   if (!t)
2238     return;
2239
2240   old_type = TREE_TYPE (decl);
2241   spec_types = TYPE_ARG_TYPES (old_type);
2242
2243   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2244     {
2245       /* Remove the this pointer, but remember the object's type for
2246          CV quals.  */
2247       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2248       spec_types = TREE_CHAIN (spec_types);
2249       tmpl_types = TREE_CHAIN (tmpl_types);
2250
2251       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2252         {
2253           /* DECL may contain more parameters than TMPL due to the extra
2254              in-charge parameter in constructors and destructors.  */
2255           in_charge = spec_types;
2256           spec_types = TREE_CHAIN (spec_types);
2257         }
2258       if (DECL_HAS_VTT_PARM_P (decl))
2259         {
2260           vtt = spec_types;
2261           spec_types = TREE_CHAIN (spec_types);
2262         }
2263     }
2264
2265   /* Compute the merged default arguments.  */
2266   new_spec_types =
2267     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2268
2269   /* Compute the new FUNCTION_TYPE.  */
2270   if (object_type)
2271     {
2272       if (vtt)
2273         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2274                                          TREE_VALUE (vtt),
2275                                          new_spec_types);
2276
2277       if (in_charge)
2278         /* Put the in-charge parameter back.  */
2279         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2280                                          TREE_VALUE (in_charge),
2281                                          new_spec_types);
2282
2283       new_type = build_method_type_directly (object_type,
2284                                              TREE_TYPE (old_type),
2285                                              new_spec_types);
2286     }
2287   else
2288     new_type = build_function_type (TREE_TYPE (old_type),
2289                                     new_spec_types);
2290   new_type = cp_build_type_attribute_variant (new_type,
2291                                               TYPE_ATTRIBUTES (old_type));
2292   new_type = build_exception_variant (new_type,
2293                                       TYPE_RAISES_EXCEPTIONS (old_type));
2294
2295   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2296     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2297
2298   TREE_TYPE (decl) = new_type;
2299 }
2300
2301 /* Return the number of template headers we expect to see for a definition
2302    or specialization of CTYPE or one of its non-template members.  */
2303
2304 int
2305 num_template_headers_for_class (tree ctype)
2306 {
2307   int num_templates = 0;
2308
2309   while (ctype && CLASS_TYPE_P (ctype))
2310     {
2311       /* You're supposed to have one `template <...>' for every
2312          template class, but you don't need one for a full
2313          specialization.  For example:
2314
2315          template <class T> struct S{};
2316          template <> struct S<int> { void f(); };
2317          void S<int>::f () {}
2318
2319          is correct; there shouldn't be a `template <>' for the
2320          definition of `S<int>::f'.  */
2321       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2322         /* If CTYPE does not have template information of any
2323            kind,  then it is not a template, nor is it nested
2324            within a template.  */
2325         break;
2326       if (explicit_class_specialization_p (ctype))
2327         break;
2328       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2329         ++num_templates;
2330
2331       ctype = TYPE_CONTEXT (ctype);
2332     }
2333
2334   return num_templates;
2335 }
2336
2337 /* Do a simple sanity check on the template headers that precede the
2338    variable declaration DECL.  */
2339
2340 void
2341 check_template_variable (tree decl)
2342 {
2343   tree ctx = CP_DECL_CONTEXT (decl);
2344   int wanted = num_template_headers_for_class (ctx);
2345   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2346       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2347     {
2348       if (cxx_dialect < cxx14)
2349         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2350                  "variable templates only available with "
2351                  "-std=c++14 or -std=gnu++14");
2352
2353       // Namespace-scope variable templates should have a template header.
2354       ++wanted;
2355     }
2356   if (template_header_count > wanted)
2357     {
2358       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2359                              "too many template headers for %D (should be %d)",
2360                              decl, wanted);
2361       if (warned && CLASS_TYPE_P (ctx)
2362           && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2363         inform (DECL_SOURCE_LOCATION (decl),
2364                 "members of an explicitly specialized class are defined "
2365                 "without a template header");
2366     }
2367 }
2368
2369 /* Check to see if the function just declared, as indicated in
2370    DECLARATOR, and in DECL, is a specialization of a function
2371    template.  We may also discover that the declaration is an explicit
2372    instantiation at this point.
2373
2374    Returns DECL, or an equivalent declaration that should be used
2375    instead if all goes well.  Issues an error message if something is
2376    amiss.  Returns error_mark_node if the error is not easily
2377    recoverable.
2378
2379    FLAGS is a bitmask consisting of the following flags:
2380
2381    2: The function has a definition.
2382    4: The function is a friend.
2383
2384    The TEMPLATE_COUNT is the number of references to qualifying
2385    template classes that appeared in the name of the function.  For
2386    example, in
2387
2388      template <class T> struct S { void f(); };
2389      void S<int>::f();
2390
2391    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2392    classes are not counted in the TEMPLATE_COUNT, so that in
2393
2394      template <class T> struct S {};
2395      template <> struct S<int> { void f(); }
2396      template <> void S<int>::f();
2397
2398    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2399    invalid; there should be no template <>.)
2400
2401    If the function is a specialization, it is marked as such via
2402    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2403    is set up correctly, and it is added to the list of specializations
2404    for that template.  */
2405
2406 tree
2407 check_explicit_specialization (tree declarator,
2408                                tree decl,
2409                                int template_count,
2410                                int flags)
2411 {
2412   int have_def = flags & 2;
2413   int is_friend = flags & 4;
2414   int specialization = 0;
2415   int explicit_instantiation = 0;
2416   int member_specialization = 0;
2417   tree ctype = DECL_CLASS_CONTEXT (decl);
2418   tree dname = DECL_NAME (decl);
2419   tmpl_spec_kind tsk;
2420
2421   if (is_friend)
2422     {
2423       if (!processing_specialization)
2424         tsk = tsk_none;
2425       else
2426         tsk = tsk_excessive_parms;
2427     }
2428   else
2429     tsk = current_tmpl_spec_kind (template_count);
2430
2431   switch (tsk)
2432     {
2433     case tsk_none:
2434       if (processing_specialization)
2435         {
2436           specialization = 1;
2437           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2438         }
2439       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2440         {
2441           if (is_friend)
2442             /* This could be something like:
2443
2444                template <class T> void f(T);
2445                class S { friend void f<>(int); }  */
2446             specialization = 1;
2447           else
2448             {
2449               /* This case handles bogus declarations like template <>
2450                  template <class T> void f<int>(); */
2451
2452               error ("template-id %qD in declaration of primary template",
2453                      declarator);
2454               return decl;
2455             }
2456         }
2457       break;
2458
2459     case tsk_invalid_member_spec:
2460       /* The error has already been reported in
2461          check_specialization_scope.  */
2462       return error_mark_node;
2463
2464     case tsk_invalid_expl_inst:
2465       error ("template parameter list used in explicit instantiation");
2466
2467       /* Fall through.  */
2468
2469     case tsk_expl_inst:
2470       if (have_def)
2471         error ("definition provided for explicit instantiation");
2472
2473       explicit_instantiation = 1;
2474       break;
2475
2476     case tsk_excessive_parms:
2477     case tsk_insufficient_parms:
2478       if (tsk == tsk_excessive_parms)
2479         error ("too many template parameter lists in declaration of %qD",
2480                decl);
2481       else if (template_header_count)
2482         error("too few template parameter lists in declaration of %qD", decl);
2483       else
2484         error("explicit specialization of %qD must be introduced by "
2485               "%<template <>%>", decl);
2486
2487       /* Fall through.  */
2488     case tsk_expl_spec:
2489       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2490         /* In cases like template<> constexpr bool v = true;
2491            We'll give an error in check_template_variable.  */
2492         break;
2493
2494       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2495       if (ctype)
2496         member_specialization = 1;
2497       else
2498         specialization = 1;
2499       break;
2500
2501     case tsk_template:
2502       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2503         {
2504           /* This case handles bogus declarations like template <>
2505              template <class T> void f<int>(); */
2506
2507           if (!uses_template_parms (declarator))
2508             error ("template-id %qD in declaration of primary template",
2509                    declarator);
2510           else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2511             {
2512               /* Partial specialization of variable template.  */
2513               SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2514               specialization = 1;
2515               goto ok;
2516             }
2517           else if (cxx_dialect < cxx14)
2518             error ("non-type partial specialization %qD "
2519                    "is not allowed", declarator);
2520           else
2521             error ("non-class, non-variable partial specialization %qD "
2522                    "is not allowed", declarator);
2523           return decl;
2524         ok:;
2525         }
2526
2527       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2528         /* This is a specialization of a member template, without
2529            specialization the containing class.  Something like:
2530
2531              template <class T> struct S {
2532                template <class U> void f (U);
2533              };
2534              template <> template <class U> void S<int>::f(U) {}
2535
2536            That's a specialization -- but of the entire template.  */
2537         specialization = 1;
2538       break;
2539
2540     default:
2541       gcc_unreachable ();
2542     }
2543
2544   if ((specialization || member_specialization)
2545       /* This doesn't apply to variable templates.  */
2546       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2547           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2548     {
2549       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2550       for (; t; t = TREE_CHAIN (t))
2551         if (TREE_PURPOSE (t))
2552           {
2553             permerror (input_location, 
2554                        "default argument specified in explicit specialization");
2555             break;
2556           }
2557     }
2558
2559   if (specialization || member_specialization || explicit_instantiation)
2560     {
2561       tree tmpl = NULL_TREE;
2562       tree targs = NULL_TREE;
2563       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2564
2565       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2566       if (!was_template_id)
2567         {
2568           tree fns;
2569
2570           gcc_assert (identifier_p (declarator));
2571           if (ctype)
2572             fns = dname;
2573           else
2574             {
2575               /* If there is no class context, the explicit instantiation
2576                  must be at namespace scope.  */
2577               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2578
2579               /* Find the namespace binding, using the declaration
2580                  context.  */
2581               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2582                                            false, true);
2583               if (fns == error_mark_node || !is_overloaded_fn (fns))
2584                 {
2585                   error ("%qD is not a template function", dname);
2586                   fns = error_mark_node;
2587                 }
2588               else
2589                 {
2590                   tree fn = OVL_CURRENT (fns);
2591                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2592                                                 CP_DECL_CONTEXT (fn)))
2593                     error ("%qD is not declared in %qD",
2594                            decl, current_namespace);
2595                 }
2596             }
2597
2598           declarator = lookup_template_function (fns, NULL_TREE);
2599         }
2600
2601       if (declarator == error_mark_node)
2602         return error_mark_node;
2603
2604       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2605         {
2606           if (!explicit_instantiation)
2607             /* A specialization in class scope.  This is invalid,
2608                but the error will already have been flagged by
2609                check_specialization_scope.  */
2610             return error_mark_node;
2611           else
2612             {
2613               /* It's not valid to write an explicit instantiation in
2614                  class scope, e.g.:
2615
2616                    class C { template void f(); }
2617
2618                    This case is caught by the parser.  However, on
2619                    something like:
2620
2621                    template class C { void f(); };
2622
2623                    (which is invalid) we can get here.  The error will be
2624                    issued later.  */
2625               ;
2626             }
2627
2628           return decl;
2629         }
2630       else if (ctype != NULL_TREE
2631                && (identifier_p (TREE_OPERAND (declarator, 0))))
2632         {
2633           // We'll match variable templates in start_decl.
2634           if (VAR_P (decl))
2635             return decl;
2636
2637           /* Find the list of functions in ctype that have the same
2638              name as the declared function.  */
2639           tree name = TREE_OPERAND (declarator, 0);
2640           tree fns = NULL_TREE;
2641           int idx;
2642
2643           if (constructor_name_p (name, ctype))
2644             {
2645               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2646
2647               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2648                   : !CLASSTYPE_DESTRUCTORS (ctype))
2649                 {
2650                   /* From [temp.expl.spec]:
2651
2652                      If such an explicit specialization for the member
2653                      of a class template names an implicitly-declared
2654                      special member function (clause _special_), the
2655                      program is ill-formed.
2656
2657                      Similar language is found in [temp.explicit].  */
2658                   error ("specialization of implicitly-declared special member function");
2659                   return error_mark_node;
2660                 }
2661
2662               name = is_constructor ? ctor_identifier : dtor_identifier;
2663             }
2664
2665           if (!DECL_CONV_FN_P (decl))
2666             {
2667               idx = lookup_fnfields_1 (ctype, name);
2668               if (idx >= 0)
2669                 fns = (*CLASSTYPE_METHOD_VEC (ctype))[idx];
2670             }
2671           else
2672             {
2673               vec<tree, va_gc> *methods;
2674               tree ovl;
2675
2676               /* For a type-conversion operator, we cannot do a
2677                  name-based lookup.  We might be looking for `operator
2678                  int' which will be a specialization of `operator T'.
2679                  So, we find *all* the conversion operators, and then
2680                  select from them.  */
2681               fns = NULL_TREE;
2682
2683               methods = CLASSTYPE_METHOD_VEC (ctype);
2684               if (methods)
2685                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2686                      methods->iterate (idx, &ovl);
2687                      ++idx)
2688                   {
2689                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2690                       /* There are no more conversion functions.  */
2691                       break;
2692
2693                     /* Glue all these conversion functions together
2694                        with those we already have.  */
2695                     for (; ovl; ovl = OVL_NEXT (ovl))
2696                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2697                   }
2698             }
2699
2700           if (fns == NULL_TREE)
2701             {
2702               error ("no member function %qD declared in %qT", name, ctype);
2703               return error_mark_node;
2704             }
2705           else
2706             TREE_OPERAND (declarator, 0) = fns;
2707         }
2708
2709       /* Figure out what exactly is being specialized at this point.
2710          Note that for an explicit instantiation, even one for a
2711          member function, we cannot tell apriori whether the
2712          instantiation is for a member template, or just a member
2713          function of a template class.  Even if a member template is
2714          being instantiated, the member template arguments may be
2715          elided if they can be deduced from the rest of the
2716          declaration.  */
2717       tmpl = determine_specialization (declarator, decl,
2718                                        &targs,
2719                                        member_specialization,
2720                                        template_count,
2721                                        tsk);
2722
2723       if (!tmpl || tmpl == error_mark_node)
2724         /* We couldn't figure out what this declaration was
2725            specializing.  */
2726         return error_mark_node;
2727       else
2728         {
2729           tree gen_tmpl = most_general_template (tmpl);
2730
2731           if (explicit_instantiation)
2732             {
2733               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2734                  is done by do_decl_instantiation later.  */
2735
2736               int arg_depth = TMPL_ARGS_DEPTH (targs);
2737               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2738
2739               if (arg_depth > parm_depth)
2740                 {
2741                   /* If TMPL is not the most general template (for
2742                      example, if TMPL is a friend template that is
2743                      injected into namespace scope), then there will
2744                      be too many levels of TARGS.  Remove some of them
2745                      here.  */
2746                   int i;
2747                   tree new_targs;
2748
2749                   new_targs = make_tree_vec (parm_depth);
2750                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2751                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2752                       = TREE_VEC_ELT (targs, i);
2753                   targs = new_targs;
2754                 }
2755
2756               return instantiate_template (tmpl, targs, tf_error);
2757             }
2758
2759           /* If we thought that the DECL was a member function, but it
2760              turns out to be specializing a static member function,
2761              make DECL a static member function as well.  */
2762           if (DECL_FUNCTION_TEMPLATE_P (tmpl)
2763               && DECL_STATIC_FUNCTION_P (tmpl)
2764               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2765             revert_static_member_fn (decl);
2766
2767           /* If this is a specialization of a member template of a
2768              template class, we want to return the TEMPLATE_DECL, not
2769              the specialization of it.  */
2770           if (tsk == tsk_template && !was_template_id)
2771             {
2772               tree result = DECL_TEMPLATE_RESULT (tmpl);
2773               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2774               DECL_INITIAL (result) = NULL_TREE;
2775               if (have_def)
2776                 {
2777                   tree parm;
2778                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2779                   DECL_SOURCE_LOCATION (result)
2780                     = DECL_SOURCE_LOCATION (decl);
2781                   /* We want to use the argument list specified in the
2782                      definition, not in the original declaration.  */
2783                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2784                   for (parm = DECL_ARGUMENTS (result); parm;
2785                        parm = DECL_CHAIN (parm))
2786                     DECL_CONTEXT (parm) = result;
2787                 }
2788               return register_specialization (tmpl, gen_tmpl, targs,
2789                                               is_friend, 0);
2790             }
2791
2792           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2793           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2794
2795           if (was_template_id)
2796             TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
2797
2798           /* Inherit default function arguments from the template
2799              DECL is specializing.  */
2800           if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2801             copy_default_args_to_explicit_spec (decl);
2802
2803           /* This specialization has the same protection as the
2804              template it specializes.  */
2805           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2806           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2807
2808           /* 7.1.1-1 [dcl.stc]
2809
2810              A storage-class-specifier shall not be specified in an
2811              explicit specialization...
2812
2813              The parser rejects these, so unless action is taken here,
2814              explicit function specializations will always appear with
2815              global linkage.
2816
2817              The action recommended by the C++ CWG in response to C++
2818              defect report 605 is to make the storage class and linkage
2819              of the explicit specialization match the templated function:
2820
2821              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2822            */
2823           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2824             {
2825               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2826               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2827
2828               /* This specialization has the same linkage and visibility as
2829                  the function template it specializes.  */
2830               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2831               if (! TREE_PUBLIC (decl))
2832                 {
2833                   DECL_INTERFACE_KNOWN (decl) = 1;
2834                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2835                 }
2836               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2837               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2838                 {
2839                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2840                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2841                 }
2842             }
2843
2844           /* If DECL is a friend declaration, declared using an
2845              unqualified name, the namespace associated with DECL may
2846              have been set incorrectly.  For example, in:
2847
2848                template <typename T> void f(T);
2849                namespace N {
2850                  struct S { friend void f<int>(int); }
2851                }
2852
2853              we will have set the DECL_CONTEXT for the friend
2854              declaration to N, rather than to the global namespace.  */
2855           if (DECL_NAMESPACE_SCOPE_P (decl))
2856             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2857
2858           if (is_friend && !have_def)
2859             /* This is not really a declaration of a specialization.
2860                It's just the name of an instantiation.  But, it's not
2861                a request for an instantiation, either.  */
2862             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2863           else if (TREE_CODE (decl) == FUNCTION_DECL)
2864             /* A specialization is not necessarily COMDAT.  */
2865             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
2866                                   && DECL_DECLARED_INLINE_P (decl));
2867           else if (TREE_CODE (decl) == VAR_DECL)
2868             DECL_COMDAT (decl) = false;
2869
2870           /* Register this specialization so that we can find it
2871              again.  */
2872           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2873
2874           /* A 'structor should already have clones.  */
2875           gcc_assert (decl == error_mark_node
2876                       || variable_template_p (tmpl)
2877                       || !(DECL_CONSTRUCTOR_P (decl)
2878                            || DECL_DESTRUCTOR_P (decl))
2879                       || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
2880         }
2881     }
2882
2883   return decl;
2884 }
2885
2886 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2887    parameters.  These are represented in the same format used for
2888    DECL_TEMPLATE_PARMS.  */
2889
2890 int
2891 comp_template_parms (const_tree parms1, const_tree parms2)
2892 {
2893   const_tree p1;
2894   const_tree p2;
2895
2896   if (parms1 == parms2)
2897     return 1;
2898
2899   for (p1 = parms1, p2 = parms2;
2900        p1 != NULL_TREE && p2 != NULL_TREE;
2901        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2902     {
2903       tree t1 = TREE_VALUE (p1);
2904       tree t2 = TREE_VALUE (p2);
2905       int i;
2906
2907       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2908       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2909
2910       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2911         return 0;
2912
2913       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2914         {
2915           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2916           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2917
2918           /* If either of the template parameters are invalid, assume
2919              they match for the sake of error recovery. */
2920           if (error_operand_p (parm1) || error_operand_p (parm2))
2921             return 1;
2922
2923           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2924             return 0;
2925
2926           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2927               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2928                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2929             continue;
2930           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2931             return 0;
2932         }
2933     }
2934
2935   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2936     /* One set of parameters has more parameters lists than the
2937        other.  */
2938     return 0;
2939
2940   return 1;
2941 }
2942
2943 /* Determine whether PARM is a parameter pack.  */
2944
2945 bool 
2946 template_parameter_pack_p (const_tree parm)
2947 {
2948   /* Determine if we have a non-type template parameter pack.  */
2949   if (TREE_CODE (parm) == PARM_DECL)
2950     return (DECL_TEMPLATE_PARM_P (parm) 
2951             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2952   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2953     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2954
2955   /* If this is a list of template parameters, we could get a
2956      TYPE_DECL or a TEMPLATE_DECL.  */ 
2957   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2958     parm = TREE_TYPE (parm);
2959
2960   /* Otherwise it must be a type template parameter.  */
2961   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2962            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2963           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2964 }
2965
2966 /* Determine if T is a function parameter pack.  */
2967
2968 bool
2969 function_parameter_pack_p (const_tree t)
2970 {
2971   if (t && TREE_CODE (t) == PARM_DECL)
2972     return DECL_PACK_P (t);
2973   return false;
2974 }
2975
2976 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2977    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2978
2979 tree
2980 get_function_template_decl (const_tree primary_func_tmpl_inst)
2981 {
2982   if (! primary_func_tmpl_inst
2983       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2984       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2985     return NULL;
2986
2987   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2988 }
2989
2990 /* Return true iff the function parameter PARAM_DECL was expanded
2991    from the function parameter pack PACK.  */
2992
2993 bool
2994 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2995 {
2996   if (DECL_ARTIFICIAL (param_decl)
2997       || !function_parameter_pack_p (pack))
2998     return false;
2999
3000   /* The parameter pack and its pack arguments have the same
3001      DECL_PARM_INDEX.  */
3002   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3003 }
3004
3005 /* Determine whether ARGS describes a variadic template args list,
3006    i.e., one that is terminated by a template argument pack.  */
3007
3008 static bool 
3009 template_args_variadic_p (tree args)
3010 {
3011   int nargs;
3012   tree last_parm;
3013
3014   if (args == NULL_TREE)
3015     return false;
3016
3017   args = INNERMOST_TEMPLATE_ARGS (args);
3018   nargs = TREE_VEC_LENGTH (args);
3019
3020   if (nargs == 0)
3021     return false;
3022
3023   last_parm = TREE_VEC_ELT (args, nargs - 1);
3024
3025   return ARGUMENT_PACK_P (last_parm);
3026 }
3027
3028 /* Generate a new name for the parameter pack name NAME (an
3029    IDENTIFIER_NODE) that incorporates its */
3030
3031 static tree
3032 make_ith_pack_parameter_name (tree name, int i)
3033 {
3034   /* Munge the name to include the parameter index.  */
3035 #define NUMBUF_LEN 128
3036   char numbuf[NUMBUF_LEN];
3037   char* newname;
3038   int newname_len;
3039
3040   if (name == NULL_TREE)
3041     return name;
3042   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3043   newname_len = IDENTIFIER_LENGTH (name)
3044                 + strlen (numbuf) + 2;
3045   newname = (char*)alloca (newname_len);
3046   snprintf (newname, newname_len,
3047             "%s#%i", IDENTIFIER_POINTER (name), i);
3048   return get_identifier (newname);
3049 }
3050
3051 /* Return true if T is a primary function, class or alias template
3052    instantiation.  */
3053
3054 bool
3055 primary_template_instantiation_p (const_tree t)
3056 {
3057   if (!t)
3058     return false;
3059
3060   if (TREE_CODE (t) == FUNCTION_DECL)
3061     return DECL_LANG_SPECIFIC (t)
3062            && DECL_TEMPLATE_INSTANTIATION (t)
3063            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
3064   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3065     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
3066            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
3067   else if (alias_template_specialization_p (t))
3068     return true;
3069   return false;
3070 }
3071
3072 /* Return true if PARM is a template template parameter.  */
3073
3074 bool
3075 template_template_parameter_p (const_tree parm)
3076 {
3077   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3078 }
3079
3080 /* Return true iff PARM is a DECL representing a type template
3081    parameter.  */
3082
3083 bool
3084 template_type_parameter_p (const_tree parm)
3085 {
3086   return (parm
3087           && (TREE_CODE (parm) == TYPE_DECL
3088               || TREE_CODE (parm) == TEMPLATE_DECL)
3089           && DECL_TEMPLATE_PARM_P (parm));
3090 }
3091
3092 /* Return the template parameters of T if T is a
3093    primary template instantiation, NULL otherwise.  */
3094
3095 tree
3096 get_primary_template_innermost_parameters (const_tree t)
3097 {
3098   tree parms = NULL, template_info = NULL;
3099
3100   if ((template_info = get_template_info (t))
3101       && primary_template_instantiation_p (t))
3102     parms = INNERMOST_TEMPLATE_PARMS
3103         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3104
3105   return parms;
3106 }
3107
3108 /* Return the template parameters of the LEVELth level from the full list
3109    of template parameters PARMS.  */
3110
3111 tree
3112 get_template_parms_at_level (tree parms, int level)
3113 {
3114   tree p;
3115   if (!parms
3116       || TREE_CODE (parms) != TREE_LIST
3117       || level > TMPL_PARMS_DEPTH (parms))
3118     return NULL_TREE;
3119
3120   for (p = parms; p; p = TREE_CHAIN (p))
3121     if (TMPL_PARMS_DEPTH (p) == level)
3122       return p;
3123
3124   return NULL_TREE;
3125 }
3126
3127 /* Returns the template arguments of T if T is a template instantiation,
3128    NULL otherwise.  */
3129
3130 tree
3131 get_template_innermost_arguments (const_tree t)
3132 {
3133   tree args = NULL, template_info = NULL;
3134
3135   if ((template_info = get_template_info (t))
3136       && TI_ARGS (template_info))
3137     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3138
3139   return args;
3140 }
3141
3142 /* Return the argument pack elements of T if T is a template argument pack,
3143    NULL otherwise.  */
3144
3145 tree
3146 get_template_argument_pack_elems (const_tree t)
3147 {
3148   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3149       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3150     return NULL;
3151
3152   return ARGUMENT_PACK_ARGS (t);
3153 }
3154
3155 /* Structure used to track the progress of find_parameter_packs_r.  */
3156 struct find_parameter_pack_data 
3157 {
3158   /* TREE_LIST that will contain all of the parameter packs found by
3159      the traversal.  */
3160   tree* parameter_packs;
3161
3162   /* Set of AST nodes that have been visited by the traversal.  */
3163   hash_set<tree> *visited;
3164 };
3165
3166 /* Identifies all of the argument packs that occur in a template
3167    argument and appends them to the TREE_LIST inside DATA, which is a
3168    find_parameter_pack_data structure. This is a subroutine of
3169    make_pack_expansion and uses_parameter_packs.  */
3170 static tree
3171 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3172 {
3173   tree t = *tp;
3174   struct find_parameter_pack_data* ppd = 
3175     (struct find_parameter_pack_data*)data;
3176   bool parameter_pack_p = false;
3177
3178   /* Handle type aliases/typedefs.  */
3179   if (TYPE_ALIAS_P (t))
3180     {
3181       if (TYPE_TEMPLATE_INFO (t))
3182         cp_walk_tree (&TYPE_TI_ARGS (t),
3183                       &find_parameter_packs_r,
3184                       ppd, ppd->visited);
3185       *walk_subtrees = 0;
3186       return NULL_TREE;
3187     }
3188
3189   /* Identify whether this is a parameter pack or not.  */
3190   switch (TREE_CODE (t))
3191     {
3192     case TEMPLATE_PARM_INDEX:
3193       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3194         parameter_pack_p = true;
3195       break;
3196
3197     case TEMPLATE_TYPE_PARM:
3198       t = TYPE_MAIN_VARIANT (t);
3199     case TEMPLATE_TEMPLATE_PARM:
3200       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3201         parameter_pack_p = true;
3202       break;
3203
3204     case FIELD_DECL:
3205     case PARM_DECL:
3206       if (DECL_PACK_P (t))
3207         {
3208           /* We don't want to walk into the type of a PARM_DECL,
3209              because we don't want to see the type parameter pack.  */
3210           *walk_subtrees = 0;
3211           parameter_pack_p = true;
3212         }
3213       break;
3214
3215       /* Look through a lambda capture proxy to the field pack.  */
3216     case VAR_DECL:
3217       if (DECL_HAS_VALUE_EXPR_P (t))
3218         {
3219           tree v = DECL_VALUE_EXPR (t);
3220           cp_walk_tree (&v,
3221                         &find_parameter_packs_r,
3222                         ppd, ppd->visited);
3223           *walk_subtrees = 0;
3224         }
3225       break;
3226
3227     case BASES:
3228       parameter_pack_p = true;
3229       break;
3230     default:
3231       /* Not a parameter pack.  */
3232       break;
3233     }
3234
3235   if (parameter_pack_p)
3236     {
3237       /* Add this parameter pack to the list.  */
3238       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3239     }
3240
3241   if (TYPE_P (t))
3242     cp_walk_tree (&TYPE_CONTEXT (t), 
3243                   &find_parameter_packs_r, ppd, ppd->visited);
3244
3245   /* This switch statement will return immediately if we don't find a
3246      parameter pack.  */
3247   switch (TREE_CODE (t)) 
3248     {
3249     case TEMPLATE_PARM_INDEX:
3250       return NULL_TREE;
3251
3252     case BOUND_TEMPLATE_TEMPLATE_PARM:
3253       /* Check the template itself.  */
3254       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3255                     &find_parameter_packs_r, ppd, ppd->visited);
3256       /* Check the template arguments.  */
3257       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3258                     ppd->visited);
3259       *walk_subtrees = 0;
3260       return NULL_TREE;
3261
3262     case TEMPLATE_TYPE_PARM:
3263     case TEMPLATE_TEMPLATE_PARM:
3264       return NULL_TREE;
3265
3266     case PARM_DECL:
3267       return NULL_TREE;
3268
3269     case RECORD_TYPE:
3270       if (TYPE_PTRMEMFUNC_P (t))
3271         return NULL_TREE;
3272       /* Fall through.  */
3273
3274     case UNION_TYPE:
3275     case ENUMERAL_TYPE:
3276       if (TYPE_TEMPLATE_INFO (t))
3277         cp_walk_tree (&TYPE_TI_ARGS (t),
3278                       &find_parameter_packs_r, ppd, ppd->visited);
3279
3280       *walk_subtrees = 0;
3281       return NULL_TREE;
3282
3283     case CONSTRUCTOR:
3284     case TEMPLATE_DECL:
3285       cp_walk_tree (&TREE_TYPE (t),
3286                     &find_parameter_packs_r, ppd, ppd->visited);
3287       return NULL_TREE;
3288  
3289     case TYPENAME_TYPE:
3290       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3291                    ppd, ppd->visited);
3292       *walk_subtrees = 0;
3293       return NULL_TREE;
3294       
3295     case TYPE_PACK_EXPANSION:
3296     case EXPR_PACK_EXPANSION:
3297       *walk_subtrees = 0;
3298       return NULL_TREE;
3299
3300     case INTEGER_TYPE:
3301       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3302                     ppd, ppd->visited);
3303       *walk_subtrees = 0;
3304       return NULL_TREE;
3305
3306     case IDENTIFIER_NODE:
3307       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3308                     ppd->visited);
3309       *walk_subtrees = 0;
3310       return NULL_TREE;
3311
3312     default:
3313       return NULL_TREE;
3314     }
3315
3316   return NULL_TREE;
3317 }
3318
3319 /* Determines if the expression or type T uses any parameter packs.  */
3320 bool
3321 uses_parameter_packs (tree t)
3322 {
3323   tree parameter_packs = NULL_TREE;
3324   struct find_parameter_pack_data ppd;
3325   ppd.parameter_packs = &parameter_packs;
3326   ppd.visited = new hash_set<tree>;
3327   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3328   delete ppd.visited;
3329   return parameter_packs != NULL_TREE;
3330 }
3331
3332 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3333    representation a base-class initializer into a parameter pack
3334    expansion. If all goes well, the resulting node will be an
3335    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3336    respectively.  */
3337 tree 
3338 make_pack_expansion (tree arg)
3339 {
3340   tree result;
3341   tree parameter_packs = NULL_TREE;
3342   bool for_types = false;
3343   struct find_parameter_pack_data ppd;
3344
3345   if (!arg || arg == error_mark_node)
3346     return arg;
3347
3348   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3349     {
3350       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3351          class initializer.  In this case, the TREE_PURPOSE will be a
3352          _TYPE node (representing the base class expansion we're
3353          initializing) and the TREE_VALUE will be a TREE_LIST
3354          containing the initialization arguments. 
3355
3356          The resulting expansion looks somewhat different from most
3357          expansions. Rather than returning just one _EXPANSION, we
3358          return a TREE_LIST whose TREE_PURPOSE is a
3359          TYPE_PACK_EXPANSION containing the bases that will be
3360          initialized.  The TREE_VALUE will be identical to the
3361          original TREE_VALUE, which is a list of arguments that will
3362          be passed to each base.  We do not introduce any new pack
3363          expansion nodes into the TREE_VALUE (although it is possible
3364          that some already exist), because the TREE_PURPOSE and
3365          TREE_VALUE all need to be expanded together with the same
3366          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3367          resulting TREE_PURPOSE will mention the parameter packs in
3368          both the bases and the arguments to the bases.  */
3369       tree purpose;
3370       tree value;
3371       tree parameter_packs = NULL_TREE;
3372
3373       /* Determine which parameter packs will be used by the base
3374          class expansion.  */
3375       ppd.visited = new hash_set<tree>;
3376       ppd.parameter_packs = &parameter_packs;
3377       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3378                     &ppd, ppd.visited);
3379
3380       if (parameter_packs == NULL_TREE)
3381         {
3382           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3383           delete ppd.visited;
3384           return error_mark_node;
3385         }
3386
3387       if (TREE_VALUE (arg) != void_type_node)
3388         {
3389           /* Collect the sets of parameter packs used in each of the
3390              initialization arguments.  */
3391           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3392             {
3393               /* Determine which parameter packs will be expanded in this
3394                  argument.  */
3395               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3396                             &ppd, ppd.visited);
3397             }
3398         }
3399
3400       delete ppd.visited;
3401
3402       /* Create the pack expansion type for the base type.  */
3403       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3404       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3405       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3406
3407       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3408          they will rarely be compared to anything.  */
3409       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3410
3411       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3412     }
3413
3414   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3415     for_types = true;
3416
3417   /* Build the PACK_EXPANSION_* node.  */
3418   result = for_types
3419      ? cxx_make_type (TYPE_PACK_EXPANSION)
3420      : make_node (EXPR_PACK_EXPANSION);
3421   SET_PACK_EXPANSION_PATTERN (result, arg);
3422   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3423     {
3424       /* Propagate type and const-expression information.  */
3425       TREE_TYPE (result) = TREE_TYPE (arg);
3426       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3427     }
3428   else
3429     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3430        they will rarely be compared to anything.  */
3431     SET_TYPE_STRUCTURAL_EQUALITY (result);
3432
3433   /* Determine which parameter packs will be expanded.  */
3434   ppd.parameter_packs = &parameter_packs;
3435   ppd.visited = new hash_set<tree>;
3436   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3437   delete ppd.visited;
3438
3439   /* Make sure we found some parameter packs.  */
3440   if (parameter_packs == NULL_TREE)
3441     {
3442       if (TYPE_P (arg))
3443         error ("expansion pattern %<%T%> contains no argument packs", arg);
3444       else
3445         error ("expansion pattern %<%E%> contains no argument packs", arg);
3446       return error_mark_node;
3447     }
3448   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3449
3450   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3451
3452   return result;
3453 }
3454
3455 /* Checks T for any "bare" parameter packs, which have not yet been
3456    expanded, and issues an error if any are found. This operation can
3457    only be done on full expressions or types (e.g., an expression
3458    statement, "if" condition, etc.), because we could have expressions like:
3459
3460      foo(f(g(h(args)))...)
3461
3462    where "args" is a parameter pack. check_for_bare_parameter_packs
3463    should not be called for the subexpressions args, h(args),
3464    g(h(args)), or f(g(h(args))), because we would produce erroneous
3465    error messages. 
3466
3467    Returns TRUE and emits an error if there were bare parameter packs,
3468    returns FALSE otherwise.  */
3469 bool 
3470 check_for_bare_parameter_packs (tree t)
3471 {
3472   tree parameter_packs = NULL_TREE;
3473   struct find_parameter_pack_data ppd;
3474
3475   if (!processing_template_decl || !t || t == error_mark_node)
3476     return false;
3477
3478   if (TREE_CODE (t) == TYPE_DECL)
3479     t = TREE_TYPE (t);
3480
3481   ppd.parameter_packs = &parameter_packs;
3482   ppd.visited = new hash_set<tree>;
3483   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3484   delete ppd.visited;
3485
3486   if (parameter_packs) 
3487     {
3488       error ("parameter packs not expanded with %<...%>:");
3489       while (parameter_packs)
3490         {
3491           tree pack = TREE_VALUE (parameter_packs);
3492           tree name = NULL_TREE;
3493
3494           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3495               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3496             name = TYPE_NAME (pack);
3497           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3498             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3499           else
3500             name = DECL_NAME (pack);
3501
3502           if (name)
3503             inform (input_location, "        %qD", name);
3504           else
3505             inform (input_location, "        <anonymous>");
3506
3507           parameter_packs = TREE_CHAIN (parameter_packs);
3508         }
3509
3510       return true;
3511     }
3512
3513   return false;
3514 }
3515
3516 /* Expand any parameter packs that occur in the template arguments in
3517    ARGS.  */
3518 tree
3519 expand_template_argument_pack (tree args)
3520 {
3521   tree result_args = NULL_TREE;
3522   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3523   int num_result_args = -1;
3524   int non_default_args_count = -1;
3525
3526   /* First, determine if we need to expand anything, and the number of
3527      slots we'll need.  */
3528   for (in_arg = 0; in_arg < nargs; ++in_arg)
3529     {
3530       tree arg = TREE_VEC_ELT (args, in_arg);
3531       if (arg == NULL_TREE)
3532         return args;
3533       if (ARGUMENT_PACK_P (arg))
3534         {
3535           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3536           if (num_result_args < 0)
3537             num_result_args = in_arg + num_packed;
3538           else
3539             num_result_args += num_packed;
3540         }
3541       else
3542         {
3543           if (num_result_args >= 0)
3544             num_result_args++;
3545         }
3546     }
3547
3548   /* If no expansion is necessary, we're done.  */
3549   if (num_result_args < 0)
3550     return args;
3551
3552   /* Expand arguments.  */
3553   result_args = make_tree_vec (num_result_args);
3554   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3555     non_default_args_count =
3556       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3557   for (in_arg = 0; in_arg < nargs; ++in_arg)
3558     {
3559       tree arg = TREE_VEC_ELT (args, in_arg);
3560       if (ARGUMENT_PACK_P (arg))
3561         {
3562           tree packed = ARGUMENT_PACK_ARGS (arg);
3563           int i, num_packed = TREE_VEC_LENGTH (packed);
3564           for (i = 0; i < num_packed; ++i, ++out_arg)
3565             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3566           if (non_default_args_count > 0)
3567             non_default_args_count += num_packed - 1;
3568         }
3569       else
3570         {
3571           TREE_VEC_ELT (result_args, out_arg) = arg;
3572           ++out_arg;
3573         }
3574     }
3575   if (non_default_args_count >= 0)
3576     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3577   return result_args;
3578 }
3579
3580 /* Checks if DECL shadows a template parameter.
3581
3582    [temp.local]: A template-parameter shall not be redeclared within its
3583    scope (including nested scopes).
3584
3585    Emits an error and returns TRUE if the DECL shadows a parameter,
3586    returns FALSE otherwise.  */
3587
3588 bool
3589 check_template_shadow (tree decl)
3590 {
3591   tree olddecl;
3592
3593   /* If we're not in a template, we can't possibly shadow a template
3594      parameter.  */
3595   if (!current_template_parms)
3596     return true;
3597
3598   /* Figure out what we're shadowing.  */
3599   if (TREE_CODE (decl) == OVERLOAD)
3600     decl = OVL_CURRENT (decl);
3601   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3602
3603   /* If there's no previous binding for this name, we're not shadowing
3604      anything, let alone a template parameter.  */
3605   if (!olddecl)
3606     return true;
3607
3608   /* If we're not shadowing a template parameter, we're done.  Note
3609      that OLDDECL might be an OVERLOAD (or perhaps even an
3610      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3611      node.  */
3612   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3613     return true;
3614
3615   /* We check for decl != olddecl to avoid bogus errors for using a
3616      name inside a class.  We check TPFI to avoid duplicate errors for
3617      inline member templates.  */
3618   if (decl == olddecl
3619       || (DECL_TEMPLATE_PARM_P (decl)
3620           && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
3621     return true;
3622
3623   /* Don't complain about the injected class name, as we've already
3624      complained about the class itself.  */
3625   if (DECL_SELF_REFERENCE_P (decl))
3626     return false;
3627
3628   error ("declaration of %q+#D", decl);
3629   error (" shadows template parm %q+#D", olddecl);
3630   return false;
3631 }
3632
3633 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3634    ORIG_LEVEL, DECL, and TYPE.  */
3635
3636 static tree
3637 build_template_parm_index (int index,
3638                            int level,
3639                            int orig_level,
3640                            tree decl,
3641                            tree type)
3642 {
3643   tree t = make_node (TEMPLATE_PARM_INDEX);
3644   TEMPLATE_PARM_IDX (t) = index;
3645   TEMPLATE_PARM_LEVEL (t) = level;
3646   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3647   TEMPLATE_PARM_DECL (t) = decl;
3648   TREE_TYPE (t) = type;
3649   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3650   TREE_READONLY (t) = TREE_READONLY (decl);
3651
3652   return t;
3653 }
3654
3655 /* Find the canonical type parameter for the given template type
3656    parameter.  Returns the canonical type parameter, which may be TYPE
3657    if no such parameter existed.  */
3658
3659 static tree
3660 canonical_type_parameter (tree type)
3661 {
3662   tree list;
3663   int idx = TEMPLATE_TYPE_IDX (type);
3664   if (!canonical_template_parms)
3665     vec_alloc (canonical_template_parms, idx+1);
3666
3667   while (canonical_template_parms->length () <= (unsigned)idx)
3668     vec_safe_push (canonical_template_parms, NULL_TREE);
3669
3670   list = (*canonical_template_parms)[idx];
3671   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3672     list = TREE_CHAIN (list);
3673
3674   if (list)
3675     return TREE_VALUE (list);
3676   else
3677     {
3678       (*canonical_template_parms)[idx]
3679                 = tree_cons (NULL_TREE, type,
3680                              (*canonical_template_parms)[idx]);
3681       return type;
3682     }
3683 }
3684
3685 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3686    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3687    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3688    new one is created.  */
3689
3690 static tree
3691 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3692                             tsubst_flags_t complain)
3693 {
3694   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3695       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3696           != TEMPLATE_PARM_LEVEL (index) - levels)
3697       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3698     {
3699       tree orig_decl = TEMPLATE_PARM_DECL (index);
3700       tree decl, t;
3701
3702       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3703                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3704       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3705       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3706       DECL_ARTIFICIAL (decl) = 1;
3707       SET_DECL_TEMPLATE_PARM_P (decl);
3708
3709       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3710                                      TEMPLATE_PARM_LEVEL (index) - levels,
3711                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3712                                      decl, type);
3713       TEMPLATE_PARM_DESCENDANTS (index) = t;
3714       TEMPLATE_PARM_PARAMETER_PACK (t) 
3715         = TEMPLATE_PARM_PARAMETER_PACK (index);
3716
3717         /* Template template parameters need this.  */
3718       if (TREE_CODE (decl) == TEMPLATE_DECL)
3719         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3720           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3721            args, complain);
3722     }
3723
3724   return TEMPLATE_PARM_DESCENDANTS (index);
3725 }
3726
3727 /* Process information from new template parameter PARM and append it
3728    to the LIST being built.  This new parameter is a non-type
3729    parameter iff IS_NON_TYPE is true. This new parameter is a
3730    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3731    is in PARM_LOC.  */
3732
3733 tree
3734 process_template_parm (tree list, location_t parm_loc, tree parm,
3735                        bool is_non_type, bool is_parameter_pack)
3736 {
3737   tree decl = 0;
3738   tree defval;
3739   int idx = 0;
3740
3741   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3742   defval = TREE_PURPOSE (parm);
3743
3744   if (list)
3745     {
3746       tree p = tree_last (list);
3747
3748       if (p && TREE_VALUE (p) != error_mark_node)
3749         {
3750           p = TREE_VALUE (p);
3751           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3752             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3753           else
3754             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3755         }
3756
3757       ++idx;
3758     }
3759
3760   if (is_non_type)
3761     {
3762       parm = TREE_VALUE (parm);
3763
3764       SET_DECL_TEMPLATE_PARM_P (parm);
3765
3766       if (TREE_TYPE (parm) != error_mark_node)
3767         {
3768           /* [temp.param]
3769
3770              The top-level cv-qualifiers on the template-parameter are
3771              ignored when determining its type.  */
3772           TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3773           if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3774             TREE_TYPE (parm) = error_mark_node;
3775           else if (uses_parameter_packs (TREE_TYPE (parm))
3776                    && !is_parameter_pack
3777                    /* If we're in a nested template parameter list, the template
3778                       template parameter could be a parameter pack.  */
3779                    && processing_template_parmlist == 1)
3780             {
3781               /* This template parameter is not a parameter pack, but it
3782                  should be. Complain about "bare" parameter packs.  */
3783               check_for_bare_parameter_packs (TREE_TYPE (parm));
3784
3785               /* Recover by calling this a parameter pack.  */
3786               is_parameter_pack = true;
3787             }
3788         }
3789
3790       /* A template parameter is not modifiable.  */
3791       TREE_CONSTANT (parm) = 1;
3792       TREE_READONLY (parm) = 1;
3793       decl = build_decl (parm_loc,
3794                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3795       TREE_CONSTANT (decl) = 1;
3796       TREE_READONLY (decl) = 1;
3797       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3798         = build_template_parm_index (idx, processing_template_decl,
3799                                      processing_template_decl,
3800                                      decl, TREE_TYPE (parm));
3801
3802       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3803         = is_parameter_pack;
3804     }
3805   else
3806     {
3807       tree t;
3808       parm = TREE_VALUE (TREE_VALUE (parm));
3809
3810       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3811         {
3812           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3813           /* This is for distinguishing between real templates and template
3814              template parameters */
3815           TREE_TYPE (parm) = t;
3816           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3817           decl = parm;
3818         }
3819       else
3820         {
3821           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3822           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3823           decl = build_decl (parm_loc,
3824                              TYPE_DECL, parm, t);
3825         }
3826
3827       TYPE_NAME (t) = decl;
3828       TYPE_STUB_DECL (t) = decl;
3829       parm = decl;
3830       TEMPLATE_TYPE_PARM_INDEX (t)
3831         = build_template_parm_index (idx, processing_template_decl,
3832                                      processing_template_decl,
3833                                      decl, TREE_TYPE (parm));
3834       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3835       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3836     }
3837   DECL_ARTIFICIAL (decl) = 1;
3838   SET_DECL_TEMPLATE_PARM_P (decl);
3839   pushdecl (decl);
3840   parm = build_tree_list (defval, parm);
3841   return chainon (list, parm);
3842 }
3843
3844 /* The end of a template parameter list has been reached.  Process the
3845    tree list into a parameter vector, converting each parameter into a more
3846    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3847    as PARM_DECLs.  */
3848
3849 tree
3850 end_template_parm_list (tree parms)
3851 {
3852   int nparms;
3853   tree parm, next;
3854   tree saved_parmlist = make_tree_vec (list_length (parms));
3855
3856   current_template_parms
3857     = tree_cons (size_int (processing_template_decl),
3858                  saved_parmlist, current_template_parms);
3859
3860   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3861     {
3862       next = TREE_CHAIN (parm);
3863       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3864       TREE_CHAIN (parm) = NULL_TREE;
3865     }
3866
3867   --processing_template_parmlist;
3868
3869   return saved_parmlist;
3870 }
3871
3872 /* end_template_decl is called after a template declaration is seen.  */
3873
3874 void
3875 end_template_decl (void)
3876 {
3877   reset_specialization ();
3878
3879   if (! processing_template_decl)
3880     return;
3881
3882   /* This matches the pushlevel in begin_template_parm_list.  */
3883   finish_scope ();
3884
3885   --processing_template_decl;
3886   current_template_parms = TREE_CHAIN (current_template_parms);
3887 }
3888
3889 /* Takes a TREE_LIST representing a template parameter and convert it
3890    into an argument suitable to be passed to the type substitution
3891    functions.  Note that If the TREE_LIST contains an error_mark
3892    node, the returned argument is error_mark_node.  */
3893
3894 static tree
3895 template_parm_to_arg (tree t)
3896 {
3897
3898   if (t == NULL_TREE
3899       || TREE_CODE (t) != TREE_LIST)
3900     return t;
3901
3902   if (error_operand_p (TREE_VALUE (t)))
3903     return error_mark_node;
3904
3905   t = TREE_VALUE (t);
3906
3907   if (TREE_CODE (t) == TYPE_DECL
3908       || TREE_CODE (t) == TEMPLATE_DECL)
3909     {
3910       t = TREE_TYPE (t);
3911
3912       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3913         {
3914           /* Turn this argument into a TYPE_ARGUMENT_PACK
3915              with a single element, which expands T.  */
3916           tree vec = make_tree_vec (1);
3917 #ifdef ENABLE_CHECKING
3918           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3919             (vec, TREE_VEC_LENGTH (vec));
3920 #endif
3921           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3922
3923           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3924           SET_ARGUMENT_PACK_ARGS (t, vec);
3925         }
3926     }
3927   else
3928     {
3929       t = DECL_INITIAL (t);
3930
3931       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3932         {
3933           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3934              with a single element, which expands T.  */
3935           tree vec = make_tree_vec (1);
3936           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3937 #ifdef ENABLE_CHECKING
3938           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3939             (vec, TREE_VEC_LENGTH (vec));
3940 #endif
3941           t = convert_from_reference (t);
3942           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3943
3944           t  = make_node (NONTYPE_ARGUMENT_PACK);
3945           SET_ARGUMENT_PACK_ARGS (t, vec);
3946           TREE_TYPE (t) = type;
3947         }
3948       else
3949         t = convert_from_reference (t);
3950     }
3951   return t;
3952 }
3953
3954 /* Given a set of template parameters, return them as a set of template
3955    arguments.  The template parameters are represented as a TREE_VEC, in
3956    the form documented in cp-tree.h for template arguments.  */
3957
3958 static tree
3959 template_parms_to_args (tree parms)
3960 {
3961   tree header;
3962   tree args = NULL_TREE;
3963   int length = TMPL_PARMS_DEPTH (parms);
3964   int l = length;
3965
3966   /* If there is only one level of template parameters, we do not
3967      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3968      TREE_VEC containing the arguments.  */
3969   if (length > 1)
3970     args = make_tree_vec (length);
3971
3972   for (header = parms; header; header = TREE_CHAIN (header))
3973     {
3974       tree a = copy_node (TREE_VALUE (header));
3975       int i;
3976
3977       TREE_TYPE (a) = NULL_TREE;
3978       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3979         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
3980
3981 #ifdef ENABLE_CHECKING
3982       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3983 #endif
3984
3985       if (length > 1)
3986         TREE_VEC_ELT (args, --l) = a;
3987       else
3988         args = a;
3989     }
3990
3991     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
3992       /* This can happen for template parms of a template template
3993          parameter, e.g:
3994
3995          template<template<class T, class U> class TT> struct S;
3996
3997          Consider the level of the parms of TT; T and U both have
3998          level 2; TT has no template parm of level 1. So in this case
3999          the first element of full_template_args is NULL_TREE. If we
4000          leave it like this TMPL_ARGS_DEPTH on args returns 1 instead
4001          of 2. This will make tsubst wrongly consider that T and U
4002          have level 1. Instead, let's create a dummy vector as the
4003          first element of full_template_args so that TMPL_ARGS_DEPTH
4004          returns the correct depth for args.  */
4005       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4006   return args;
4007 }
4008
4009 /* Within the declaration of a template, return the currently active
4010    template parameters as an argument TREE_VEC.  */
4011
4012 static tree
4013 current_template_args (void)
4014 {
4015   return template_parms_to_args (current_template_parms);
4016 }
4017
4018 /* Update the declared TYPE by doing any lookups which were thought to be
4019    dependent, but are not now that we know the SCOPE of the declarator.  */
4020
4021 tree
4022 maybe_update_decl_type (tree orig_type, tree scope)
4023 {
4024   tree type = orig_type;
4025
4026   if (type == NULL_TREE)
4027     return type;
4028
4029   if (TREE_CODE (orig_type) == TYPE_DECL)
4030     type = TREE_TYPE (type);
4031
4032   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4033       && dependent_type_p (type)
4034       /* Don't bother building up the args in this case.  */
4035       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4036     {
4037       /* tsubst in the args corresponding to the template parameters,
4038          including auto if present.  Most things will be unchanged, but
4039          make_typename_type and tsubst_qualified_id will resolve
4040          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4041       tree args = current_template_args ();
4042       tree auto_node = type_uses_auto (type);
4043       tree pushed;
4044       if (auto_node)
4045         {
4046           tree auto_vec = make_tree_vec (1);
4047           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4048           args = add_to_template_args (args, auto_vec);
4049         }
4050       pushed = push_scope (scope);
4051       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4052       if (pushed)
4053         pop_scope (scope);
4054     }
4055
4056   if (type == error_mark_node)
4057     return orig_type;
4058
4059   if (TREE_CODE (orig_type) == TYPE_DECL)
4060     {
4061       if (same_type_p (type, TREE_TYPE (orig_type)))
4062         type = orig_type;
4063       else
4064         type = TYPE_NAME (type);
4065     }
4066   return type;
4067 }
4068
4069 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4070    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4071    a member template.  Used by push_template_decl below.  */
4072
4073 static tree
4074 build_template_decl (tree decl, tree parms, bool member_template_p)
4075 {
4076   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4077   DECL_TEMPLATE_PARMS (tmpl) = parms;
4078   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4079   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4080   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4081
4082   return tmpl;
4083 }
4084
4085 struct template_parm_data
4086 {
4087   /* The level of the template parameters we are currently
4088      processing.  */
4089   int level;
4090
4091   /* The index of the specialization argument we are currently
4092      processing.  */
4093   int current_arg;
4094
4095   /* An array whose size is the number of template parameters.  The
4096      elements are nonzero if the parameter has been used in any one
4097      of the arguments processed so far.  */
4098   int* parms;
4099
4100   /* An array whose size is the number of template arguments.  The
4101      elements are nonzero if the argument makes use of template
4102      parameters of this level.  */
4103   int* arg_uses_template_parms;
4104 };
4105
4106 /* Subroutine of push_template_decl used to see if each template
4107    parameter in a partial specialization is used in the explicit
4108    argument list.  If T is of the LEVEL given in DATA (which is
4109    treated as a template_parm_data*), then DATA->PARMS is marked
4110    appropriately.  */
4111
4112 static int
4113 mark_template_parm (tree t, void* data)
4114 {
4115   int level;
4116   int idx;
4117   struct template_parm_data* tpd = (struct template_parm_data*) data;
4118
4119   template_parm_level_and_index (t, &level, &idx);
4120
4121   if (level == tpd->level)
4122     {
4123       tpd->parms[idx] = 1;
4124       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4125     }
4126
4127   /* Return zero so that for_each_template_parm will continue the
4128      traversal of the tree; we want to mark *every* template parm.  */
4129   return 0;
4130 }
4131
4132 /* Process the partial specialization DECL.  */
4133
4134 static tree
4135 process_partial_specialization (tree decl)
4136 {
4137   tree type = TREE_TYPE (decl);
4138   tree tinfo = get_template_info (decl);
4139   tree maintmpl = TI_TEMPLATE (tinfo);
4140   tree specargs = TI_ARGS (tinfo);
4141   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4142   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4143   tree inner_parms;
4144   tree inst;
4145   int nargs = TREE_VEC_LENGTH (inner_args);
4146   int ntparms;
4147   int  i;
4148   bool did_error_intro = false;
4149   struct template_parm_data tpd;
4150   struct template_parm_data tpd2;
4151
4152   gcc_assert (current_template_parms);
4153
4154   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4155   ntparms = TREE_VEC_LENGTH (inner_parms);
4156
4157   /* We check that each of the template parameters given in the
4158      partial specialization is used in the argument list to the
4159      specialization.  For example:
4160
4161        template <class T> struct S;
4162        template <class T> struct S<T*>;
4163
4164      The second declaration is OK because `T*' uses the template
4165      parameter T, whereas
4166
4167        template <class T> struct S<int>;
4168
4169      is no good.  Even trickier is:
4170
4171        template <class T>
4172        struct S1
4173        {
4174           template <class U>
4175           struct S2;
4176           template <class U>
4177           struct S2<T>;
4178        };
4179
4180      The S2<T> declaration is actually invalid; it is a
4181      full-specialization.  Of course,
4182
4183           template <class U>
4184           struct S2<T (*)(U)>;
4185
4186      or some such would have been OK.  */
4187   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4188   tpd.parms = XALLOCAVEC (int, ntparms);
4189   memset (tpd.parms, 0, sizeof (int) * ntparms);
4190
4191   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4192   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4193   for (i = 0; i < nargs; ++i)
4194     {
4195       tpd.current_arg = i;
4196       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4197                               &mark_template_parm,
4198                               &tpd,
4199                               NULL,
4200                               /*include_nondeduced_p=*/false);
4201     }
4202   for (i = 0; i < ntparms; ++i)
4203     if (tpd.parms[i] == 0)
4204       {
4205         /* One of the template parms was not used in a deduced context in the
4206            specialization.  */
4207         if (!did_error_intro)
4208           {
4209             error ("template parameters not deducible in "
4210                    "partial specialization:");
4211             did_error_intro = true;
4212           }
4213
4214         inform (input_location, "        %qD",
4215                 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4216       }
4217
4218   if (did_error_intro)
4219     return error_mark_node;
4220
4221   /* [temp.class.spec]
4222
4223      The argument list of the specialization shall not be identical to
4224      the implicit argument list of the primary template.  */
4225   tree main_args
4226     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4227   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args)))
4228     error ("partial specialization %qD does not specialize "
4229            "any template arguments", decl);
4230
4231   /* A partial specialization that replaces multiple parameters of the
4232      primary template with a pack expansion is less specialized for those
4233      parameters.  */
4234   if (nargs < DECL_NTPARMS (maintmpl))
4235     {
4236       error ("partial specialization is not more specialized than the "
4237              "primary template because it replaces multiple parameters "
4238              "with a pack expansion");
4239       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4240       return decl;
4241     }
4242
4243   /* [temp.class.spec]
4244
4245      A partially specialized non-type argument expression shall not
4246      involve template parameters of the partial specialization except
4247      when the argument expression is a simple identifier.
4248
4249      The type of a template parameter corresponding to a specialized
4250      non-type argument shall not be dependent on a parameter of the
4251      specialization. 
4252
4253      Also, we verify that pack expansions only occur at the
4254      end of the argument list.  */
4255   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4256   tpd2.parms = 0;
4257   for (i = 0; i < nargs; ++i)
4258     {
4259       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4260       tree arg = TREE_VEC_ELT (inner_args, i);
4261       tree packed_args = NULL_TREE;
4262       int j, len = 1;
4263
4264       if (ARGUMENT_PACK_P (arg))
4265         {
4266           /* Extract the arguments from the argument pack. We'll be
4267              iterating over these in the following loop.  */
4268           packed_args = ARGUMENT_PACK_ARGS (arg);
4269           len = TREE_VEC_LENGTH (packed_args);
4270         }
4271
4272       for (j = 0; j < len; j++)
4273         {
4274           if (packed_args)
4275             /* Get the Jth argument in the parameter pack.  */
4276             arg = TREE_VEC_ELT (packed_args, j);
4277
4278           if (PACK_EXPANSION_P (arg))
4279             {
4280               /* Pack expansions must come at the end of the
4281                  argument list.  */
4282               if ((packed_args && j < len - 1)
4283                   || (!packed_args && i < nargs - 1))
4284                 {
4285                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4286                     error ("parameter pack argument %qE must be at the "
4287                            "end of the template argument list", arg);
4288                   else
4289                     error ("parameter pack argument %qT must be at the "
4290                            "end of the template argument list", arg);
4291                 }
4292             }
4293
4294           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4295             /* We only care about the pattern.  */
4296             arg = PACK_EXPANSION_PATTERN (arg);
4297
4298           if (/* These first two lines are the `non-type' bit.  */
4299               !TYPE_P (arg)
4300               && TREE_CODE (arg) != TEMPLATE_DECL
4301               /* This next two lines are the `argument expression is not just a
4302                  simple identifier' condition and also the `specialized
4303                  non-type argument' bit.  */
4304               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4305               && !(REFERENCE_REF_P (arg)
4306                    && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4307             {
4308               if ((!packed_args && tpd.arg_uses_template_parms[i])
4309                   || (packed_args && uses_template_parms (arg)))
4310                 error ("template argument %qE involves template parameter(s)",
4311                        arg);
4312               else 
4313                 {
4314                   /* Look at the corresponding template parameter,
4315                      marking which template parameters its type depends
4316                      upon.  */
4317                   tree type = TREE_TYPE (parm);
4318
4319                   if (!tpd2.parms)
4320                     {
4321                       /* We haven't yet initialized TPD2.  Do so now.  */
4322                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4323                       /* The number of parameters here is the number in the
4324                          main template, which, as checked in the assertion
4325                          above, is NARGS.  */
4326                       tpd2.parms = XALLOCAVEC (int, nargs);
4327                       tpd2.level = 
4328                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4329                     }
4330
4331                   /* Mark the template parameters.  But this time, we're
4332                      looking for the template parameters of the main
4333                      template, not in the specialization.  */
4334                   tpd2.current_arg = i;
4335                   tpd2.arg_uses_template_parms[i] = 0;
4336                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4337                   for_each_template_parm (type,
4338                                           &mark_template_parm,
4339                                           &tpd2,
4340                                           NULL,
4341                                           /*include_nondeduced_p=*/false);
4342
4343                   if (tpd2.arg_uses_template_parms [i])
4344                     {
4345                       /* The type depended on some template parameters.
4346                          If they are fully specialized in the
4347                          specialization, that's OK.  */
4348                       int j;
4349                       int count = 0;
4350                       for (j = 0; j < nargs; ++j)
4351                         if (tpd2.parms[j] != 0
4352                             && tpd.arg_uses_template_parms [j])
4353                           ++count;
4354                       if (count != 0)
4355                         error_n (input_location, count,
4356                                  "type %qT of template argument %qE depends "
4357                                  "on a template parameter",
4358                                  "type %qT of template argument %qE depends "
4359                                  "on template parameters",
4360                                  type,
4361                                  arg);
4362                     }
4363                 }
4364             }
4365         }
4366     }
4367
4368   /* We should only get here once.  */
4369   if (TREE_CODE (decl) == TYPE_DECL)
4370     gcc_assert (!COMPLETE_TYPE_P (type));
4371
4372   tree tmpl = build_template_decl (decl, current_template_parms,
4373                                    DECL_MEMBER_TEMPLATE_P (maintmpl));
4374   TREE_TYPE (tmpl) = type;
4375   DECL_TEMPLATE_RESULT (tmpl) = decl;
4376   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4377   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
4378   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
4379
4380   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4381     = tree_cons (specargs, tmpl,
4382                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4383   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4384
4385   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4386        inst = TREE_CHAIN (inst))
4387     {
4388       tree instance = TREE_VALUE (inst);
4389       if (TYPE_P (instance)
4390           ? (COMPLETE_TYPE_P (instance)
4391              && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
4392           : DECL_TEMPLATE_INSTANTIATION (instance))
4393         {
4394           tree spec = most_specialized_partial_spec (instance, tf_none);
4395           if (spec && TREE_VALUE (spec) == tmpl)
4396             {
4397               tree inst_decl = (DECL_P (instance)
4398                                 ? instance : TYPE_NAME (instance));
4399               permerror (input_location,
4400                          "partial specialization of %qD after instantiation "
4401                          "of %qD", decl, inst_decl);
4402             }
4403         }
4404     }
4405
4406   return decl;
4407 }
4408
4409 /* PARM is a template parameter of some form; return the corresponding
4410    TEMPLATE_PARM_INDEX.  */
4411
4412 static tree
4413 get_template_parm_index (tree parm)
4414 {
4415   if (TREE_CODE (parm) == PARM_DECL
4416       || TREE_CODE (parm) == CONST_DECL)
4417     parm = DECL_INITIAL (parm);
4418   else if (TREE_CODE (parm) == TYPE_DECL
4419            || TREE_CODE (parm) == TEMPLATE_DECL)
4420     parm = TREE_TYPE (parm);
4421   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
4422       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
4423       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
4424     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
4425   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
4426   return parm;
4427 }
4428
4429 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
4430    parameter packs used by the template parameter PARM.  */
4431
4432 static void
4433 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
4434 {
4435   /* A type parm can't refer to another parm.  */
4436   if (TREE_CODE (parm) == TYPE_DECL)
4437     return;
4438   else if (TREE_CODE (parm) == PARM_DECL)
4439     {
4440       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
4441                     ppd, ppd->visited);
4442       return;
4443     }
4444
4445   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
4446
4447   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
4448   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
4449     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
4450 }
4451
4452 /* PARM is a template parameter pack.  Return any parameter packs used in
4453    its type or the type of any of its template parameters.  If there are
4454    any such packs, it will be instantiated into a fixed template parameter
4455    list by partial instantiation rather than be fully deduced.  */
4456
4457 tree
4458 fixed_parameter_pack_p (tree parm)
4459 {
4460   /* This can only be true in a member template.  */
4461   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
4462     return NULL_TREE;
4463   /* This can only be true for a parameter pack.  */
4464   if (!template_parameter_pack_p (parm))
4465     return NULL_TREE;
4466   /* A type parm can't refer to another parm.  */
4467   if (TREE_CODE (parm) == TYPE_DECL)
4468     return NULL_TREE;
4469
4470   tree parameter_packs = NULL_TREE;
4471   struct find_parameter_pack_data ppd;
4472   ppd.parameter_packs = &parameter_packs;
4473   ppd.visited = new hash_set<tree>;
4474
4475   fixed_parameter_pack_p_1 (parm, &ppd);
4476
4477   delete ppd.visited;
4478   return parameter_packs;
4479 }
4480
4481 /* Check that a template declaration's use of default arguments and
4482    parameter packs is not invalid.  Here, PARMS are the template
4483    parameters.  IS_PRIMARY is true if DECL is the thing declared by
4484    a primary template.  IS_PARTIAL is true if DECL is a partial
4485    specialization.
4486
4487    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4488    declaration (but not a definition); 1 indicates a declaration, 2
4489    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4490    emitted for extraneous default arguments.
4491
4492    Returns TRUE if there were no errors found, FALSE otherwise. */
4493
4494 bool
4495 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
4496                          bool is_partial, int is_friend_decl)
4497 {
4498   const char *msg;
4499   int last_level_to_check;
4500   tree parm_level;
4501   bool no_errors = true;
4502
4503   /* [temp.param]
4504
4505      A default template-argument shall not be specified in a
4506      function template declaration or a function template definition, nor
4507      in the template-parameter-list of the definition of a member of a
4508      class template.  */
4509
4510   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
4511       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
4512     /* You can't have a function template declaration in a local
4513        scope, nor you can you define a member of a class template in a
4514        local scope.  */
4515     return true;
4516
4517   if ((TREE_CODE (decl) == TYPE_DECL
4518        && TREE_TYPE (decl)
4519        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4520       || (TREE_CODE (decl) == FUNCTION_DECL
4521           && LAMBDA_FUNCTION_P (decl)))
4522     /* A lambda doesn't have an explicit declaration; don't complain
4523        about the parms of the enclosing class.  */
4524     return true;
4525
4526   if (current_class_type
4527       && !TYPE_BEING_DEFINED (current_class_type)
4528       && DECL_LANG_SPECIFIC (decl)
4529       && DECL_DECLARES_FUNCTION_P (decl)
4530       /* If this is either a friend defined in the scope of the class
4531          or a member function.  */
4532       && (DECL_FUNCTION_MEMBER_P (decl)
4533           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4534           : DECL_FRIEND_CONTEXT (decl)
4535           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4536           : false)
4537       /* And, if it was a member function, it really was defined in
4538          the scope of the class.  */
4539       && (!DECL_FUNCTION_MEMBER_P (decl)
4540           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4541     /* We already checked these parameters when the template was
4542        declared, so there's no need to do it again now.  This function
4543        was defined in class scope, but we're processing its body now
4544        that the class is complete.  */
4545     return true;
4546
4547   /* Core issue 226 (C++0x only): the following only applies to class
4548      templates.  */
4549   if (is_primary
4550       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
4551     {
4552       /* [temp.param]
4553
4554          If a template-parameter has a default template-argument, all
4555          subsequent template-parameters shall have a default
4556          template-argument supplied.  */
4557       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4558         {
4559           tree inner_parms = TREE_VALUE (parm_level);
4560           int ntparms = TREE_VEC_LENGTH (inner_parms);
4561           int seen_def_arg_p = 0;
4562           int i;
4563
4564           for (i = 0; i < ntparms; ++i)
4565             {
4566               tree parm = TREE_VEC_ELT (inner_parms, i);
4567
4568               if (parm == error_mark_node)
4569                 continue;
4570
4571               if (TREE_PURPOSE (parm))
4572                 seen_def_arg_p = 1;
4573               else if (seen_def_arg_p
4574                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4575                 {
4576                   error ("no default argument for %qD", TREE_VALUE (parm));
4577                   /* For better subsequent error-recovery, we indicate that
4578                      there should have been a default argument.  */
4579                   TREE_PURPOSE (parm) = error_mark_node;
4580                   no_errors = false;
4581                 }
4582               else if (!is_partial
4583                        && !is_friend_decl
4584                        /* Don't complain about an enclosing partial
4585                           specialization.  */
4586                        && parm_level == parms
4587                        && TREE_CODE (decl) == TYPE_DECL
4588                        && i < ntparms - 1
4589                        && template_parameter_pack_p (TREE_VALUE (parm))
4590                        /* A fixed parameter pack will be partially
4591                           instantiated into a fixed length list.  */
4592                        && !fixed_parameter_pack_p (TREE_VALUE (parm)))
4593                 {
4594                   /* A primary class template can only have one
4595                      parameter pack, at the end of the template
4596                      parameter list.  */
4597
4598                   error ("parameter pack %q+D must be at the end of the"
4599                          " template parameter list", TREE_VALUE (parm));
4600
4601                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4602                     = error_mark_node;
4603                   no_errors = false;
4604                 }
4605             }
4606         }
4607     }
4608
4609   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4610       || is_partial 
4611       || !is_primary
4612       || is_friend_decl)
4613     /* For an ordinary class template, default template arguments are
4614        allowed at the innermost level, e.g.:
4615          template <class T = int>
4616          struct S {};
4617        but, in a partial specialization, they're not allowed even
4618        there, as we have in [temp.class.spec]:
4619
4620          The template parameter list of a specialization shall not
4621          contain default template argument values.
4622
4623        So, for a partial specialization, or for a function template
4624        (in C++98/C++03), we look at all of them.  */
4625     ;
4626   else
4627     /* But, for a primary class template that is not a partial
4628        specialization we look at all template parameters except the
4629        innermost ones.  */
4630     parms = TREE_CHAIN (parms);
4631
4632   /* Figure out what error message to issue.  */
4633   if (is_friend_decl == 2)
4634     msg = G_("default template arguments may not be used in function template "
4635              "friend re-declaration");
4636   else if (is_friend_decl)
4637     msg = G_("default template arguments may not be used in function template "
4638              "friend declarations");
4639   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4640     msg = G_("default template arguments may not be used in function templates "
4641              "without -std=c++11 or -std=gnu++11");
4642   else if (is_partial)
4643     msg = G_("default template arguments may not be used in "
4644              "partial specializations");
4645   else
4646     msg = G_("default argument for template parameter for class enclosing %qD");
4647
4648   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4649     /* If we're inside a class definition, there's no need to
4650        examine the parameters to the class itself.  On the one
4651        hand, they will be checked when the class is defined, and,
4652        on the other, default arguments are valid in things like:
4653          template <class T = double>
4654          struct S { template <class U> void f(U); };
4655        Here the default argument for `S' has no bearing on the
4656        declaration of `f'.  */
4657     last_level_to_check = template_class_depth (current_class_type) + 1;
4658   else
4659     /* Check everything.  */
4660     last_level_to_check = 0;
4661
4662   for (parm_level = parms;
4663        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4664        parm_level = TREE_CHAIN (parm_level))
4665     {
4666       tree inner_parms = TREE_VALUE (parm_level);
4667       int i;
4668       int ntparms;
4669
4670       ntparms = TREE_VEC_LENGTH (inner_parms);
4671       for (i = 0; i < ntparms; ++i)
4672         {
4673           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4674             continue;
4675
4676           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4677             {
4678               if (msg)
4679                 {
4680                   no_errors = false;
4681                   if (is_friend_decl == 2)
4682                     return no_errors;
4683
4684                   error (msg, decl);
4685                   msg = 0;
4686                 }
4687
4688               /* Clear out the default argument so that we are not
4689                  confused later.  */
4690               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4691             }
4692         }
4693
4694       /* At this point, if we're still interested in issuing messages,
4695          they must apply to classes surrounding the object declared.  */
4696       if (msg)
4697         msg = G_("default argument for template parameter for class "
4698                  "enclosing %qD");
4699     }
4700
4701   return no_errors;
4702 }
4703
4704 /* Worker for push_template_decl_real, called via
4705    for_each_template_parm.  DATA is really an int, indicating the
4706    level of the parameters we are interested in.  If T is a template
4707    parameter of that level, return nonzero.  */
4708
4709 static int
4710 template_parm_this_level_p (tree t, void* data)
4711 {
4712   int this_level = *(int *)data;
4713   int level;
4714
4715   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4716     level = TEMPLATE_PARM_LEVEL (t);
4717   else
4718     level = TEMPLATE_TYPE_LEVEL (t);
4719   return level == this_level;
4720 }
4721
4722 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4723    parameters given by current_template_args, or reuses a
4724    previously existing one, if appropriate.  Returns the DECL, or an
4725    equivalent one, if it is replaced via a call to duplicate_decls.
4726
4727    If IS_FRIEND is true, DECL is a friend declaration.  */
4728
4729 tree
4730 push_template_decl_real (tree decl, bool is_friend)
4731 {
4732   tree tmpl;
4733   tree args;
4734   tree info;
4735   tree ctx;
4736   bool is_primary;
4737   bool is_partial;
4738   int new_template_p = 0;
4739   /* True if the template is a member template, in the sense of
4740      [temp.mem].  */
4741   bool member_template_p = false;
4742
4743   if (decl == error_mark_node || !current_template_parms)
4744     return error_mark_node;
4745
4746   /* See if this is a partial specialization.  */
4747   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
4748                  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4749                  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
4750                 || (TREE_CODE (decl) == VAR_DECL
4751                     && DECL_LANG_SPECIFIC (decl)
4752                     && DECL_TEMPLATE_SPECIALIZATION (decl)
4753                     && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
4754
4755   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4756     is_friend = true;
4757
4758   if (is_friend)
4759     /* For a friend, we want the context of the friend function, not
4760        the type of which it is a friend.  */
4761     ctx = CP_DECL_CONTEXT (decl);
4762   else if (CP_DECL_CONTEXT (decl)
4763            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4764     /* In the case of a virtual function, we want the class in which
4765        it is defined.  */
4766     ctx = CP_DECL_CONTEXT (decl);
4767   else
4768     /* Otherwise, if we're currently defining some class, the DECL
4769        is assumed to be a member of the class.  */
4770     ctx = current_scope ();
4771
4772   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4773     ctx = NULL_TREE;
4774
4775   if (!DECL_CONTEXT (decl))
4776     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4777
4778   /* See if this is a primary template.  */
4779   if (is_friend && ctx
4780       && uses_template_parms_level (ctx, processing_template_decl))
4781     /* A friend template that specifies a class context, i.e.
4782          template <typename T> friend void A<T>::f();
4783        is not primary.  */
4784     is_primary = false;
4785   else if (TREE_CODE (decl) == TYPE_DECL
4786            && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4787     is_primary = false;
4788   else
4789     is_primary = template_parm_scope_p ();
4790
4791   if (is_primary)
4792     {
4793       if (DECL_CLASS_SCOPE_P (decl))
4794         member_template_p = true;
4795       if (TREE_CODE (decl) == TYPE_DECL
4796           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4797         {
4798           error ("template class without a name");
4799           return error_mark_node;
4800         }
4801       else if (TREE_CODE (decl) == FUNCTION_DECL)
4802         {
4803           if (member_template_p)
4804             {
4805               if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
4806                 error ("member template %qD may not have virt-specifiers", decl);
4807             }
4808           if (DECL_DESTRUCTOR_P (decl))
4809             {
4810               /* [temp.mem]
4811
4812                  A destructor shall not be a member template.  */
4813               error ("destructor %qD declared as member template", decl);
4814               return error_mark_node;
4815             }
4816           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4817               && (!prototype_p (TREE_TYPE (decl))
4818                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4819                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4820                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4821                       == void_list_node)))
4822             {
4823               /* [basic.stc.dynamic.allocation]
4824
4825                  An allocation function can be a function
4826                  template. ... Template allocation functions shall
4827                  have two or more parameters.  */
4828               error ("invalid template declaration of %qD", decl);
4829               return error_mark_node;
4830             }
4831         }
4832       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4833                && CLASS_TYPE_P (TREE_TYPE (decl)))
4834         /* OK */;
4835       else if (TREE_CODE (decl) == TYPE_DECL
4836                && TYPE_DECL_ALIAS_P (decl))
4837         /* alias-declaration */
4838         gcc_assert (!DECL_ARTIFICIAL (decl));
4839       else if (VAR_P (decl))
4840         /* C++14 variable template. */;
4841       else
4842         {
4843           error ("template declaration of %q#D", decl);
4844           return error_mark_node;
4845         }
4846     }
4847
4848   /* Check to see that the rules regarding the use of default
4849      arguments are not being violated.  */
4850   check_default_tmpl_args (decl, current_template_parms,
4851                            is_primary, is_partial, /*is_friend_decl=*/0);
4852
4853   /* Ensure that there are no parameter packs in the type of this
4854      declaration that have not been expanded.  */
4855   if (TREE_CODE (decl) == FUNCTION_DECL)
4856     {
4857       /* Check each of the arguments individually to see if there are
4858          any bare parameter packs.  */
4859       tree type = TREE_TYPE (decl);
4860       tree arg = DECL_ARGUMENTS (decl);
4861       tree argtype = TYPE_ARG_TYPES (type);
4862
4863       while (arg && argtype)
4864         {
4865           if (!DECL_PACK_P (arg)
4866               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4867             {
4868             /* This is a PARM_DECL that contains unexpanded parameter
4869                packs. We have already complained about this in the
4870                check_for_bare_parameter_packs call, so just replace
4871                these types with ERROR_MARK_NODE.  */
4872               TREE_TYPE (arg) = error_mark_node;
4873               TREE_VALUE (argtype) = error_mark_node;
4874             }
4875
4876           arg = DECL_CHAIN (arg);
4877           argtype = TREE_CHAIN (argtype);
4878         }
4879
4880       /* Check for bare parameter packs in the return type and the
4881          exception specifiers.  */
4882       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4883         /* Errors were already issued, set return type to int
4884            as the frontend doesn't expect error_mark_node as
4885            the return type.  */
4886         TREE_TYPE (type) = integer_type_node;
4887       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4888         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4889     }
4890   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
4891                                             && TYPE_DECL_ALIAS_P (decl))
4892                                            ? DECL_ORIGINAL_TYPE (decl)
4893                                            : TREE_TYPE (decl)))
4894     {
4895       TREE_TYPE (decl) = error_mark_node;
4896       return error_mark_node;
4897     }
4898
4899   if (is_partial)
4900     return process_partial_specialization (decl);
4901
4902   args = current_template_args ();
4903
4904   if (!ctx
4905       || TREE_CODE (ctx) == FUNCTION_DECL
4906       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4907       || (TREE_CODE (decl) == TYPE_DECL
4908           && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4909       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4910     {
4911       if (DECL_LANG_SPECIFIC (decl)
4912           && DECL_TEMPLATE_INFO (decl)
4913           && DECL_TI_TEMPLATE (decl))
4914         tmpl = DECL_TI_TEMPLATE (decl);
4915       /* If DECL is a TYPE_DECL for a class-template, then there won't
4916          be DECL_LANG_SPECIFIC.  The information equivalent to
4917          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4918       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4919                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4920                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4921         {
4922           /* Since a template declaration already existed for this
4923              class-type, we must be redeclaring it here.  Make sure
4924              that the redeclaration is valid.  */
4925           redeclare_class_template (TREE_TYPE (decl),
4926                                     current_template_parms);
4927           /* We don't need to create a new TEMPLATE_DECL; just use the
4928              one we already had.  */
4929           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4930         }
4931       else
4932         {
4933           tmpl = build_template_decl (decl, current_template_parms,
4934                                       member_template_p);
4935           new_template_p = 1;
4936
4937           if (DECL_LANG_SPECIFIC (decl)
4938               && DECL_TEMPLATE_SPECIALIZATION (decl))
4939             {
4940               /* A specialization of a member template of a template
4941                  class.  */
4942               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4943               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4944               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4945             }
4946         }
4947     }
4948   else
4949     {
4950       tree a, t, current, parms;
4951       int i;
4952       tree tinfo = get_template_info (decl);
4953
4954       if (!tinfo)
4955         {
4956           error ("template definition of non-template %q#D", decl);
4957           return error_mark_node;
4958         }
4959
4960       tmpl = TI_TEMPLATE (tinfo);
4961
4962       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4963           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4964           && DECL_TEMPLATE_SPECIALIZATION (decl)
4965           && DECL_MEMBER_TEMPLATE_P (tmpl))
4966         {
4967           tree new_tmpl;
4968
4969           /* The declaration is a specialization of a member
4970              template, declared outside the class.  Therefore, the
4971              innermost template arguments will be NULL, so we
4972              replace them with the arguments determined by the
4973              earlier call to check_explicit_specialization.  */
4974           args = DECL_TI_ARGS (decl);
4975
4976           new_tmpl
4977             = build_template_decl (decl, current_template_parms,
4978                                    member_template_p);
4979           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4980           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4981           DECL_TI_TEMPLATE (decl) = new_tmpl;
4982           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4983           DECL_TEMPLATE_INFO (new_tmpl)
4984             = build_template_info (tmpl, args);
4985
4986           register_specialization (new_tmpl,
4987                                    most_general_template (tmpl),
4988                                    args,
4989                                    is_friend, 0);
4990           return decl;
4991         }
4992
4993       /* Make sure the template headers we got make sense.  */
4994
4995       parms = DECL_TEMPLATE_PARMS (tmpl);
4996       i = TMPL_PARMS_DEPTH (parms);
4997       if (TMPL_ARGS_DEPTH (args) != i)
4998         {
4999           error ("expected %d levels of template parms for %q#D, got %d",
5000                  i, decl, TMPL_ARGS_DEPTH (args));
5001           DECL_INTERFACE_KNOWN (decl) = 1;
5002           return error_mark_node;
5003         }
5004       else
5005         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5006           {
5007             a = TMPL_ARGS_LEVEL (args, i);
5008             t = INNERMOST_TEMPLATE_PARMS (parms);
5009
5010             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5011               {
5012                 if (current == decl)
5013                   error ("got %d template parameters for %q#D",
5014                          TREE_VEC_LENGTH (a), decl);
5015                 else
5016                   error ("got %d template parameters for %q#T",
5017                          TREE_VEC_LENGTH (a), current);
5018                 error ("  but %d required", TREE_VEC_LENGTH (t));
5019                 /* Avoid crash in import_export_decl.  */
5020                 DECL_INTERFACE_KNOWN (decl) = 1;
5021                 return error_mark_node;
5022               }
5023
5024             if (current == decl)
5025               current = ctx;
5026             else if (current == NULL_TREE)
5027               /* Can happen in erroneous input.  */
5028               break;
5029             else
5030               current = get_containing_scope (current);
5031           }
5032
5033       /* Check that the parms are used in the appropriate qualifying scopes
5034          in the declarator.  */
5035       if (!comp_template_args
5036           (TI_ARGS (tinfo),
5037            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5038         {
5039           error ("\
5040 template arguments to %qD do not match original template %qD",
5041                  decl, DECL_TEMPLATE_RESULT (tmpl));
5042           if (!uses_template_parms (TI_ARGS (tinfo)))
5043             inform (input_location, "use template<> for an explicit specialization");
5044           /* Avoid crash in import_export_decl.  */
5045           DECL_INTERFACE_KNOWN (decl) = 1;
5046           return error_mark_node;
5047         }
5048     }
5049
5050   DECL_TEMPLATE_RESULT (tmpl) = decl;
5051   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5052
5053   /* Push template declarations for global functions and types.  Note
5054      that we do not try to push a global template friend declared in a
5055      template class; such a thing may well depend on the template
5056      parameters of the class.  */
5057   if (new_template_p && !ctx
5058       && !(is_friend && template_class_depth (current_class_type) > 0))
5059     {
5060       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5061       if (tmpl == error_mark_node)
5062         return error_mark_node;
5063
5064       /* Hide template friend classes that haven't been declared yet.  */
5065       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5066         {
5067           DECL_ANTICIPATED (tmpl) = 1;
5068           DECL_FRIEND_P (tmpl) = 1;
5069         }
5070     }
5071
5072   if (is_primary)
5073     {
5074       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5075       int i;
5076
5077       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5078       if (DECL_CONV_FN_P (tmpl))
5079         {
5080           int depth = TMPL_PARMS_DEPTH (parms);
5081
5082           /* It is a conversion operator. See if the type converted to
5083              depends on innermost template operands.  */
5084
5085           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5086                                          depth))
5087             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5088         }
5089
5090       /* Give template template parms a DECL_CONTEXT of the template
5091          for which they are a parameter.  */
5092       parms = INNERMOST_TEMPLATE_PARMS (parms);
5093       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5094         {
5095           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5096           if (TREE_CODE (parm) == TEMPLATE_DECL)
5097             DECL_CONTEXT (parm) = tmpl;
5098         }
5099
5100       if (TREE_CODE (decl) == TYPE_DECL
5101           && TYPE_DECL_ALIAS_P (decl)
5102           && complex_alias_template_p (tmpl))
5103         TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5104     }
5105
5106   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5107      back to its most general template.  If TMPL is a specialization,
5108      ARGS may only have the innermost set of arguments.  Add the missing
5109      argument levels if necessary.  */
5110   if (DECL_TEMPLATE_INFO (tmpl))
5111     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5112
5113   info = build_template_info (tmpl, args);
5114
5115   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5116     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5117   else
5118     {
5119       if (is_primary && !DECL_LANG_SPECIFIC (decl))
5120         retrofit_lang_decl (decl);
5121       if (DECL_LANG_SPECIFIC (decl))
5122         DECL_TEMPLATE_INFO (decl) = info;
5123     }
5124
5125   if (flag_implicit_templates
5126       && !is_friend
5127       && TREE_PUBLIC (decl)
5128       && VAR_OR_FUNCTION_DECL_P (decl))
5129     /* Set DECL_COMDAT on template instantiations; if we force
5130        them to be emitted by explicit instantiation or -frepo,
5131        mark_needed will tell cgraph to do the right thing.  */
5132     DECL_COMDAT (decl) = true;
5133
5134   return DECL_TEMPLATE_RESULT (tmpl);
5135 }
5136
5137 tree
5138 push_template_decl (tree decl)
5139 {
5140   return push_template_decl_real (decl, false);
5141 }
5142
5143 /* FN is an inheriting constructor that inherits from the constructor
5144    template INHERITED; turn FN into a constructor template with a matching
5145    template header.  */
5146
5147 tree
5148 add_inherited_template_parms (tree fn, tree inherited)
5149 {
5150   tree inner_parms
5151     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5152   inner_parms = copy_node (inner_parms);
5153   tree parms
5154     = tree_cons (size_int (processing_template_decl + 1),
5155                  inner_parms, current_template_parms);
5156   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5157   tree args = template_parms_to_args (parms);
5158   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5159   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5160   DECL_TEMPLATE_RESULT (tmpl) = fn;
5161   DECL_ARTIFICIAL (tmpl) = true;
5162   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5163   return tmpl;
5164 }
5165
5166 /* Called when a class template TYPE is redeclared with the indicated
5167    template PARMS, e.g.:
5168
5169      template <class T> struct S;
5170      template <class T> struct S {};  */
5171
5172 bool
5173 redeclare_class_template (tree type, tree parms)
5174 {
5175   tree tmpl;
5176   tree tmpl_parms;
5177   int i;
5178
5179   if (!TYPE_TEMPLATE_INFO (type))
5180     {
5181       error ("%qT is not a template type", type);
5182       return false;
5183     }
5184
5185   tmpl = TYPE_TI_TEMPLATE (type);
5186   if (!PRIMARY_TEMPLATE_P (tmpl))
5187     /* The type is nested in some template class.  Nothing to worry
5188        about here; there are no new template parameters for the nested
5189        type.  */
5190     return true;
5191
5192   if (!parms)
5193     {
5194       error ("template specifiers not specified in declaration of %qD",
5195              tmpl);
5196       return false;
5197     }
5198
5199   parms = INNERMOST_TEMPLATE_PARMS (parms);
5200   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5201
5202   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5203     {
5204       error_n (input_location, TREE_VEC_LENGTH (parms),
5205                "redeclared with %d template parameter",
5206                "redeclared with %d template parameters",
5207                TREE_VEC_LENGTH (parms));
5208       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5209                 "previous declaration %q+D used %d template parameter",
5210                 "previous declaration %q+D used %d template parameters",
5211                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5212       return false;
5213     }
5214
5215   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5216     {
5217       tree tmpl_parm;
5218       tree parm;
5219       tree tmpl_default;
5220       tree parm_default;
5221
5222       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5223           || TREE_VEC_ELT (parms, i) == error_mark_node)
5224         continue;
5225
5226       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5227       if (error_operand_p (tmpl_parm))
5228         return false;
5229
5230       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5231       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5232       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5233
5234       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5235          TEMPLATE_DECL.  */
5236       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5237           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5238               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5239           || (TREE_CODE (tmpl_parm) != PARM_DECL
5240               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5241                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5242           || (TREE_CODE (tmpl_parm) == PARM_DECL
5243               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5244                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5245         {
5246           error ("template parameter %q+#D", tmpl_parm);
5247           error ("redeclared here as %q#D", parm);
5248           return false;
5249         }
5250
5251       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5252         {
5253           /* We have in [temp.param]:
5254
5255              A template-parameter may not be given default arguments
5256              by two different declarations in the same scope.  */
5257           error_at (input_location, "redefinition of default argument for %q#D", parm);
5258           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5259                   "original definition appeared here");
5260           return false;
5261         }
5262
5263       if (parm_default != NULL_TREE)
5264         /* Update the previous template parameters (which are the ones
5265            that will really count) with the new default value.  */
5266         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5267       else if (tmpl_default != NULL_TREE)
5268         /* Update the new parameters, too; they'll be used as the
5269            parameters for any members.  */
5270         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5271     }
5272
5273     return true;
5274 }
5275
5276 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5277    to be used when the caller has already checked
5278    (processing_template_decl
5279     && !instantiation_dependent_expression_p (expr)
5280     && potential_constant_expression (expr))
5281    and cleared processing_template_decl.  */
5282
5283 tree
5284 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
5285 {
5286   return tsubst_copy_and_build (expr,
5287                                 /*args=*/NULL_TREE,
5288                                 complain,
5289                                 /*in_decl=*/NULL_TREE,
5290                                 /*function_p=*/false,
5291                                 /*integral_constant_expression_p=*/true);
5292 }
5293
5294 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5295    (possibly simplified) expression.  */
5296
5297 tree
5298 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5299 {
5300   if (expr == NULL_TREE)
5301     return NULL_TREE;
5302
5303   /* If we're in a template, but EXPR isn't value dependent, simplify
5304      it.  We're supposed to treat:
5305
5306        template <typename T> void f(T[1 + 1]);
5307        template <typename T> void f(T[2]);
5308
5309      as two declarations of the same function, for example.  */
5310   if (processing_template_decl
5311       && !instantiation_dependent_expression_p (expr)
5312       && potential_constant_expression (expr))
5313     {
5314       processing_template_decl_sentinel s;
5315       expr = instantiate_non_dependent_expr_internal (expr, complain);
5316     }
5317   return expr;
5318 }
5319
5320 tree
5321 instantiate_non_dependent_expr (tree expr)
5322 {
5323   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
5324 }
5325
5326 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5327    template declaration, or a TYPE_DECL for an alias declaration.  */
5328
5329 bool
5330 alias_type_or_template_p (tree t)
5331 {
5332   if (t == NULL_TREE)
5333     return false;
5334   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5335           || (TYPE_P (t)
5336               && TYPE_NAME (t)
5337               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5338           || DECL_ALIAS_TEMPLATE_P (t));
5339 }
5340
5341 /* Return TRUE iff T is a specialization of an alias template.  */
5342
5343 bool
5344 alias_template_specialization_p (const_tree t)
5345 {
5346   /* It's an alias template specialization if it's an alias and its
5347      TYPE_NAME is a specialization of a primary template.  */
5348   if (TYPE_ALIAS_P (t))
5349     {
5350       tree name = TYPE_NAME (t);
5351       if (DECL_LANG_SPECIFIC (name))
5352         if (tree ti = DECL_TEMPLATE_INFO (name))
5353           {
5354             tree tmpl = TI_TEMPLATE (ti);
5355             return PRIMARY_TEMPLATE_P (tmpl);
5356           }
5357     }
5358   return false;
5359 }
5360
5361 /* An alias template is complex from a SFINAE perspective if a template-id
5362    using that alias can be ill-formed when the expansion is not, as with
5363    the void_t template.  We determine this by checking whether the
5364    expansion for the alias template uses all its template parameters.  */
5365
5366 struct uses_all_template_parms_data
5367 {
5368   int level;
5369   bool *seen;
5370 };
5371
5372 static int
5373 uses_all_template_parms_r (tree t, void *data_)
5374 {
5375   struct uses_all_template_parms_data &data
5376     = *(struct uses_all_template_parms_data*)data_;
5377   tree idx = get_template_parm_index (t);
5378
5379   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
5380     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
5381   return 0;
5382 }
5383
5384 static bool
5385 complex_alias_template_p (const_tree tmpl)
5386 {
5387   struct uses_all_template_parms_data data;
5388   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5389   tree parms = DECL_TEMPLATE_PARMS (tmpl);
5390   data.level = TMPL_PARMS_DEPTH (parms);
5391   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
5392   data.seen = XALLOCAVEC (bool, len);
5393   for (int i = 0; i < len; ++i)
5394     data.seen[i] = false;
5395
5396   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
5397   for (int i = 0; i < len; ++i)
5398     if (!data.seen[i])
5399       return true;
5400   return false;
5401 }
5402
5403 /* Return TRUE iff T is a specialization of a complex alias template with
5404    dependent template-arguments.  */
5405
5406 bool
5407 dependent_alias_template_spec_p (const_tree t)
5408 {
5409   return (alias_template_specialization_p (t)
5410           && TEMPLATE_DECL_COMPLEX_ALIAS_P (DECL_TI_TEMPLATE (TYPE_NAME (t)))
5411           && (any_dependent_template_arguments_p
5412               (INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (t)))));
5413 }
5414
5415 /* Return the number of innermost template parameters in TMPL.  */
5416
5417 static int
5418 num_innermost_template_parms (tree tmpl)
5419 {
5420   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
5421   return TREE_VEC_LENGTH (parms);
5422 }
5423
5424 /* Return either TMPL or another template that it is equivalent to under DR
5425    1286: An alias that just changes the name of a template is equivalent to
5426    the other template.  */
5427
5428 static tree
5429 get_underlying_template (tree tmpl)
5430 {
5431   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
5432   while (DECL_ALIAS_TEMPLATE_P (tmpl))
5433     {
5434       tree result = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5435       if (TYPE_TEMPLATE_INFO (result))
5436         {
5437           tree sub = TYPE_TI_TEMPLATE (result);
5438           if (PRIMARY_TEMPLATE_P (sub)
5439               && (num_innermost_template_parms (tmpl)
5440                   == num_innermost_template_parms (sub)))
5441             {
5442               tree alias_args = INNERMOST_TEMPLATE_ARGS
5443                 (template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
5444               if (!comp_template_args (TYPE_TI_ARGS (result), alias_args))
5445                 break;
5446               /* The alias type is equivalent to the pattern of the
5447                  underlying template, so strip the alias.  */
5448               tmpl = sub;
5449               continue;
5450             }
5451         }
5452       break;
5453     }
5454   return tmpl;
5455 }
5456
5457 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5458    must be a function or a pointer-to-function type, as specified
5459    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5460    and check that the resulting function has external linkage.  */
5461
5462 static tree
5463 convert_nontype_argument_function (tree type, tree expr,
5464                                    tsubst_flags_t complain)
5465 {
5466   tree fns = expr;
5467   tree fn, fn_no_ptr;
5468   linkage_kind linkage;
5469
5470   fn = instantiate_type (type, fns, tf_none);
5471   if (fn == error_mark_node)
5472     return error_mark_node;
5473
5474   fn_no_ptr = fn;
5475   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5476     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5477   if (BASELINK_P (fn_no_ptr))
5478     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5479  
5480   /* [temp.arg.nontype]/1
5481
5482      A template-argument for a non-type, non-template template-parameter
5483      shall be one of:
5484      [...]
5485      -- the address of an object or function with external [C++11: or
5486         internal] linkage.  */
5487
5488   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
5489     {
5490       if (complain & tf_error)
5491         {
5492           error ("%qE is not a valid template argument for type %qT",
5493                  expr, type);
5494           if (TYPE_PTR_P (type))
5495             error ("it must be the address of a function with "
5496                    "external linkage");
5497           else
5498             error ("it must be the name of a function with "
5499                    "external linkage");
5500         }
5501       return NULL_TREE;
5502     }
5503
5504   linkage = decl_linkage (fn_no_ptr);
5505   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
5506     {
5507       if (complain & tf_error)
5508         {
5509           if (cxx_dialect >= cxx11)
5510             error ("%qE is not a valid template argument for type %qT "
5511                    "because %qD has no linkage",
5512                    expr, type, fn_no_ptr);
5513           else
5514             error ("%qE is not a valid template argument for type %qT "
5515                    "because %qD does not have external linkage",
5516                    expr, type, fn_no_ptr);
5517         }
5518       return NULL_TREE;
5519     }
5520
5521   return fn;
5522 }
5523
5524 /* Subroutine of convert_nontype_argument.
5525    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5526    Emit an error otherwise.  */
5527
5528 static bool
5529 check_valid_ptrmem_cst_expr (tree type, tree expr,
5530                              tsubst_flags_t complain)
5531 {
5532   STRIP_NOPS (expr);
5533   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5534     return true;
5535   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
5536     return true;
5537   if (processing_template_decl
5538       && TREE_CODE (expr) == ADDR_EXPR
5539       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
5540     return true;
5541   if (complain & tf_error)
5542     {
5543       error ("%qE is not a valid template argument for type %qT",
5544              expr, type);
5545       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5546     }
5547   return false;
5548 }
5549
5550 /* Returns TRUE iff the address of OP is value-dependent.
5551
5552    14.6.2.4 [temp.dep.temp]:
5553    A non-integral non-type template-argument is dependent if its type is
5554    dependent or it has either of the following forms
5555      qualified-id
5556      & qualified-id
5557    and contains a nested-name-specifier which specifies a class-name that
5558    names a dependent type.
5559
5560    We generalize this to just say that the address of a member of a
5561    dependent class is value-dependent; the above doesn't cover the
5562    address of a static data member named with an unqualified-id.  */
5563
5564 static bool
5565 has_value_dependent_address (tree op)
5566 {
5567   /* We could use get_inner_reference here, but there's no need;
5568      this is only relevant for template non-type arguments, which
5569      can only be expressed as &id-expression.  */
5570   if (DECL_P (op))
5571     {
5572       tree ctx = CP_DECL_CONTEXT (op);
5573       if (TYPE_P (ctx) && dependent_type_p (ctx))
5574         return true;
5575     }
5576
5577   return false;
5578 }
5579
5580 /* The next set of functions are used for providing helpful explanatory
5581    diagnostics for failed overload resolution.  Their messages should be
5582    indented by two spaces for consistency with the messages in
5583    call.c  */
5584
5585 static int
5586 unify_success (bool /*explain_p*/)
5587 {
5588   return 0;
5589 }
5590
5591 static int
5592 unify_parameter_deduction_failure (bool explain_p, tree parm)
5593 {
5594   if (explain_p)
5595     inform (input_location,
5596             "  couldn't deduce template parameter %qD", parm);
5597   return 1;
5598 }
5599
5600 static int
5601 unify_invalid (bool /*explain_p*/)
5602 {
5603   return 1;
5604 }
5605
5606 static int
5607 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5608 {
5609   if (explain_p)
5610     inform (input_location,
5611             "  types %qT and %qT have incompatible cv-qualifiers",
5612             parm, arg);
5613   return 1;
5614 }
5615
5616 static int
5617 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5618 {
5619   if (explain_p)
5620     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5621   return 1;
5622 }
5623
5624 static int
5625 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5626 {
5627   if (explain_p)
5628     inform (input_location,
5629             "  template parameter %qD is not a parameter pack, but "
5630             "argument %qD is",
5631             parm, arg);
5632   return 1;
5633 }
5634
5635 static int
5636 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5637 {
5638   if (explain_p)
5639     inform (input_location,
5640             "  template argument %qE does not match "
5641             "pointer-to-member constant %qE",
5642             arg, parm);
5643   return 1;
5644 }
5645
5646 static int
5647 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5648 {
5649   if (explain_p)
5650     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5651   return 1;
5652 }
5653
5654 static int
5655 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5656 {
5657   if (explain_p)
5658     inform (input_location,
5659             "  inconsistent parameter pack deduction with %qT and %qT",
5660             old_arg, new_arg);
5661   return 1;
5662 }
5663
5664 static int
5665 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5666 {
5667   if (explain_p)
5668     {
5669       if (TYPE_P (parm))
5670         inform (input_location,
5671                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
5672                 parm, first, second);
5673       else
5674         inform (input_location,
5675                 "  deduced conflicting values for non-type parameter "
5676                 "%qE (%qE and %qE)", parm, first, second);
5677     }
5678   return 1;
5679 }
5680
5681 static int
5682 unify_vla_arg (bool explain_p, tree arg)
5683 {
5684   if (explain_p)
5685     inform (input_location,
5686             "  variable-sized array type %qT is not "
5687             "a valid template argument",
5688             arg);
5689   return 1;
5690 }
5691
5692 static int
5693 unify_method_type_error (bool explain_p, tree arg)
5694 {
5695   if (explain_p)
5696     inform (input_location,
5697             "  member function type %qT is not a valid template argument",
5698             arg);
5699   return 1;
5700 }
5701
5702 static int
5703 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
5704 {
5705   if (explain_p)
5706     {
5707       if (least_p)
5708         inform_n (input_location, wanted,
5709                   "  candidate expects at least %d argument, %d provided",
5710                   "  candidate expects at least %d arguments, %d provided",
5711                   wanted, have);
5712       else
5713         inform_n (input_location, wanted,
5714                   "  candidate expects %d argument, %d provided",
5715                   "  candidate expects %d arguments, %d provided",
5716                   wanted, have);
5717     }
5718   return 1;
5719 }
5720
5721 static int
5722 unify_too_many_arguments (bool explain_p, int have, int wanted)
5723 {
5724   return unify_arity (explain_p, have, wanted);
5725 }
5726
5727 static int
5728 unify_too_few_arguments (bool explain_p, int have, int wanted,
5729                          bool least_p = false)
5730 {
5731   return unify_arity (explain_p, have, wanted, least_p);
5732 }
5733
5734 static int
5735 unify_arg_conversion (bool explain_p, tree to_type,
5736                       tree from_type, tree arg)
5737 {
5738   if (explain_p)
5739     inform (EXPR_LOC_OR_LOC (arg, input_location),
5740             "  cannot convert %qE (type %qT) to type %qT",
5741             arg, from_type, to_type);
5742   return 1;
5743 }
5744
5745 static int
5746 unify_no_common_base (bool explain_p, enum template_base_result r,
5747                       tree parm, tree arg)
5748 {
5749   if (explain_p)
5750     switch (r)
5751       {
5752       case tbr_ambiguous_baseclass:
5753         inform (input_location, "  %qT is an ambiguous base class of %qT",
5754                 parm, arg);
5755         break;
5756       default:
5757         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5758         break;
5759       }
5760   return 1;
5761 }
5762
5763 static int
5764 unify_inconsistent_template_template_parameters (bool explain_p)
5765 {
5766   if (explain_p)
5767     inform (input_location,
5768             "  template parameters of a template template argument are "
5769             "inconsistent with other deduced template arguments");
5770   return 1;
5771 }
5772
5773 static int
5774 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5775 {
5776   if (explain_p)
5777     inform (input_location,
5778             "  can't deduce a template for %qT from non-template type %qT",
5779             parm, arg);
5780   return 1;
5781 }
5782
5783 static int
5784 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5785 {
5786   if (explain_p)
5787     inform (input_location,
5788             "  template argument %qE does not match %qD", arg, parm);
5789   return 1;
5790 }
5791
5792 static int
5793 unify_overload_resolution_failure (bool explain_p, tree arg)
5794 {
5795   if (explain_p)
5796     inform (input_location,
5797             "  could not resolve address from overloaded function %qE",
5798             arg);
5799   return 1;
5800 }
5801
5802 /* Attempt to convert the non-type template parameter EXPR to the
5803    indicated TYPE.  If the conversion is successful, return the
5804    converted value.  If the conversion is unsuccessful, return
5805    NULL_TREE if we issued an error message, or error_mark_node if we
5806    did not.  We issue error messages for out-and-out bad template
5807    parameters, but not simply because the conversion failed, since we
5808    might be just trying to do argument deduction.  Both TYPE and EXPR
5809    must be non-dependent.
5810
5811    The conversion follows the special rules described in
5812    [temp.arg.nontype], and it is much more strict than an implicit
5813    conversion.
5814
5815    This function is called twice for each template argument (see
5816    lookup_template_class for a more accurate description of this
5817    problem). This means that we need to handle expressions which
5818    are not valid in a C++ source, but can be created from the
5819    first call (for instance, casts to perform conversions). These
5820    hacks can go away after we fix the double coercion problem.  */
5821
5822 static tree
5823 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5824 {
5825   tree expr_type;
5826
5827   /* Detect immediately string literals as invalid non-type argument.
5828      This special-case is not needed for correctness (we would easily
5829      catch this later), but only to provide better diagnostic for this
5830      common user mistake. As suggested by DR 100, we do not mention
5831      linkage issues in the diagnostic as this is not the point.  */
5832   /* FIXME we're making this OK.  */
5833   if (TREE_CODE (expr) == STRING_CST)
5834     {
5835       if (complain & tf_error)
5836         error ("%qE is not a valid template argument for type %qT "
5837                "because string literals can never be used in this context",
5838                expr, type);
5839       return NULL_TREE;
5840     }
5841
5842   /* Add the ADDR_EXPR now for the benefit of
5843      value_dependent_expression_p.  */
5844   if (TYPE_PTROBV_P (type)
5845       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5846     {
5847       expr = decay_conversion (expr, complain);
5848       if (expr == error_mark_node)
5849         return error_mark_node;
5850     }
5851
5852   /* If we are in a template, EXPR may be non-dependent, but still
5853      have a syntactic, rather than semantic, form.  For example, EXPR
5854      might be a SCOPE_REF, rather than the VAR_DECL to which the
5855      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5856      so that access checking can be performed when the template is
5857      instantiated -- but here we need the resolved form so that we can
5858      convert the argument.  */
5859   bool non_dep = false;
5860   if (TYPE_REF_OBJ_P (type)
5861       && has_value_dependent_address (expr))
5862     /* If we want the address and it's value-dependent, don't fold.  */;
5863   else if (!type_unknown_p (expr)
5864            && processing_template_decl
5865            && !instantiation_dependent_expression_p (expr)
5866            && potential_constant_expression (expr))
5867     non_dep = true;
5868   if (error_operand_p (expr))
5869     return error_mark_node;
5870   expr_type = TREE_TYPE (expr);
5871   if (TREE_CODE (type) == REFERENCE_TYPE)
5872     expr = mark_lvalue_use (expr);
5873   else
5874     expr = mark_rvalue_use (expr);
5875
5876   /* If the argument is non-dependent, perform any conversions in
5877      non-dependent context as well.  */
5878   processing_template_decl_sentinel s (non_dep);
5879   if (non_dep)
5880     expr = instantiate_non_dependent_expr_internal (expr, complain);
5881
5882   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5883      to a non-type argument of "nullptr".  */
5884   if (expr == nullptr_node && TYPE_PTR_OR_PTRMEM_P (type))
5885     expr = convert (type, expr);
5886
5887   /* In C++11, integral or enumeration non-type template arguments can be
5888      arbitrary constant expressions.  Pointer and pointer to
5889      member arguments can be general constant expressions that evaluate
5890      to a null value, but otherwise still need to be of a specific form.  */
5891   if (cxx_dialect >= cxx11)
5892     {
5893       if (TREE_CODE (expr) == PTRMEM_CST)
5894         /* A PTRMEM_CST is already constant, and a valid template
5895            argument for a parameter of pointer to member type, we just want
5896            to leave it in that form rather than lower it to a
5897            CONSTRUCTOR.  */;
5898       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5899         expr = maybe_constant_value (expr);
5900       else if (TYPE_PTR_OR_PTRMEM_P (type))
5901         {
5902           tree folded = maybe_constant_value (expr);
5903           if (TYPE_PTR_P (type) ? integer_zerop (folded)
5904               : null_member_pointer_value_p (folded))
5905             expr = folded;
5906         }
5907     }
5908
5909   /* HACK: Due to double coercion, we can get a
5910      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5911      which is the tree that we built on the first call (see
5912      below when coercing to reference to object or to reference to
5913      function). We just strip everything and get to the arg.
5914      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5915      for examples.  */
5916   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5917     {
5918       tree probe_type, probe = expr;
5919       if (REFERENCE_REF_P (probe))
5920         probe = TREE_OPERAND (probe, 0);
5921       probe_type = TREE_TYPE (probe);
5922       if (TREE_CODE (probe) == NOP_EXPR)
5923         {
5924           /* ??? Maybe we could use convert_from_reference here, but we
5925              would need to relax its constraints because the NOP_EXPR
5926              could actually change the type to something more cv-qualified,
5927              and this is not folded by convert_from_reference.  */
5928           tree addr = TREE_OPERAND (probe, 0);
5929           if (TREE_CODE (probe_type) == REFERENCE_TYPE
5930               && TREE_CODE (addr) == ADDR_EXPR
5931               && TYPE_PTR_P (TREE_TYPE (addr))
5932               && (same_type_ignoring_top_level_qualifiers_p
5933                   (TREE_TYPE (probe_type),
5934                    TREE_TYPE (TREE_TYPE (addr)))))
5935             {
5936               expr = TREE_OPERAND (addr, 0);
5937               expr_type = TREE_TYPE (probe_type);
5938             }
5939         }
5940     }
5941
5942   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5943      parameter is a pointer to object, through decay and
5944      qualification conversion. Let's strip everything.  */
5945   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5946     {
5947       tree probe = expr;
5948       STRIP_NOPS (probe);
5949       if (TREE_CODE (probe) == ADDR_EXPR
5950           && TYPE_PTR_P (TREE_TYPE (probe)))
5951         {
5952           /* Skip the ADDR_EXPR only if it is part of the decay for
5953              an array. Otherwise, it is part of the original argument
5954              in the source code.  */
5955           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (probe, 0))) == ARRAY_TYPE)
5956             probe = TREE_OPERAND (probe, 0);
5957           expr = probe;
5958           expr_type = TREE_TYPE (expr);
5959         }
5960     }
5961
5962   /* [temp.arg.nontype]/5, bullet 1
5963
5964      For a non-type template-parameter of integral or enumeration type,
5965      integral promotions (_conv.prom_) and integral conversions
5966      (_conv.integral_) are applied.  */
5967   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5968     {
5969       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5970       t = maybe_constant_value (t);
5971       if (t != error_mark_node)
5972         expr = t;
5973
5974       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5975         return error_mark_node;
5976
5977       /* Notice that there are constant expressions like '4 % 0' which
5978          do not fold into integer constants.  */
5979       if (TREE_CODE (expr) != INTEGER_CST)
5980         {
5981           if (complain & tf_error)
5982             {
5983               int errs = errorcount, warns = warningcount + werrorcount;
5984               if (processing_template_decl
5985                   && !require_potential_constant_expression (expr))
5986                 return NULL_TREE;
5987               expr = cxx_constant_value (expr);
5988               if (errorcount > errs || warningcount + werrorcount > warns)
5989                 inform (EXPR_LOC_OR_LOC (expr, input_location),
5990                         "in template argument for type %qT ", type);
5991               if (expr == error_mark_node)
5992                 return NULL_TREE;
5993               /* else cxx_constant_value complained but gave us
5994                  a real constant, so go ahead.  */
5995               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5996             }
5997           else
5998             return NULL_TREE;
5999         }
6000
6001       /* Avoid typedef problems.  */
6002       if (TREE_TYPE (expr) != type)
6003         expr = fold_convert (type, expr);
6004     }
6005   /* [temp.arg.nontype]/5, bullet 2
6006
6007      For a non-type template-parameter of type pointer to object,
6008      qualification conversions (_conv.qual_) and the array-to-pointer
6009      conversion (_conv.array_) are applied.  */
6010   else if (TYPE_PTROBV_P (type))
6011     {
6012       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6013
6014          A template-argument for a non-type, non-template template-parameter
6015          shall be one of: [...]
6016
6017          -- the name of a non-type template-parameter;
6018          -- the address of an object or function with external linkage, [...]
6019             expressed as "& id-expression" where the & is optional if the name
6020             refers to a function or array, or if the corresponding
6021             template-parameter is a reference.
6022
6023         Here, we do not care about functions, as they are invalid anyway
6024         for a parameter of type pointer-to-object.  */
6025
6026       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
6027         /* Non-type template parameters are OK.  */
6028         ;
6029       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6030         /* Null pointer values are OK in C++11.  */;
6031       else if (TREE_CODE (expr) != ADDR_EXPR
6032                && TREE_CODE (expr_type) != ARRAY_TYPE)
6033         {
6034           if (VAR_P (expr))
6035             {
6036               if (complain & tf_error)
6037                 error ("%qD is not a valid template argument "
6038                        "because %qD is a variable, not the address of "
6039                        "a variable", expr, expr);
6040               return NULL_TREE;
6041             }
6042           if (POINTER_TYPE_P (expr_type))
6043             {
6044               if (complain & tf_error)
6045                 error ("%qE is not a valid template argument for %qT "
6046                        "because it is not the address of a variable",
6047                        expr, type);
6048               return NULL_TREE;
6049             }
6050           /* Other values, like integer constants, might be valid
6051              non-type arguments of some other type.  */
6052           return error_mark_node;
6053         }
6054       else
6055         {
6056           tree decl;
6057
6058           decl = ((TREE_CODE (expr) == ADDR_EXPR)
6059                   ? TREE_OPERAND (expr, 0) : expr);
6060           if (!VAR_P (decl))
6061             {
6062               if (complain & tf_error)
6063                 error ("%qE is not a valid template argument of type %qT "
6064                        "because %qE is not a variable", expr, type, decl);
6065               return NULL_TREE;
6066             }
6067           else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6068             {
6069               if (complain & tf_error)
6070                 error ("%qE is not a valid template argument of type %qT "
6071                        "because %qD does not have external linkage",
6072                        expr, type, decl);
6073               return NULL_TREE;
6074             }
6075           else if (cxx_dialect >= cxx11 && decl_linkage (decl) == lk_none)
6076             {
6077               if (complain & tf_error)
6078                 error ("%qE is not a valid template argument of type %qT "
6079                        "because %qD has no linkage", expr, type, decl);
6080               return NULL_TREE;
6081             }
6082         }
6083
6084       expr = decay_conversion (expr, complain);
6085       if (expr == error_mark_node)
6086         return error_mark_node;
6087
6088       expr = perform_qualification_conversions (type, expr);
6089       if (expr == error_mark_node)
6090         return error_mark_node;
6091     }
6092   /* [temp.arg.nontype]/5, bullet 3
6093
6094      For a non-type template-parameter of type reference to object, no
6095      conversions apply. The type referred to by the reference may be more
6096      cv-qualified than the (otherwise identical) type of the
6097      template-argument. The template-parameter is bound directly to the
6098      template-argument, which must be an lvalue.  */
6099   else if (TYPE_REF_OBJ_P (type))
6100     {
6101       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6102                                                       expr_type))
6103         return error_mark_node;
6104
6105       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6106         {
6107           if (complain & tf_error)
6108             error ("%qE is not a valid template argument for type %qT "
6109                    "because of conflicts in cv-qualification", expr, type);
6110           return NULL_TREE;
6111         }
6112
6113       if (!real_lvalue_p (expr))
6114         {
6115           if (complain & tf_error)
6116             error ("%qE is not a valid template argument for type %qT "
6117                    "because it is not an lvalue", expr, type);
6118           return NULL_TREE;
6119         }
6120
6121       /* [temp.arg.nontype]/1
6122
6123          A template-argument for a non-type, non-template template-parameter
6124          shall be one of: [...]
6125
6126          -- the address of an object or function with external linkage.  */
6127       if (INDIRECT_REF_P (expr)
6128           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6129         {
6130           expr = TREE_OPERAND (expr, 0);
6131           if (DECL_P (expr))
6132             {
6133               if (complain & tf_error)
6134                 error ("%q#D is not a valid template argument for type %qT "
6135                        "because a reference variable does not have a constant "
6136                        "address", expr, type);
6137               return NULL_TREE;
6138             }
6139         }
6140
6141       if (!DECL_P (expr))
6142         {
6143           if (complain & tf_error)
6144             error ("%qE is not a valid template argument for type %qT "
6145                    "because it is not an object with external linkage",
6146                    expr, type);
6147           return NULL_TREE;
6148         }
6149
6150       if (!DECL_EXTERNAL_LINKAGE_P (expr))
6151         {
6152           if (complain & tf_error)
6153             error ("%qE is not a valid template argument for type %qT "
6154                    "because object %qD has not external linkage",
6155                    expr, type, expr);
6156           return NULL_TREE;
6157         }
6158
6159       expr = build_nop (type, build_address (expr));
6160     }
6161   /* [temp.arg.nontype]/5, bullet 4
6162
6163      For a non-type template-parameter of type pointer to function, only
6164      the function-to-pointer conversion (_conv.func_) is applied. If the
6165      template-argument represents a set of overloaded functions (or a
6166      pointer to such), the matching function is selected from the set
6167      (_over.over_).  */
6168   else if (TYPE_PTRFN_P (type))
6169     {
6170       /* If the argument is a template-id, we might not have enough
6171          context information to decay the pointer.  */
6172       if (!type_unknown_p (expr_type))
6173         {
6174           expr = decay_conversion (expr, complain);
6175           if (expr == error_mark_node)
6176             return error_mark_node;
6177         }
6178
6179       if (cxx_dialect >= cxx11 && integer_zerop (expr))
6180         /* Null pointer values are OK in C++11.  */
6181         return perform_qualification_conversions (type, expr);
6182
6183       expr = convert_nontype_argument_function (type, expr, complain);
6184       if (!expr || expr == error_mark_node)
6185         return expr;
6186     }
6187   /* [temp.arg.nontype]/5, bullet 5
6188
6189      For a non-type template-parameter of type reference to function, no
6190      conversions apply. If the template-argument represents a set of
6191      overloaded functions, the matching function is selected from the set
6192      (_over.over_).  */
6193   else if (TYPE_REFFN_P (type))
6194     {
6195       if (TREE_CODE (expr) == ADDR_EXPR)
6196         {
6197           if (complain & tf_error)
6198             {
6199               error ("%qE is not a valid template argument for type %qT "
6200                      "because it is a pointer", expr, type);
6201               inform (input_location, "try using %qE instead",
6202                       TREE_OPERAND (expr, 0));
6203             }
6204           return NULL_TREE;
6205         }
6206
6207       expr = convert_nontype_argument_function (type, expr, complain);
6208       if (!expr || expr == error_mark_node)
6209         return expr;
6210
6211       expr = build_nop (type, build_address (expr));
6212     }
6213   /* [temp.arg.nontype]/5, bullet 6
6214
6215      For a non-type template-parameter of type pointer to member function,
6216      no conversions apply. If the template-argument represents a set of
6217      overloaded member functions, the matching member function is selected
6218      from the set (_over.over_).  */
6219   else if (TYPE_PTRMEMFUNC_P (type))
6220     {
6221       expr = instantiate_type (type, expr, tf_none);
6222       if (expr == error_mark_node)
6223         return error_mark_node;
6224
6225       /* [temp.arg.nontype] bullet 1 says the pointer to member
6226          expression must be a pointer-to-member constant.  */
6227       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6228         return error_mark_node;
6229
6230       /* There is no way to disable standard conversions in
6231          resolve_address_of_overloaded_function (called by
6232          instantiate_type). It is possible that the call succeeded by
6233          converting &B::I to &D::I (where B is a base of D), so we need
6234          to reject this conversion here.
6235
6236          Actually, even if there was a way to disable standard conversions,
6237          it would still be better to reject them here so that we can
6238          provide a superior diagnostic.  */
6239       if (!same_type_p (TREE_TYPE (expr), type))
6240         {
6241           if (complain & tf_error)
6242             {
6243               error ("%qE is not a valid template argument for type %qT "
6244                      "because it is of type %qT", expr, type,
6245                      TREE_TYPE (expr));
6246               /* If we are just one standard conversion off, explain.  */
6247               if (can_convert_standard (type, TREE_TYPE (expr), complain))
6248                 inform (input_location,
6249                         "standard conversions are not allowed in this context");
6250             }
6251           return NULL_TREE;
6252         }
6253     }
6254   /* [temp.arg.nontype]/5, bullet 7
6255
6256      For a non-type template-parameter of type pointer to data member,
6257      qualification conversions (_conv.qual_) are applied.  */
6258   else if (TYPE_PTRDATAMEM_P (type))
6259     {
6260       /* [temp.arg.nontype] bullet 1 says the pointer to member
6261          expression must be a pointer-to-member constant.  */
6262       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6263         return error_mark_node;
6264
6265       expr = perform_qualification_conversions (type, expr);
6266       if (expr == error_mark_node)
6267         return expr;
6268     }
6269   else if (NULLPTR_TYPE_P (type))
6270     {
6271       if (expr != nullptr_node)
6272         {
6273           if (complain & tf_error)
6274             error ("%qE is not a valid template argument for type %qT "
6275                    "because it is of type %qT", expr, type, TREE_TYPE (expr));
6276           return NULL_TREE;
6277         }
6278       return expr;
6279     }
6280   /* A template non-type parameter must be one of the above.  */
6281   else
6282     gcc_unreachable ();
6283
6284   /* Sanity check: did we actually convert the argument to the
6285      right type?  */
6286   gcc_assert (same_type_ignoring_top_level_qualifiers_p
6287               (type, TREE_TYPE (expr)));
6288   return convert_from_reference (expr);
6289 }
6290
6291 /* Subroutine of coerce_template_template_parms, which returns 1 if
6292    PARM_PARM and ARG_PARM match using the rule for the template
6293    parameters of template template parameters. Both PARM and ARG are
6294    template parameters; the rest of the arguments are the same as for
6295    coerce_template_template_parms.
6296  */
6297 static int
6298 coerce_template_template_parm (tree parm,
6299                               tree arg,
6300                               tsubst_flags_t complain,
6301                               tree in_decl,
6302                               tree outer_args)
6303 {
6304   if (arg == NULL_TREE || error_operand_p (arg)
6305       || parm == NULL_TREE || error_operand_p (parm))
6306     return 0;
6307   
6308   if (TREE_CODE (arg) != TREE_CODE (parm))
6309     return 0;
6310   
6311   switch (TREE_CODE (parm))
6312     {
6313     case TEMPLATE_DECL:
6314       /* We encounter instantiations of templates like
6315          template <template <template <class> class> class TT>
6316          class C;  */
6317       {
6318         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6319         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6320         
6321         if (!coerce_template_template_parms
6322             (parmparm, argparm, complain, in_decl, outer_args))
6323           return 0;
6324       }
6325       /* Fall through.  */
6326       
6327     case TYPE_DECL:
6328       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6329           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6330         /* Argument is a parameter pack but parameter is not.  */
6331         return 0;
6332       break;
6333       
6334     case PARM_DECL:
6335       /* The tsubst call is used to handle cases such as
6336          
6337            template <int> class C {};
6338            template <class T, template <T> class TT> class D {};
6339            D<int, C> d;
6340
6341          i.e. the parameter list of TT depends on earlier parameters.  */
6342       if (!uses_template_parms (TREE_TYPE (arg))
6343           && !same_type_p
6344                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6345                  TREE_TYPE (arg)))
6346         return 0;
6347       
6348       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6349           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6350         /* Argument is a parameter pack but parameter is not.  */
6351         return 0;
6352       
6353       break;
6354
6355     default:
6356       gcc_unreachable ();
6357     }
6358
6359   return 1;
6360 }
6361
6362
6363 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6364    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6365    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6366    or PARM_DECL.
6367
6368    Consider the example:
6369      template <class T> class A;
6370      template<template <class U> class TT> class B;
6371
6372    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6373    the parameters to A, and OUTER_ARGS contains A.  */
6374
6375 static int
6376 coerce_template_template_parms (tree parm_parms,
6377                                 tree arg_parms,
6378                                 tsubst_flags_t complain,
6379                                 tree in_decl,
6380                                 tree outer_args)
6381 {
6382   int nparms, nargs, i;
6383   tree parm, arg;
6384   int variadic_p = 0;
6385
6386   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6387   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6388
6389   nparms = TREE_VEC_LENGTH (parm_parms);
6390   nargs = TREE_VEC_LENGTH (arg_parms);
6391
6392   /* Determine whether we have a parameter pack at the end of the
6393      template template parameter's template parameter list.  */
6394   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6395     {
6396       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6397       
6398       if (error_operand_p (parm))
6399         return 0;
6400
6401       switch (TREE_CODE (parm))
6402         {
6403         case TEMPLATE_DECL:
6404         case TYPE_DECL:
6405           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6406             variadic_p = 1;
6407           break;
6408           
6409         case PARM_DECL:
6410           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6411             variadic_p = 1;
6412           break;
6413           
6414         default:
6415           gcc_unreachable ();
6416         }
6417     }
6418  
6419   if (nargs != nparms
6420       && !(variadic_p && nargs >= nparms - 1))
6421     return 0;
6422
6423   /* Check all of the template parameters except the parameter pack at
6424      the end (if any).  */
6425   for (i = 0; i < nparms - variadic_p; ++i)
6426     {
6427       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6428           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6429         continue;
6430
6431       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6432       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6433
6434       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6435                                           outer_args))
6436         return 0;
6437
6438     }
6439
6440   if (variadic_p)
6441     {
6442       /* Check each of the template parameters in the template
6443          argument against the template parameter pack at the end of
6444          the template template parameter.  */
6445       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6446         return 0;
6447
6448       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6449
6450       for (; i < nargs; ++i)
6451         {
6452           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6453             continue;
6454  
6455           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6456  
6457           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6458                                               outer_args))
6459             return 0;
6460         }
6461     }
6462
6463   return 1;
6464 }
6465
6466 /* Verifies that the deduced template arguments (in TARGS) for the
6467    template template parameters (in TPARMS) represent valid bindings,
6468    by comparing the template parameter list of each template argument
6469    to the template parameter list of its corresponding template
6470    template parameter, in accordance with DR150. This
6471    routine can only be called after all template arguments have been
6472    deduced. It will return TRUE if all of the template template
6473    parameter bindings are okay, FALSE otherwise.  */
6474 bool 
6475 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6476 {
6477   int i, ntparms = TREE_VEC_LENGTH (tparms);
6478   bool ret = true;
6479
6480   /* We're dealing with template parms in this process.  */
6481   ++processing_template_decl;
6482
6483   targs = INNERMOST_TEMPLATE_ARGS (targs);
6484
6485   for (i = 0; i < ntparms; ++i)
6486     {
6487       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6488       tree targ = TREE_VEC_ELT (targs, i);
6489
6490       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6491         {
6492           tree packed_args = NULL_TREE;
6493           int idx, len = 1;
6494
6495           if (ARGUMENT_PACK_P (targ))
6496             {
6497               /* Look inside the argument pack.  */
6498               packed_args = ARGUMENT_PACK_ARGS (targ);
6499               len = TREE_VEC_LENGTH (packed_args);
6500             }
6501
6502           for (idx = 0; idx < len; ++idx)
6503             {
6504               tree targ_parms = NULL_TREE;
6505
6506               if (packed_args)
6507                 /* Extract the next argument from the argument
6508                    pack.  */
6509                 targ = TREE_VEC_ELT (packed_args, idx);
6510
6511               if (PACK_EXPANSION_P (targ))
6512                 /* Look at the pattern of the pack expansion.  */
6513                 targ = PACK_EXPANSION_PATTERN (targ);
6514
6515               /* Extract the template parameters from the template
6516                  argument.  */
6517               if (TREE_CODE (targ) == TEMPLATE_DECL)
6518                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6519               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6520                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6521
6522               /* Verify that we can coerce the template template
6523                  parameters from the template argument to the template
6524                  parameter.  This requires an exact match.  */
6525               if (targ_parms
6526                   && !coerce_template_template_parms
6527                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6528                         targ_parms,
6529                         tf_none,
6530                         tparm,
6531                         targs))
6532                 {
6533                   ret = false;
6534                   goto out;
6535                 }
6536             }
6537         }
6538     }
6539
6540  out:
6541
6542   --processing_template_decl;
6543   return ret;
6544 }
6545
6546 /* Since type attributes aren't mangled, we need to strip them from
6547    template type arguments.  */
6548
6549 static tree
6550 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6551 {
6552   tree mv;
6553   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6554     return arg;
6555   mv = TYPE_MAIN_VARIANT (arg);
6556   arg = strip_typedefs (arg);
6557   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6558       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6559     {
6560       if (complain & tf_warning)
6561         warning (0, "ignoring attributes on template argument %qT", arg);
6562       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6563       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6564     }
6565   return arg;
6566 }
6567
6568 /* Convert the indicated template ARG as necessary to match the
6569    indicated template PARM.  Returns the converted ARG, or
6570    error_mark_node if the conversion was unsuccessful.  Error and
6571    warning messages are issued under control of COMPLAIN.  This
6572    conversion is for the Ith parameter in the parameter list.  ARGS is
6573    the full set of template arguments deduced so far.  */
6574
6575 static tree
6576 convert_template_argument (tree parm,
6577                            tree arg,
6578                            tree args,
6579                            tsubst_flags_t complain,
6580                            int i,
6581                            tree in_decl)
6582 {
6583   tree orig_arg;
6584   tree val;
6585   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6586
6587   if (parm == error_mark_node)
6588     return error_mark_node;
6589
6590   if (TREE_CODE (arg) == TREE_LIST
6591       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6592     {
6593       /* The template argument was the name of some
6594          member function.  That's usually
6595          invalid, but static members are OK.  In any
6596          case, grab the underlying fields/functions
6597          and issue an error later if required.  */
6598       orig_arg = TREE_VALUE (arg);
6599       TREE_TYPE (arg) = unknown_type_node;
6600     }
6601
6602   orig_arg = arg;
6603
6604   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6605   requires_type = (TREE_CODE (parm) == TYPE_DECL
6606                    || requires_tmpl_type);
6607
6608   /* When determining whether an argument pack expansion is a template,
6609      look at the pattern.  */
6610   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6611     arg = PACK_EXPANSION_PATTERN (arg);
6612
6613   /* Deal with an injected-class-name used as a template template arg.  */
6614   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6615     {
6616       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6617       if (TREE_CODE (t) == TEMPLATE_DECL)
6618         {
6619           if (cxx_dialect >= cxx11)
6620             /* OK under DR 1004.  */;
6621           else if (complain & tf_warning_or_error)
6622             pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
6623                      " used as template template argument", TYPE_NAME (arg));
6624           else if (flag_pedantic_errors)
6625             t = arg;
6626
6627           arg = t;
6628         }
6629     }
6630
6631   is_tmpl_type = 
6632     ((TREE_CODE (arg) == TEMPLATE_DECL
6633       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6634      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
6635      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6636      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6637
6638   if (is_tmpl_type
6639       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6640           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6641     arg = TYPE_STUB_DECL (arg);
6642
6643   is_type = TYPE_P (arg) || is_tmpl_type;
6644
6645   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6646       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6647     {
6648       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
6649         {
6650           if (complain & tf_error)
6651             error ("invalid use of destructor %qE as a type", orig_arg);
6652           return error_mark_node;
6653         }
6654
6655       permerror (input_location,
6656                  "to refer to a type member of a template parameter, "
6657                  "use %<typename %E%>", orig_arg);
6658
6659       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6660                                      TREE_OPERAND (arg, 1),
6661                                      typename_type,
6662                                      complain);
6663       arg = orig_arg;
6664       is_type = 1;
6665     }
6666   if (is_type != requires_type)
6667     {
6668       if (in_decl)
6669         {
6670           if (complain & tf_error)
6671             {
6672               error ("type/value mismatch at argument %d in template "
6673                      "parameter list for %qD",
6674                      i + 1, in_decl);
6675               if (is_type)
6676                 inform (input_location,
6677                         "  expected a constant of type %qT, got %qT",
6678                         TREE_TYPE (parm),
6679                         (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6680               else if (requires_tmpl_type)
6681                 inform (input_location,
6682                         "  expected a class template, got %qE", orig_arg);
6683               else
6684                 inform (input_location,
6685                         "  expected a type, got %qE", orig_arg);
6686             }
6687         }
6688       return error_mark_node;
6689     }
6690   if (is_tmpl_type ^ requires_tmpl_type)
6691     {
6692       if (in_decl && (complain & tf_error))
6693         {
6694           error ("type/value mismatch at argument %d in template "
6695                  "parameter list for %qD",
6696                  i + 1, in_decl);
6697           if (is_tmpl_type)
6698             inform (input_location,
6699                     "  expected a type, got %qT", DECL_NAME (arg));
6700           else
6701             inform (input_location,
6702                     "  expected a class template, got %qT", orig_arg);
6703         }
6704       return error_mark_node;
6705     }
6706
6707   if (is_type)
6708     {
6709       if (requires_tmpl_type)
6710         {
6711           if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6712             val = orig_arg;
6713           else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6714             /* The number of argument required is not known yet.
6715                Just accept it for now.  */
6716             val = TREE_TYPE (arg);
6717           else
6718             {
6719               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6720               tree argparm;
6721
6722               /* Strip alias templates that are equivalent to another
6723                  template.  */
6724               arg = get_underlying_template (arg);
6725               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6726
6727               if (coerce_template_template_parms (parmparm, argparm,
6728                                                   complain, in_decl,
6729                                                   args))
6730                 {
6731                   val = arg;
6732
6733                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6734                      TEMPLATE_DECL.  */
6735                   if (val != error_mark_node)
6736                     {
6737                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6738                         val = TREE_TYPE (val);
6739                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6740                         val = make_pack_expansion (val);
6741                     }
6742                 }
6743               else
6744                 {
6745                   if (in_decl && (complain & tf_error))
6746                     {
6747                       error ("type/value mismatch at argument %d in "
6748                              "template parameter list for %qD",
6749                              i + 1, in_decl);
6750                       inform (input_location,
6751                               "  expected a template of type %qD, got %qT",
6752                               parm, orig_arg);
6753                     }
6754
6755                   val = error_mark_node;
6756                 }
6757             }
6758         }
6759       else
6760         val = orig_arg;
6761       /* We only form one instance of each template specialization.
6762          Therefore, if we use a non-canonical variant (i.e., a
6763          typedef), any future messages referring to the type will use
6764          the typedef, which is confusing if those future uses do not
6765          themselves also use the typedef.  */
6766       if (TYPE_P (val))
6767         val = canonicalize_type_argument (val, complain);
6768     }
6769   else
6770     {
6771       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6772
6773       if (invalid_nontype_parm_type_p (t, complain))
6774         return error_mark_node;
6775
6776       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6777         {
6778           if (same_type_p (t, TREE_TYPE (orig_arg)))
6779             val = orig_arg;
6780           else
6781             {
6782               /* Not sure if this is reachable, but it doesn't hurt
6783                  to be robust.  */
6784               error ("type mismatch in nontype parameter pack");
6785               val = error_mark_node;
6786             }
6787         }
6788       else if (!dependent_template_arg_p (orig_arg)
6789                && !uses_template_parms (t))
6790         /* We used to call digest_init here.  However, digest_init
6791            will report errors, which we don't want when complain
6792            is zero.  More importantly, digest_init will try too
6793            hard to convert things: for example, `0' should not be
6794            converted to pointer type at this point according to
6795            the standard.  Accepting this is not merely an
6796            extension, since deciding whether or not these
6797            conversions can occur is part of determining which
6798            function template to call, or whether a given explicit
6799            argument specification is valid.  */
6800         val = convert_nontype_argument (t, orig_arg, complain);
6801       else
6802         val = strip_typedefs_expr (orig_arg);
6803
6804       if (val == NULL_TREE)
6805         val = error_mark_node;
6806       else if (val == error_mark_node && (complain & tf_error))
6807         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6808
6809       if (TREE_CODE (val) == SCOPE_REF)
6810         {
6811           /* Strip typedefs from the SCOPE_REF.  */
6812           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6813           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6814                                                    complain);
6815           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6816                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6817         }
6818     }
6819
6820   return val;
6821 }
6822
6823 /* Coerces the remaining template arguments in INNER_ARGS (from
6824    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6825    Returns the coerced argument pack. PARM_IDX is the position of this
6826    parameter in the template parameter list. ARGS is the original
6827    template argument list.  */
6828 static tree
6829 coerce_template_parameter_pack (tree parms,
6830                                 int parm_idx,
6831                                 tree args,
6832                                 tree inner_args,
6833                                 int arg_idx,
6834                                 tree new_args,
6835                                 int* lost,
6836                                 tree in_decl,
6837                                 tsubst_flags_t complain)
6838 {
6839   tree parm = TREE_VEC_ELT (parms, parm_idx);
6840   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6841   tree packed_args;
6842   tree argument_pack;
6843   tree packed_parms = NULL_TREE;
6844
6845   if (arg_idx > nargs)
6846     arg_idx = nargs;
6847
6848   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
6849     {
6850       /* When the template parameter is a non-type template parameter pack
6851          or template template parameter pack whose type or template
6852          parameters use parameter packs, we know exactly how many arguments
6853          we are looking for.  Build a vector of the instantiated decls for
6854          these template parameters in PACKED_PARMS.  */
6855       /* We can't use make_pack_expansion here because it would interpret a
6856          _DECL as a use rather than a declaration.  */
6857       tree decl = TREE_VALUE (parm);
6858       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
6859       SET_PACK_EXPANSION_PATTERN (exp, decl);
6860       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
6861       SET_TYPE_STRUCTURAL_EQUALITY (exp);
6862
6863       TREE_VEC_LENGTH (args)--;
6864       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
6865       TREE_VEC_LENGTH (args)++;
6866
6867       if (packed_parms == error_mark_node)
6868         return error_mark_node;
6869
6870       /* If we're doing a partial instantiation of a member template,
6871          verify that all of the types used for the non-type
6872          template parameter pack are, in fact, valid for non-type
6873          template parameters.  */
6874       if (arg_idx < nargs
6875           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6876         {
6877           int j, len = TREE_VEC_LENGTH (packed_parms);
6878           for (j = 0; j < len; ++j)
6879             {
6880               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
6881               if (invalid_nontype_parm_type_p (t, complain))
6882                 return error_mark_node;
6883             }
6884           /* We don't know how many args we have yet, just
6885              use the unconverted ones for now.  */
6886           return NULL_TREE;
6887         }
6888
6889       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
6890     }
6891   else
6892     packed_args = make_tree_vec (nargs - arg_idx);
6893
6894   /* Convert the remaining arguments, which will be a part of the
6895      parameter pack "parm".  */
6896   for (; arg_idx < nargs; ++arg_idx)
6897     {
6898       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6899       tree actual_parm = TREE_VALUE (parm);
6900       int pack_idx = arg_idx - parm_idx;
6901
6902       if (packed_parms)
6903         {
6904           /* Once we've packed as many args as we have types, stop.  */
6905           if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
6906             break;
6907           else if (PACK_EXPANSION_P (arg))
6908             /* We don't know how many args we have yet, just
6909                use the unconverted ones for now.  */
6910             return NULL_TREE;
6911           else
6912             actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
6913         }
6914
6915       if (arg == error_mark_node)
6916         {
6917           if (complain & tf_error)
6918             error ("template argument %d is invalid", arg_idx + 1);
6919         }
6920       else
6921         arg = convert_template_argument (actual_parm, 
6922                                          arg, new_args, complain, parm_idx,
6923                                          in_decl);
6924       if (arg == error_mark_node)
6925         (*lost)++;
6926       TREE_VEC_ELT (packed_args, pack_idx) = arg;
6927     }
6928
6929   if (arg_idx - parm_idx < TREE_VEC_LENGTH (packed_args)
6930       && TREE_VEC_LENGTH (packed_args) > 0)
6931     {
6932       if (complain & tf_error)
6933         error ("wrong number of template arguments (%d, should be %d)",
6934                arg_idx - parm_idx, TREE_VEC_LENGTH (packed_args));
6935       return error_mark_node;
6936     }
6937
6938   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6939       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6940     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6941   else
6942     {
6943       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6944       TREE_TYPE (argument_pack) 
6945         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6946       TREE_CONSTANT (argument_pack) = 1;
6947     }
6948
6949   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6950 #ifdef ENABLE_CHECKING
6951   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6952                                        TREE_VEC_LENGTH (packed_args));
6953 #endif
6954   return argument_pack;
6955 }
6956
6957 /* Returns the number of pack expansions in the template argument vector
6958    ARGS.  */
6959
6960 static int
6961 pack_expansion_args_count (tree args)
6962 {
6963   int i;
6964   int count = 0;
6965   if (args)
6966     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
6967       {
6968         tree elt = TREE_VEC_ELT (args, i);
6969         if (elt && PACK_EXPANSION_P (elt))
6970           ++count;
6971       }
6972   return count;
6973 }
6974
6975 /* Convert all template arguments to their appropriate types, and
6976    return a vector containing the innermost resulting template
6977    arguments.  If any error occurs, return error_mark_node. Error and
6978    warning messages are issued under control of COMPLAIN.
6979
6980    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6981    for arguments not specified in ARGS.  Otherwise, if
6982    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6983    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6984    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6985    ARGS.  */
6986
6987 static tree
6988 coerce_template_parms (tree parms,
6989                        tree args,
6990                        tree in_decl,
6991                        tsubst_flags_t complain,
6992                        bool require_all_args,
6993                        bool use_default_args)
6994 {
6995   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6996   tree orig_inner_args;
6997   tree inner_args;
6998   tree new_args;
6999   tree new_inner_args;
7000   int saved_unevaluated_operand;
7001   int saved_inhibit_evaluation_warnings;
7002
7003   /* When used as a boolean value, indicates whether this is a
7004      variadic template parameter list. Since it's an int, we can also
7005      subtract it from nparms to get the number of non-variadic
7006      parameters.  */
7007   int variadic_p = 0;
7008   int variadic_args_p = 0;
7009   int post_variadic_parms = 0;
7010
7011   /* Likewise for parameters with default arguments.  */
7012   int default_p = 0;
7013
7014   if (args == error_mark_node)
7015     return error_mark_node;
7016
7017   nparms = TREE_VEC_LENGTH (parms);
7018
7019   /* Determine if there are any parameter packs or default arguments.  */
7020   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
7021     {
7022       tree parm = TREE_VEC_ELT (parms, parm_idx);
7023       if (variadic_p)
7024         ++post_variadic_parms;
7025       if (template_parameter_pack_p (TREE_VALUE (parm)))
7026         ++variadic_p;
7027       if (TREE_PURPOSE (parm))
7028         ++default_p;
7029     }
7030
7031   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
7032   /* If there are no parameters that follow a parameter pack, we need to
7033      expand any argument packs so that we can deduce a parameter pack from
7034      some non-packed args followed by an argument pack, as in variadic85.C.
7035      If there are such parameters, we need to leave argument packs intact
7036      so the arguments are assigned properly.  This can happen when dealing
7037      with a nested class inside a partial specialization of a class
7038      template, as in variadic92.C, or when deducing a template parameter pack
7039      from a sub-declarator, as in variadic114.C.  */
7040   if (!post_variadic_parms)
7041     inner_args = expand_template_argument_pack (inner_args);
7042
7043   /* Count any pack expansion args.  */
7044   variadic_args_p = pack_expansion_args_count (inner_args);
7045
7046   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
7047   if ((nargs > nparms && !variadic_p)
7048       || (nargs < nparms - variadic_p
7049           && require_all_args
7050           && !variadic_args_p
7051           && (!use_default_args
7052               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
7053                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
7054     {
7055       if (complain & tf_error)
7056         {
7057           if (variadic_p || default_p)
7058             {
7059               nparms -= variadic_p + default_p;
7060               error ("wrong number of template arguments "
7061                      "(%d, should be at least %d)", nargs, nparms);
7062             }
7063           else
7064              error ("wrong number of template arguments "
7065                     "(%d, should be %d)", nargs, nparms);
7066
7067           if (in_decl)
7068             inform (input_location, "provided for %q+D", in_decl);
7069         }
7070
7071       return error_mark_node;
7072     }
7073   /* We can't pass a pack expansion to a non-pack parameter of an alias
7074      template (DR 1430).  */
7075   else if (in_decl && DECL_ALIAS_TEMPLATE_P (in_decl)
7076            && variadic_args_p
7077            && nargs - variadic_args_p < nparms - variadic_p)
7078     {
7079       if (complain & tf_error)
7080         {
7081           for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
7082             {
7083               tree arg = TREE_VEC_ELT (inner_args, i);
7084               tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
7085
7086               if (PACK_EXPANSION_P (arg)
7087                   && !template_parameter_pack_p (parm))
7088                 {
7089                   error ("pack expansion argument for non-pack parameter "
7090                          "%qD of alias template %qD", parm, in_decl);
7091                   inform (DECL_SOURCE_LOCATION (parm), "declared here");
7092                   goto found;
7093                 }
7094             }
7095           gcc_unreachable ();
7096         found:;
7097         }
7098       return error_mark_node;
7099     }
7100
7101   /* We need to evaluate the template arguments, even though this
7102      template-id may be nested within a "sizeof".  */
7103   saved_unevaluated_operand = cp_unevaluated_operand;
7104   cp_unevaluated_operand = 0;
7105   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
7106   c_inhibit_evaluation_warnings = 0;
7107   new_inner_args = make_tree_vec (nparms);
7108   new_args = add_outermost_template_args (args, new_inner_args);
7109   int pack_adjust = 0;
7110   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
7111     {
7112       tree arg;
7113       tree parm;
7114
7115       /* Get the Ith template parameter.  */
7116       parm = TREE_VEC_ELT (parms, parm_idx);
7117  
7118       if (parm == error_mark_node)
7119       {
7120         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
7121         continue;
7122       }
7123
7124       /* Calculate the next argument.  */
7125       if (arg_idx < nargs)
7126         arg = TREE_VEC_ELT (inner_args, arg_idx);
7127       else
7128         arg = NULL_TREE;
7129
7130       if (template_parameter_pack_p (TREE_VALUE (parm))
7131           && !(arg && ARGUMENT_PACK_P (arg)))
7132         {
7133           /* Some arguments will be placed in the
7134              template parameter pack PARM.  */
7135           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
7136                                                 inner_args, arg_idx,
7137                                                 new_args, &lost,
7138                                                 in_decl, complain);
7139
7140           if (arg == NULL_TREE)
7141             {
7142               /* We don't know how many args we have yet, just use the
7143                  unconverted (and still packed) ones for now.  */
7144               new_inner_args = orig_inner_args;
7145               arg_idx = nargs;
7146               break;
7147             }
7148
7149           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
7150
7151           /* Store this argument.  */
7152           if (arg == error_mark_node)
7153             {
7154               lost++;
7155               /* We are done with all of the arguments.  */
7156               arg_idx = nargs;
7157             }
7158           else
7159             {
7160               pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
7161               arg_idx += pack_adjust;
7162             }
7163           
7164           continue;
7165         }
7166       else if (arg)
7167         {
7168           if (PACK_EXPANSION_P (arg))
7169             {
7170               /* "If every valid specialization of a variadic template
7171                  requires an empty template parameter pack, the template is
7172                  ill-formed, no diagnostic required."  So check that the
7173                  pattern works with this parameter.  */
7174               tree pattern = PACK_EXPANSION_PATTERN (arg);
7175               tree conv = convert_template_argument (TREE_VALUE (parm),
7176                                                      pattern, new_args,
7177                                                      complain, parm_idx,
7178                                                      in_decl);
7179               if (conv == error_mark_node)
7180                 {
7181                   inform (input_location, "so any instantiation with a "
7182                          "non-empty parameter pack would be ill-formed");
7183                   ++lost;
7184                 }
7185               else if (TYPE_P (conv) && !TYPE_P (pattern))
7186                 /* Recover from missing typename.  */
7187                 TREE_VEC_ELT (inner_args, arg_idx)
7188                   = make_pack_expansion (conv);
7189
7190               /* We don't know how many args we have yet, just
7191                  use the unconverted ones for now.  */
7192               new_inner_args = inner_args;
7193               arg_idx = nargs;
7194               break;
7195             }
7196         }
7197       else if (require_all_args)
7198         {
7199           /* There must be a default arg in this case.  */
7200           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
7201                                      complain, in_decl);
7202           /* The position of the first default template argument,
7203              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
7204              Record that.  */
7205           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7206             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7207                                                  arg_idx - pack_adjust);
7208         }
7209       else
7210         break;
7211
7212       if (arg == error_mark_node)
7213         {
7214           if (complain & tf_error)
7215             error ("template argument %d is invalid", arg_idx + 1);
7216         }
7217       else if (!arg)
7218         /* This only occurs if there was an error in the template
7219            parameter list itself (which we would already have
7220            reported) that we are trying to recover from, e.g., a class
7221            template with a parameter list such as
7222            template<typename..., typename>.  */
7223         ++lost;
7224       else
7225         arg = convert_template_argument (TREE_VALUE (parm),
7226                                          arg, new_args, complain, 
7227                                          parm_idx, in_decl);
7228
7229       if (arg == error_mark_node)
7230         lost++;
7231       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
7232     }
7233   cp_unevaluated_operand = saved_unevaluated_operand;
7234   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
7235
7236   if (variadic_p && arg_idx < nargs)
7237     {
7238       if (complain & tf_error)
7239         {
7240           error ("wrong number of template arguments "
7241                  "(%d, should be %d)", nargs, arg_idx);
7242           if (in_decl)
7243             error ("provided for %q+D", in_decl);
7244         }
7245       return error_mark_node;
7246     }
7247
7248   if (lost)
7249     return error_mark_node;
7250
7251 #ifdef ENABLE_CHECKING
7252   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7253     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7254                                          TREE_VEC_LENGTH (new_inner_args));
7255 #endif
7256
7257   return new_inner_args;
7258 }
7259
7260 /* Like coerce_template_parms.  If PARMS represents all template
7261    parameters levels, this function returns a vector of vectors
7262    representing all the resulting argument levels.  Note that in this
7263    case, only the innermost arguments are coerced because the
7264    outermost ones are supposed to have been coerced already.
7265
7266    Otherwise, if PARMS represents only (the innermost) vector of
7267    parameters, this function returns a vector containing just the
7268    innermost resulting arguments.  */
7269
7270 static tree
7271 coerce_innermost_template_parms (tree parms,
7272                                   tree args,
7273                                   tree in_decl,
7274                                   tsubst_flags_t complain,
7275                                   bool require_all_args,
7276                                   bool use_default_args)
7277 {
7278   int parms_depth = TMPL_PARMS_DEPTH (parms);
7279   int args_depth = TMPL_ARGS_DEPTH (args);
7280   tree coerced_args;
7281
7282   if (parms_depth > 1)
7283     {
7284       coerced_args = make_tree_vec (parms_depth);
7285       tree level;
7286       int cur_depth;
7287
7288       for (level = parms, cur_depth = parms_depth;
7289            parms_depth > 0 && level != NULL_TREE;
7290            level = TREE_CHAIN (level), --cur_depth)
7291         {
7292           tree l;
7293           if (cur_depth == args_depth)
7294             l = coerce_template_parms (TREE_VALUE (level),
7295                                        args, in_decl, complain,
7296                                        require_all_args,
7297                                        use_default_args);
7298           else
7299             l = TMPL_ARGS_LEVEL (args, cur_depth);
7300
7301           if (l == error_mark_node)
7302             return error_mark_node;
7303
7304           SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
7305         }
7306     }
7307   else
7308     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
7309                                           args, in_decl, complain,
7310                                           require_all_args,
7311                                           use_default_args);
7312   return coerced_args;
7313 }
7314
7315 /* Returns 1 if template args OT and NT are equivalent.  */
7316
7317 static int
7318 template_args_equal (tree ot, tree nt)
7319 {
7320   if (nt == ot)
7321     return 1;
7322   if (nt == NULL_TREE || ot == NULL_TREE)
7323     return false;
7324
7325   if (TREE_CODE (nt) == TREE_VEC)
7326     /* For member templates */
7327     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
7328   else if (PACK_EXPANSION_P (ot))
7329     return (PACK_EXPANSION_P (nt)
7330             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
7331                                     PACK_EXPANSION_PATTERN (nt))
7332             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
7333                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
7334   else if (ARGUMENT_PACK_P (ot))
7335     {
7336       int i, len;
7337       tree opack, npack;
7338
7339       if (!ARGUMENT_PACK_P (nt))
7340         return 0;
7341
7342       opack = ARGUMENT_PACK_ARGS (ot);
7343       npack = ARGUMENT_PACK_ARGS (nt);
7344       len = TREE_VEC_LENGTH (opack);
7345       if (TREE_VEC_LENGTH (npack) != len)
7346         return 0;
7347       for (i = 0; i < len; ++i)
7348         if (!template_args_equal (TREE_VEC_ELT (opack, i),
7349                                   TREE_VEC_ELT (npack, i)))
7350           return 0;
7351       return 1;
7352     }
7353   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
7354     {
7355       /* We get here probably because we are in the middle of substituting
7356          into the pattern of a pack expansion. In that case the
7357          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
7358          interested in. So we want to use the initial pack argument for
7359          the comparison.  */
7360       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
7361       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
7362         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
7363       return template_args_equal (ot, nt);
7364     }
7365   else if (TYPE_P (nt))
7366     {
7367       if (!TYPE_P (ot))
7368         return false;
7369       /* Don't treat an alias template specialization with dependent
7370          arguments as equivalent to its underlying type when used as a
7371          template argument; we need them to be distinct so that we
7372          substitute into the specialization arguments at instantiation
7373          time.  And aliases can't be equivalent without being ==, so
7374          we don't need to look any deeper.  */
7375       if (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot))
7376         return false;
7377       else
7378         return same_type_p (ot, nt);
7379     }
7380   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
7381     return 0;
7382   else
7383     {
7384       /* Try to treat a template non-type argument that has been converted
7385          to the parameter type as equivalent to one that hasn't yet.  */
7386       for (enum tree_code code1 = TREE_CODE (ot);
7387            CONVERT_EXPR_CODE_P (code1)
7388              || code1 == NON_LVALUE_EXPR;
7389            code1 = TREE_CODE (ot))
7390         ot = TREE_OPERAND (ot, 0);
7391       for (enum tree_code code2 = TREE_CODE (nt);
7392            CONVERT_EXPR_CODE_P (code2)
7393              || code2 == NON_LVALUE_EXPR;
7394            code2 = TREE_CODE (nt))
7395         nt = TREE_OPERAND (nt, 0);
7396
7397       return cp_tree_equal (ot, nt);
7398     }
7399 }
7400
7401 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
7402    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
7403    NEWARG_PTR with the offending arguments if they are non-NULL.  */
7404
7405 static int
7406 comp_template_args_with_info (tree oldargs, tree newargs,
7407                               tree *oldarg_ptr, tree *newarg_ptr)
7408 {
7409   int i;
7410
7411   if (oldargs == newargs)
7412     return 1;
7413
7414   if (!oldargs || !newargs)
7415     return 0;
7416
7417   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
7418     return 0;
7419
7420   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
7421     {
7422       tree nt = TREE_VEC_ELT (newargs, i);
7423       tree ot = TREE_VEC_ELT (oldargs, i);
7424
7425       if (! template_args_equal (ot, nt))
7426         {
7427           if (oldarg_ptr != NULL)
7428             *oldarg_ptr = ot;
7429           if (newarg_ptr != NULL)
7430             *newarg_ptr = nt;
7431           return 0;
7432         }
7433     }
7434   return 1;
7435 }
7436
7437 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
7438    of template arguments.  Returns 0 otherwise.  */
7439
7440 int
7441 comp_template_args (tree oldargs, tree newargs)
7442 {
7443   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
7444 }
7445
7446 static void
7447 add_pending_template (tree d)
7448 {
7449   tree ti = (TYPE_P (d)
7450              ? CLASSTYPE_TEMPLATE_INFO (d)
7451              : DECL_TEMPLATE_INFO (d));
7452   struct pending_template *pt;
7453   int level;
7454
7455   if (TI_PENDING_TEMPLATE_FLAG (ti))
7456     return;
7457
7458   /* We are called both from instantiate_decl, where we've already had a
7459      tinst_level pushed, and instantiate_template, where we haven't.
7460      Compensate.  */
7461   level = !current_tinst_level || current_tinst_level->decl != d;
7462
7463   if (level)
7464     push_tinst_level (d);
7465
7466   pt = ggc_alloc<pending_template> ();
7467   pt->next = NULL;
7468   pt->tinst = current_tinst_level;
7469   if (last_pending_template)
7470     last_pending_template->next = pt;
7471   else
7472     pending_templates = pt;
7473
7474   last_pending_template = pt;
7475
7476   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
7477
7478   if (level)
7479     pop_tinst_level ();
7480 }
7481
7482
7483 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
7484    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
7485    documentation for TEMPLATE_ID_EXPR.  */
7486
7487 tree
7488 lookup_template_function (tree fns, tree arglist)
7489 {
7490   tree type;
7491
7492   if (fns == error_mark_node || arglist == error_mark_node)
7493     return error_mark_node;
7494
7495   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
7496
7497   if (!is_overloaded_fn (fns) && !identifier_p (fns))
7498     {
7499       error ("%q#D is not a function template", fns);
7500       return error_mark_node;
7501     }
7502
7503   if (BASELINK_P (fns))
7504     {
7505       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
7506                                          unknown_type_node,
7507                                          BASELINK_FUNCTIONS (fns),
7508                                          arglist);
7509       return fns;
7510     }
7511
7512   type = TREE_TYPE (fns);
7513   if (TREE_CODE (fns) == OVERLOAD || !type)
7514     type = unknown_type_node;
7515
7516   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
7517 }
7518
7519 /* Within the scope of a template class S<T>, the name S gets bound
7520    (in build_self_reference) to a TYPE_DECL for the class, not a
7521    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
7522    or one of its enclosing classes, and that type is a template,
7523    return the associated TEMPLATE_DECL.  Otherwise, the original
7524    DECL is returned.
7525
7526    Also handle the case when DECL is a TREE_LIST of ambiguous
7527    injected-class-names from different bases.  */
7528
7529 tree
7530 maybe_get_template_decl_from_type_decl (tree decl)
7531 {
7532   if (decl == NULL_TREE)
7533     return decl;
7534
7535   /* DR 176: A lookup that finds an injected-class-name (10.2
7536      [class.member.lookup]) can result in an ambiguity in certain cases
7537      (for example, if it is found in more than one base class). If all of
7538      the injected-class-names that are found refer to specializations of
7539      the same class template, and if the name is followed by a
7540      template-argument-list, the reference refers to the class template
7541      itself and not a specialization thereof, and is not ambiguous.  */
7542   if (TREE_CODE (decl) == TREE_LIST)
7543     {
7544       tree t, tmpl = NULL_TREE;
7545       for (t = decl; t; t = TREE_CHAIN (t))
7546         {
7547           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7548           if (!tmpl)
7549             tmpl = elt;
7550           else if (tmpl != elt)
7551             break;
7552         }
7553       if (tmpl && t == NULL_TREE)
7554         return tmpl;
7555       else
7556         return decl;
7557     }
7558
7559   return (decl != NULL_TREE
7560           && DECL_SELF_REFERENCE_P (decl)
7561           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7562     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7563 }
7564
7565 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
7566    parameters, find the desired type.
7567
7568    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7569
7570    IN_DECL, if non-NULL, is the template declaration we are trying to
7571    instantiate.
7572
7573    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7574    the class we are looking up.
7575
7576    Issue error and warning messages under control of COMPLAIN.
7577
7578    If the template class is really a local class in a template
7579    function, then the FUNCTION_CONTEXT is the function in which it is
7580    being instantiated.
7581
7582    ??? Note that this function is currently called *twice* for each
7583    template-id: the first time from the parser, while creating the
7584    incomplete type (finish_template_type), and the second type during the
7585    real instantiation (instantiate_template_class). This is surely something
7586    that we want to avoid. It also causes some problems with argument
7587    coercion (see convert_nontype_argument for more information on this).  */
7588
7589 static tree
7590 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7591                          int entering_scope, tsubst_flags_t complain)
7592 {
7593   tree templ = NULL_TREE, parmlist;
7594   tree t;
7595   spec_entry **slot;
7596   spec_entry *entry;
7597   spec_entry elt;
7598   hashval_t hash;
7599
7600   if (identifier_p (d1))
7601     {
7602       tree value = innermost_non_namespace_value (d1);
7603       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7604         templ = value;
7605       else
7606         {
7607           if (context)
7608             push_decl_namespace (context);
7609           templ = lookup_name (d1);
7610           templ = maybe_get_template_decl_from_type_decl (templ);
7611           if (context)
7612             pop_decl_namespace ();
7613         }
7614       if (templ)
7615         context = DECL_CONTEXT (templ);
7616     }
7617   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7618     {
7619       tree type = TREE_TYPE (d1);
7620
7621       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7622          an implicit typename for the second A.  Deal with it.  */
7623       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7624         type = TREE_TYPE (type);
7625
7626       if (CLASSTYPE_TEMPLATE_INFO (type))
7627         {
7628           templ = CLASSTYPE_TI_TEMPLATE (type);
7629           d1 = DECL_NAME (templ);
7630         }
7631     }
7632   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7633            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7634     {
7635       templ = TYPE_TI_TEMPLATE (d1);
7636       d1 = DECL_NAME (templ);
7637     }
7638   else if (DECL_TYPE_TEMPLATE_P (d1))
7639     {
7640       templ = d1;
7641       d1 = DECL_NAME (templ);
7642       context = DECL_CONTEXT (templ);
7643     }
7644   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
7645     {
7646       templ = d1;
7647       d1 = DECL_NAME (templ);
7648     }
7649
7650   /* Issue an error message if we didn't find a template.  */
7651   if (! templ)
7652     {
7653       if (complain & tf_error)
7654         error ("%qT is not a template", d1);
7655       return error_mark_node;
7656     }
7657
7658   if (TREE_CODE (templ) != TEMPLATE_DECL
7659          /* Make sure it's a user visible template, if it was named by
7660             the user.  */
7661       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7662           && !PRIMARY_TEMPLATE_P (templ)))
7663     {
7664       if (complain & tf_error)
7665         {
7666           error ("non-template type %qT used as a template", d1);
7667           if (in_decl)
7668             error ("for template declaration %q+D", in_decl);
7669         }
7670       return error_mark_node;
7671     }
7672
7673   complain &= ~tf_user;
7674
7675   /* An alias that just changes the name of a template is equivalent to the
7676      other template, so if any of the arguments are pack expansions, strip
7677      the alias to avoid problems with a pack expansion passed to a non-pack
7678      alias template parameter (DR 1430).  */
7679   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
7680     templ = get_underlying_template (templ);
7681
7682   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7683     {
7684       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7685          template arguments */
7686
7687       tree parm;
7688       tree arglist2;
7689       tree outer;
7690
7691       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7692
7693       /* Consider an example where a template template parameter declared as
7694
7695            template <class T, class U = std::allocator<T> > class TT
7696
7697          The template parameter level of T and U are one level larger than
7698          of TT.  To proper process the default argument of U, say when an
7699          instantiation `TT<int>' is seen, we need to build the full
7700          arguments containing {int} as the innermost level.  Outer levels,
7701          available when not appearing as default template argument, can be
7702          obtained from the arguments of the enclosing template.
7703
7704          Suppose that TT is later substituted with std::vector.  The above
7705          instantiation is `TT<int, std::allocator<T> >' with TT at
7706          level 1, and T at level 2, while the template arguments at level 1
7707          becomes {std::vector} and the inner level 2 is {int}.  */
7708
7709       outer = DECL_CONTEXT (templ);
7710       if (outer)
7711         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7712       else if (current_template_parms)
7713         /* This is an argument of the current template, so we haven't set
7714            DECL_CONTEXT yet.  */
7715         outer = current_template_args ();
7716
7717       if (outer)
7718         arglist = add_to_template_args (outer, arglist);
7719
7720       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7721                                         complain,
7722                                         /*require_all_args=*/true,
7723                                         /*use_default_args=*/true);
7724       if (arglist2 == error_mark_node
7725           || (!uses_template_parms (arglist2)
7726               && check_instantiated_args (templ, arglist2, complain)))
7727         return error_mark_node;
7728
7729       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7730       return parm;
7731     }
7732   else
7733     {
7734       tree template_type = TREE_TYPE (templ);
7735       tree gen_tmpl;
7736       tree type_decl;
7737       tree found = NULL_TREE;
7738       int arg_depth;
7739       int parm_depth;
7740       int is_dependent_type;
7741       int use_partial_inst_tmpl = false;
7742
7743       if (template_type == error_mark_node)
7744         /* An error occurred while building the template TEMPL, and a
7745            diagnostic has most certainly been emitted for that
7746            already.  Let's propagate that error.  */
7747         return error_mark_node;
7748
7749       gen_tmpl = most_general_template (templ);
7750       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7751       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7752       arg_depth = TMPL_ARGS_DEPTH (arglist);
7753
7754       if (arg_depth == 1 && parm_depth > 1)
7755         {
7756           /* We've been given an incomplete set of template arguments.
7757              For example, given:
7758
7759                template <class T> struct S1 {
7760                  template <class U> struct S2 {};
7761                  template <class U> struct S2<U*> {};
7762                 };
7763
7764              we will be called with an ARGLIST of `U*', but the
7765              TEMPLATE will be `template <class T> template
7766              <class U> struct S1<T>::S2'.  We must fill in the missing
7767              arguments.  */
7768           arglist
7769             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7770                                            arglist);
7771           arg_depth = TMPL_ARGS_DEPTH (arglist);
7772         }
7773
7774       /* Now we should have enough arguments.  */
7775       gcc_assert (parm_depth == arg_depth);
7776
7777       /* From here on, we're only interested in the most general
7778          template.  */
7779
7780       /* Calculate the BOUND_ARGS.  These will be the args that are
7781          actually tsubst'd into the definition to create the
7782          instantiation.  */
7783       if (parm_depth > 1)
7784         {
7785           /* We have multiple levels of arguments to coerce, at once.  */
7786           int i;
7787           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7788
7789           tree bound_args = make_tree_vec (parm_depth);
7790
7791           for (i = saved_depth,
7792                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7793                i > 0 && t != NULL_TREE;
7794                --i, t = TREE_CHAIN (t))
7795             {
7796               tree a;
7797               if (i == saved_depth)
7798                 a = coerce_template_parms (TREE_VALUE (t),
7799                                            arglist, gen_tmpl,
7800                                            complain,
7801                                            /*require_all_args=*/true,
7802                                            /*use_default_args=*/true);
7803               else
7804                 /* Outer levels should have already been coerced.  */
7805                 a = TMPL_ARGS_LEVEL (arglist, i);
7806
7807               /* Don't process further if one of the levels fails.  */
7808               if (a == error_mark_node)
7809                 {
7810                   /* Restore the ARGLIST to its full size.  */
7811                   TREE_VEC_LENGTH (arglist) = saved_depth;
7812                   return error_mark_node;
7813                 }
7814
7815               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7816
7817               /* We temporarily reduce the length of the ARGLIST so
7818                  that coerce_template_parms will see only the arguments
7819                  corresponding to the template parameters it is
7820                  examining.  */
7821               TREE_VEC_LENGTH (arglist)--;
7822             }
7823
7824           /* Restore the ARGLIST to its full size.  */
7825           TREE_VEC_LENGTH (arglist) = saved_depth;
7826
7827           arglist = bound_args;
7828         }
7829       else
7830         arglist
7831           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7832                                    INNERMOST_TEMPLATE_ARGS (arglist),
7833                                    gen_tmpl,
7834                                    complain,
7835                                    /*require_all_args=*/true,
7836                                    /*use_default_args=*/true);
7837
7838       if (arglist == error_mark_node)
7839         /* We were unable to bind the arguments.  */
7840         return error_mark_node;
7841
7842       /* In the scope of a template class, explicit references to the
7843          template class refer to the type of the template, not any
7844          instantiation of it.  For example, in:
7845
7846            template <class T> class C { void f(C<T>); }
7847
7848          the `C<T>' is just the same as `C'.  Outside of the
7849          class, however, such a reference is an instantiation.  */
7850       if ((entering_scope
7851            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7852            || currently_open_class (template_type))
7853           /* comp_template_args is expensive, check it last.  */
7854           && comp_template_args (TYPE_TI_ARGS (template_type),
7855                                  arglist))
7856         return template_type;
7857
7858       /* If we already have this specialization, return it.  */
7859       elt.tmpl = gen_tmpl;
7860       elt.args = arglist;
7861       hash = spec_hasher::hash (&elt);
7862       entry = type_specializations->find_with_hash (&elt, hash);
7863
7864       if (entry)
7865         return entry->spec;
7866
7867       is_dependent_type = uses_template_parms (arglist);
7868
7869       /* If the deduced arguments are invalid, then the binding
7870          failed.  */
7871       if (!is_dependent_type
7872           && check_instantiated_args (gen_tmpl,
7873                                       INNERMOST_TEMPLATE_ARGS (arglist),
7874                                       complain))
7875         return error_mark_node;
7876
7877       if (!is_dependent_type
7878           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7879           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7880           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7881         {
7882           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7883                                       DECL_NAME (gen_tmpl),
7884                                       /*tag_scope=*/ts_global);
7885           return found;
7886         }
7887
7888       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7889                         complain, in_decl);
7890       if (context == error_mark_node)
7891         return error_mark_node;
7892
7893       if (!context)
7894         context = global_namespace;
7895
7896       /* Create the type.  */
7897       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7898         {
7899           /* The user referred to a specialization of an alias
7900             template represented by GEN_TMPL.
7901
7902             [temp.alias]/2 says:
7903
7904                 When a template-id refers to the specialization of an
7905                 alias template, it is equivalent to the associated
7906                 type obtained by substitution of its
7907                 template-arguments for the template-parameters in the
7908                 type-id of the alias template.  */
7909
7910           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
7911           /* Note that the call above (by indirectly calling
7912              register_specialization in tsubst_decl) registers the
7913              TYPE_DECL representing the specialization of the alias
7914              template.  So next time someone substitutes ARGLIST for
7915              the template parms into the alias template (GEN_TMPL),
7916              she'll get that TYPE_DECL back.  */
7917
7918           if (t == error_mark_node)
7919             return t;
7920         }
7921       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7922         {
7923           if (!is_dependent_type)
7924             {
7925               set_current_access_from_decl (TYPE_NAME (template_type));
7926               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7927                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7928                                       arglist, complain, in_decl),
7929                               SCOPED_ENUM_P (template_type), NULL);
7930
7931               if (t == error_mark_node)
7932                 return t;
7933             }
7934           else
7935             {
7936               /* We don't want to call start_enum for this type, since
7937                  the values for the enumeration constants may involve
7938                  template parameters.  And, no one should be interested
7939                  in the enumeration constants for such a type.  */
7940               t = cxx_make_type (ENUMERAL_TYPE);
7941               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7942             }
7943           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7944           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7945             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7946         }
7947       else if (CLASS_TYPE_P (template_type))
7948         {
7949           t = make_class_type (TREE_CODE (template_type));
7950           CLASSTYPE_DECLARED_CLASS (t)
7951             = CLASSTYPE_DECLARED_CLASS (template_type);
7952           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7953           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7954
7955           /* A local class.  Make sure the decl gets registered properly.  */
7956           if (context == current_function_decl)
7957             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7958
7959           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7960             /* This instantiation is another name for the primary
7961                template type. Set the TYPE_CANONICAL field
7962                appropriately. */
7963             TYPE_CANONICAL (t) = template_type;
7964           else if (any_template_arguments_need_structural_equality_p (arglist))
7965             /* Some of the template arguments require structural
7966                equality testing, so this template class requires
7967                structural equality testing. */
7968             SET_TYPE_STRUCTURAL_EQUALITY (t);
7969         }
7970       else
7971         gcc_unreachable ();
7972
7973       /* If we called start_enum or pushtag above, this information
7974          will already be set up.  */
7975       if (!TYPE_NAME (t))
7976         {
7977           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7978
7979           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7980           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7981           DECL_SOURCE_LOCATION (type_decl)
7982             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7983         }
7984       else
7985         type_decl = TYPE_NAME (t);
7986
7987       if (CLASS_TYPE_P (template_type))
7988         {
7989           TREE_PRIVATE (type_decl)
7990             = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
7991           TREE_PROTECTED (type_decl)
7992             = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
7993           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7994             {
7995               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7996               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7997             }
7998         }
7999
8000       if (OVERLOAD_TYPE_P (t)
8001           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8002         {
8003           if (tree attributes
8004               = lookup_attribute ("abi_tag", TYPE_ATTRIBUTES (template_type)))
8005             {
8006               if (!TREE_CHAIN (attributes))
8007                 TYPE_ATTRIBUTES (t) = attributes;
8008               else
8009                 TYPE_ATTRIBUTES (t)
8010                   = build_tree_list (TREE_PURPOSE (attributes),
8011                                      TREE_VALUE (attributes));
8012             }
8013         }
8014
8015       /* Let's consider the explicit specialization of a member
8016          of a class template specialization that is implicitly instantiated,
8017          e.g.:
8018              template<class T>
8019              struct S
8020              {
8021                template<class U> struct M {}; //#0
8022              };
8023
8024              template<>
8025              template<>
8026              struct S<int>::M<char> //#1
8027              {
8028                int i;
8029              };
8030         [temp.expl.spec]/4 says this is valid.
8031
8032         In this case, when we write:
8033         S<int>::M<char> m;
8034
8035         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
8036         the one of #0.
8037
8038         When we encounter #1, we want to store the partial instantiation
8039         of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
8040
8041         For all cases other than this "explicit specialization of member of a
8042         class template", we just want to store the most general template into
8043         the CLASSTYPE_TI_TEMPLATE of M.
8044
8045         This case of "explicit specialization of member of a class template"
8046         only happens when:
8047         1/ the enclosing class is an instantiation of, and therefore not
8048         the same as, the context of the most general template, and
8049         2/ we aren't looking at the partial instantiation itself, i.e.
8050         the innermost arguments are not the same as the innermost parms of
8051         the most general template.
8052
8053         So it's only when 1/ and 2/ happens that we want to use the partial
8054         instantiation of the member template in lieu of its most general
8055         template.  */
8056
8057       if (PRIMARY_TEMPLATE_P (gen_tmpl)
8058           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
8059           /* the enclosing class must be an instantiation...  */
8060           && CLASS_TYPE_P (context)
8061           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
8062         {
8063           tree partial_inst_args;
8064           TREE_VEC_LENGTH (arglist)--;
8065           ++processing_template_decl;
8066           partial_inst_args =
8067             tsubst (INNERMOST_TEMPLATE_ARGS
8068                         (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
8069                     arglist, complain, NULL_TREE);
8070           --processing_template_decl;
8071           TREE_VEC_LENGTH (arglist)++;
8072           use_partial_inst_tmpl =
8073             /*...and we must not be looking at the partial instantiation
8074              itself. */
8075             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
8076                                  partial_inst_args);
8077         }
8078
8079       if (!use_partial_inst_tmpl)
8080         /* This case is easy; there are no member templates involved.  */
8081         found = gen_tmpl;
8082       else
8083         {
8084           /* This is a full instantiation of a member template.  Find
8085              the partial instantiation of which this is an instance.  */
8086
8087           /* Temporarily reduce by one the number of levels in the ARGLIST
8088              so as to avoid comparing the last set of arguments.  */
8089           TREE_VEC_LENGTH (arglist)--;
8090           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
8091           TREE_VEC_LENGTH (arglist)++;
8092           /* FOUND is either a proper class type, or an alias
8093              template specialization.  In the later case, it's a
8094              TYPE_DECL, resulting from the substituting of arguments
8095              for parameters in the TYPE_DECL of the alias template
8096              done earlier.  So be careful while getting the template
8097              of FOUND.  */
8098           found = TREE_CODE (found) == TYPE_DECL
8099             ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
8100             : CLASSTYPE_TI_TEMPLATE (found);
8101         }
8102
8103       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
8104
8105       elt.spec = t;
8106       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
8107       entry = ggc_alloc<spec_entry> ();
8108       *entry = elt;
8109       *slot = entry;
8110
8111       /* Note this use of the partial instantiation so we can check it
8112          later in maybe_process_partial_specialization.  */
8113       DECL_TEMPLATE_INSTANTIATIONS (found)
8114         = tree_cons (arglist, t,
8115                      DECL_TEMPLATE_INSTANTIATIONS (found));
8116
8117       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
8118           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8119         /* Now that the type has been registered on the instantiations
8120            list, we set up the enumerators.  Because the enumeration
8121            constants may involve the enumeration type itself, we make
8122            sure to register the type first, and then create the
8123            constants.  That way, doing tsubst_expr for the enumeration
8124            constants won't result in recursive calls here; we'll find
8125            the instantiation and exit above.  */
8126         tsubst_enum (template_type, t, arglist);
8127
8128       if (CLASS_TYPE_P (template_type) && is_dependent_type)
8129         /* If the type makes use of template parameters, the
8130            code that generates debugging information will crash.  */
8131         DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
8132
8133       /* Possibly limit visibility based on template args.  */
8134       TREE_PUBLIC (type_decl) = 1;
8135       determine_visibility (type_decl);
8136
8137       inherit_targ_abi_tags (t);
8138
8139       return t;
8140     }
8141 }
8142
8143 /* Wrapper for lookup_template_class_1.  */
8144
8145 tree
8146 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
8147                        int entering_scope, tsubst_flags_t complain)
8148 {
8149   tree ret;
8150   timevar_push (TV_TEMPLATE_INST);
8151   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
8152                                  entering_scope, complain);
8153   timevar_pop (TV_TEMPLATE_INST);
8154   return ret;
8155 }
8156
8157 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.
8158    The type of the expression is the unknown_type_node since the
8159    template-id could refer to an explicit or partial specialization. */
8160
8161 tree
8162 lookup_template_variable (tree templ, tree arglist)
8163 {
8164   tree type = unknown_type_node;
8165   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
8166 }
8167
8168 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
8169
8170 tree
8171 finish_template_variable (tree var)
8172 {
8173   tree templ = TREE_OPERAND (var, 0);
8174
8175   tree arglist = TREE_OPERAND (var, 1);
8176   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
8177   arglist = add_outermost_template_args (tmpl_args, arglist);
8178
8179   tree parms = DECL_TEMPLATE_PARMS (templ);
8180   tsubst_flags_t complain = tf_warning_or_error;
8181   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
8182                                              /*req_all*/true,
8183                                              /*use_default*/true);
8184
8185   return instantiate_template (templ, arglist, complain);
8186 }
8187 \f
8188 struct pair_fn_data
8189 {
8190   tree_fn_t fn;
8191   void *data;
8192   /* True when we should also visit template parameters that occur in
8193      non-deduced contexts.  */
8194   bool include_nondeduced_p;
8195   hash_set<tree> *visited;
8196 };
8197
8198 /* Called from for_each_template_parm via walk_tree.  */
8199
8200 static tree
8201 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
8202 {
8203   tree t = *tp;
8204   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
8205   tree_fn_t fn = pfd->fn;
8206   void *data = pfd->data;
8207
8208   if (TYPE_P (t)
8209       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
8210       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
8211                                  pfd->include_nondeduced_p))
8212     return error_mark_node;
8213
8214   switch (TREE_CODE (t))
8215     {
8216     case RECORD_TYPE:
8217       if (TYPE_PTRMEMFUNC_P (t))
8218         break;
8219       /* Fall through.  */
8220
8221     case UNION_TYPE:
8222     case ENUMERAL_TYPE:
8223       if (!TYPE_TEMPLATE_INFO (t))
8224         *walk_subtrees = 0;
8225       else if (for_each_template_parm (TYPE_TI_ARGS (t),
8226                                        fn, data, pfd->visited, 
8227                                        pfd->include_nondeduced_p))
8228         return error_mark_node;
8229       break;
8230
8231     case INTEGER_TYPE:
8232       if (for_each_template_parm (TYPE_MIN_VALUE (t),
8233                                   fn, data, pfd->visited, 
8234                                   pfd->include_nondeduced_p)
8235           || for_each_template_parm (TYPE_MAX_VALUE (t),
8236                                      fn, data, pfd->visited,
8237                                      pfd->include_nondeduced_p))
8238         return error_mark_node;
8239       break;
8240
8241     case METHOD_TYPE:
8242       /* Since we're not going to walk subtrees, we have to do this
8243          explicitly here.  */
8244       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
8245                                   pfd->visited, pfd->include_nondeduced_p))
8246         return error_mark_node;
8247       /* Fall through.  */
8248
8249     case FUNCTION_TYPE:
8250       /* Check the return type.  */
8251       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
8252                                   pfd->include_nondeduced_p))
8253         return error_mark_node;
8254
8255       /* Check the parameter types.  Since default arguments are not
8256          instantiated until they are needed, the TYPE_ARG_TYPES may
8257          contain expressions that involve template parameters.  But,
8258          no-one should be looking at them yet.  And, once they're
8259          instantiated, they don't contain template parameters, so
8260          there's no point in looking at them then, either.  */
8261       {
8262         tree parm;
8263
8264         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
8265           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
8266                                       pfd->visited, pfd->include_nondeduced_p))
8267             return error_mark_node;
8268
8269         /* Since we've already handled the TYPE_ARG_TYPES, we don't
8270            want walk_tree walking into them itself.  */
8271         *walk_subtrees = 0;
8272       }
8273       break;
8274
8275     case TYPEOF_TYPE:
8276     case UNDERLYING_TYPE:
8277       if (pfd->include_nondeduced_p
8278           && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
8279                                      pfd->visited, 
8280                                      pfd->include_nondeduced_p))
8281         return error_mark_node;
8282       break;
8283
8284     case FUNCTION_DECL:
8285     case VAR_DECL:
8286       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
8287           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
8288                                      pfd->visited, pfd->include_nondeduced_p))
8289         return error_mark_node;
8290       /* Fall through.  */
8291
8292     case PARM_DECL:
8293     case CONST_DECL:
8294       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
8295           && for_each_template_parm (DECL_INITIAL (t), fn, data,
8296                                      pfd->visited, pfd->include_nondeduced_p))
8297         return error_mark_node;
8298       if (DECL_CONTEXT (t)
8299           && pfd->include_nondeduced_p
8300           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
8301                                      pfd->visited, pfd->include_nondeduced_p))
8302         return error_mark_node;
8303       break;
8304
8305     case BOUND_TEMPLATE_TEMPLATE_PARM:
8306       /* Record template parameters such as `T' inside `TT<T>'.  */
8307       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
8308                                   pfd->include_nondeduced_p))
8309         return error_mark_node;
8310       /* Fall through.  */
8311
8312     case TEMPLATE_TEMPLATE_PARM:
8313     case TEMPLATE_TYPE_PARM:
8314     case TEMPLATE_PARM_INDEX:
8315       if (fn && (*fn)(t, data))
8316         return error_mark_node;
8317       else if (!fn)
8318         return error_mark_node;
8319       break;
8320
8321     case TEMPLATE_DECL:
8322       /* A template template parameter is encountered.  */
8323       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
8324           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
8325                                      pfd->include_nondeduced_p))
8326         return error_mark_node;
8327
8328       /* Already substituted template template parameter */
8329       *walk_subtrees = 0;
8330       break;
8331
8332     case TYPENAME_TYPE:
8333       if (!fn
8334           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
8335                                      data, pfd->visited, 
8336                                      pfd->include_nondeduced_p))
8337         return error_mark_node;
8338       break;
8339
8340     case CONSTRUCTOR:
8341       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
8342           && pfd->include_nondeduced_p
8343           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
8344                                      (TREE_TYPE (t)), fn, data,
8345                                      pfd->visited, pfd->include_nondeduced_p))
8346         return error_mark_node;
8347       break;
8348
8349     case INDIRECT_REF:
8350     case COMPONENT_REF:
8351       /* If there's no type, then this thing must be some expression
8352          involving template parameters.  */
8353       if (!fn && !TREE_TYPE (t))
8354         return error_mark_node;
8355       break;
8356
8357     case MODOP_EXPR:
8358     case CAST_EXPR:
8359     case IMPLICIT_CONV_EXPR:
8360     case REINTERPRET_CAST_EXPR:
8361     case CONST_CAST_EXPR:
8362     case STATIC_CAST_EXPR:
8363     case DYNAMIC_CAST_EXPR:
8364     case ARROW_EXPR:
8365     case DOTSTAR_EXPR:
8366     case TYPEID_EXPR:
8367     case PSEUDO_DTOR_EXPR:
8368       if (!fn)
8369         return error_mark_node;
8370       break;
8371
8372     default:
8373       break;
8374     }
8375
8376   /* We didn't find any template parameters we liked.  */
8377   return NULL_TREE;
8378 }
8379
8380 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
8381    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
8382    call FN with the parameter and the DATA.
8383    If FN returns nonzero, the iteration is terminated, and
8384    for_each_template_parm returns 1.  Otherwise, the iteration
8385    continues.  If FN never returns a nonzero value, the value
8386    returned by for_each_template_parm is 0.  If FN is NULL, it is
8387    considered to be the function which always returns 1.
8388
8389    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
8390    parameters that occur in non-deduced contexts.  When false, only
8391    visits those template parameters that can be deduced.  */
8392
8393 static int
8394 for_each_template_parm (tree t, tree_fn_t fn, void* data,
8395                         hash_set<tree> *visited,
8396                         bool include_nondeduced_p)
8397 {
8398   struct pair_fn_data pfd;
8399   int result;
8400
8401   /* Set up.  */
8402   pfd.fn = fn;
8403   pfd.data = data;
8404   pfd.include_nondeduced_p = include_nondeduced_p;
8405
8406   /* Walk the tree.  (Conceptually, we would like to walk without
8407      duplicates, but for_each_template_parm_r recursively calls
8408      for_each_template_parm, so we would need to reorganize a fair
8409      bit to use walk_tree_without_duplicates, so we keep our own
8410      visited list.)  */
8411   if (visited)
8412     pfd.visited = visited;
8413   else
8414     pfd.visited = new hash_set<tree>;
8415   result = cp_walk_tree (&t,
8416                          for_each_template_parm_r,
8417                          &pfd,
8418                          pfd.visited) != NULL_TREE;
8419
8420   /* Clean up.  */
8421   if (!visited)
8422     {
8423       delete pfd.visited;
8424       pfd.visited = 0;
8425     }
8426
8427   return result;
8428 }
8429
8430 /* Returns true if T depends on any template parameter.  */
8431
8432 int
8433 uses_template_parms (tree t)
8434 {
8435   if (t == NULL_TREE)
8436     return false;
8437
8438   bool dependent_p;
8439   int saved_processing_template_decl;
8440
8441   saved_processing_template_decl = processing_template_decl;
8442   if (!saved_processing_template_decl)
8443     processing_template_decl = 1;
8444   if (TYPE_P (t))
8445     dependent_p = dependent_type_p (t);
8446   else if (TREE_CODE (t) == TREE_VEC)
8447     dependent_p = any_dependent_template_arguments_p (t);
8448   else if (TREE_CODE (t) == TREE_LIST)
8449     dependent_p = (uses_template_parms (TREE_VALUE (t))
8450                    || uses_template_parms (TREE_CHAIN (t)));
8451   else if (TREE_CODE (t) == TYPE_DECL)
8452     dependent_p = dependent_type_p (TREE_TYPE (t));
8453   else if (DECL_P (t)
8454            || EXPR_P (t)
8455            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
8456            || TREE_CODE (t) == OVERLOAD
8457            || BASELINK_P (t)
8458            || identifier_p (t)
8459            || TREE_CODE (t) == TRAIT_EXPR
8460            || TREE_CODE (t) == CONSTRUCTOR
8461            || CONSTANT_CLASS_P (t))
8462     dependent_p = (type_dependent_expression_p (t)
8463                    || value_dependent_expression_p (t));
8464   else
8465     {
8466       gcc_assert (t == error_mark_node);
8467       dependent_p = false;
8468     }
8469
8470   processing_template_decl = saved_processing_template_decl;
8471
8472   return dependent_p;
8473 }
8474
8475 /* Returns true iff current_function_decl is an incompletely instantiated
8476    template.  Useful instead of processing_template_decl because the latter
8477    is set to 0 during instantiate_non_dependent_expr.  */
8478
8479 bool
8480 in_template_function (void)
8481 {
8482   tree fn = current_function_decl;
8483   bool ret;
8484   ++processing_template_decl;
8485   ret = (fn && DECL_LANG_SPECIFIC (fn)
8486          && DECL_TEMPLATE_INFO (fn)
8487          && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
8488   --processing_template_decl;
8489   return ret;
8490 }
8491
8492 /* Returns true if T depends on any template parameter with level LEVEL.  */
8493
8494 int
8495 uses_template_parms_level (tree t, int level)
8496 {
8497   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
8498                                  /*include_nondeduced_p=*/true);
8499 }
8500
8501 /* Returns TRUE iff INST is an instantiation we don't need to do in an
8502    ill-formed translation unit, i.e. a variable or function that isn't
8503    usable in a constant expression.  */
8504
8505 static inline bool
8506 neglectable_inst_p (tree d)
8507 {
8508   return (DECL_P (d)
8509           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
8510                : decl_maybe_constant_var_p (d)));
8511 }
8512
8513 /* Returns TRUE iff we should refuse to instantiate DECL because it's
8514    neglectable and instantiated from within an erroneous instantiation.  */
8515
8516 static bool
8517 limit_bad_template_recursion (tree decl)
8518 {
8519   struct tinst_level *lev = current_tinst_level;
8520   int errs = errorcount + sorrycount;
8521   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
8522     return false;
8523
8524   for (; lev; lev = lev->next)
8525     if (neglectable_inst_p (lev->decl))
8526       break;
8527
8528   return (lev && errs > lev->errors);
8529 }
8530
8531 static int tinst_depth;
8532 extern int max_tinst_depth;
8533 int depth_reached;
8534
8535 static GTY(()) struct tinst_level *last_error_tinst_level;
8536
8537 /* We're starting to instantiate D; record the template instantiation context
8538    for diagnostics and to restore it later.  */
8539
8540 bool
8541 push_tinst_level (tree d)
8542 {
8543   return push_tinst_level_loc (d, input_location);
8544 }
8545
8546 /* We're starting to instantiate D; record the template instantiation context
8547    at LOC for diagnostics and to restore it later.  */
8548
8549 bool
8550 push_tinst_level_loc (tree d, location_t loc)
8551 {
8552   struct tinst_level *new_level;
8553
8554   if (tinst_depth >= max_tinst_depth)
8555     {
8556       fatal_error (input_location,
8557                    "template instantiation depth exceeds maximum of %d"
8558                    " (use -ftemplate-depth= to increase the maximum)",
8559                    max_tinst_depth);
8560       return false;
8561     }
8562
8563   /* If the current instantiation caused problems, don't let it instantiate
8564      anything else.  Do allow deduction substitution and decls usable in
8565      constant expressions.  */
8566   if (limit_bad_template_recursion (d))
8567     return false;
8568
8569   new_level = ggc_alloc<tinst_level> ();
8570   new_level->decl = d;
8571   new_level->locus = loc;
8572   new_level->errors = errorcount+sorrycount;
8573   new_level->in_system_header_p = in_system_header_at (input_location);
8574   new_level->next = current_tinst_level;
8575   current_tinst_level = new_level;
8576
8577   ++tinst_depth;
8578   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
8579     depth_reached = tinst_depth;
8580
8581   return true;
8582 }
8583
8584 /* We're done instantiating this template; return to the instantiation
8585    context.  */
8586
8587 void
8588 pop_tinst_level (void)
8589 {
8590   /* Restore the filename and line number stashed away when we started
8591      this instantiation.  */
8592   input_location = current_tinst_level->locus;
8593   current_tinst_level = current_tinst_level->next;
8594   --tinst_depth;
8595 }
8596
8597 /* We're instantiating a deferred template; restore the template
8598    instantiation context in which the instantiation was requested, which
8599    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
8600
8601 static tree
8602 reopen_tinst_level (struct tinst_level *level)
8603 {
8604   struct tinst_level *t;
8605
8606   tinst_depth = 0;
8607   for (t = level; t; t = t->next)
8608     ++tinst_depth;
8609
8610   current_tinst_level = level;
8611   pop_tinst_level ();
8612   if (current_tinst_level)
8613     current_tinst_level->errors = errorcount+sorrycount;
8614   return level->decl;
8615 }
8616
8617 /* Returns the TINST_LEVEL which gives the original instantiation
8618    context.  */
8619
8620 struct tinst_level *
8621 outermost_tinst_level (void)
8622 {
8623   struct tinst_level *level = current_tinst_level;
8624   if (level)
8625     while (level->next)
8626       level = level->next;
8627   return level;
8628 }
8629
8630 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
8631    vector of template arguments, as for tsubst.
8632
8633    Returns an appropriate tsubst'd friend declaration.  */
8634
8635 static tree
8636 tsubst_friend_function (tree decl, tree args)
8637 {
8638   tree new_friend;
8639
8640   if (TREE_CODE (decl) == FUNCTION_DECL
8641       && DECL_TEMPLATE_INSTANTIATION (decl)
8642       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8643     /* This was a friend declared with an explicit template
8644        argument list, e.g.:
8645
8646        friend void f<>(T);
8647
8648        to indicate that f was a template instantiation, not a new
8649        function declaration.  Now, we have to figure out what
8650        instantiation of what template.  */
8651     {
8652       tree template_id, arglist, fns;
8653       tree new_args;
8654       tree tmpl;
8655       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8656
8657       /* Friend functions are looked up in the containing namespace scope.
8658          We must enter that scope, to avoid finding member functions of the
8659          current class with same name.  */
8660       push_nested_namespace (ns);
8661       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8662                          tf_warning_or_error, NULL_TREE,
8663                          /*integral_constant_expression_p=*/false);
8664       pop_nested_namespace (ns);
8665       arglist = tsubst (DECL_TI_ARGS (decl), args,
8666                         tf_warning_or_error, NULL_TREE);
8667       template_id = lookup_template_function (fns, arglist);
8668
8669       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8670       tmpl = determine_specialization (template_id, new_friend,
8671                                        &new_args,
8672                                        /*need_member_template=*/0,
8673                                        TREE_VEC_LENGTH (args),
8674                                        tsk_none);
8675       return instantiate_template (tmpl, new_args, tf_error);
8676     }
8677
8678   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8679
8680   /* The NEW_FRIEND will look like an instantiation, to the
8681      compiler, but is not an instantiation from the point of view of
8682      the language.  For example, we might have had:
8683
8684      template <class T> struct S {
8685        template <class U> friend void f(T, U);
8686      };
8687
8688      Then, in S<int>, template <class U> void f(int, U) is not an
8689      instantiation of anything.  */
8690   if (new_friend == error_mark_node)
8691     return error_mark_node;
8692
8693   DECL_USE_TEMPLATE (new_friend) = 0;
8694   if (TREE_CODE (decl) == TEMPLATE_DECL)
8695     {
8696       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8697       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8698         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8699     }
8700
8701   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8702      is not a template instantiation and should not be mangled like
8703      one.  Therefore, we forget the mangling here; we'll recompute it
8704      later if we need it.  */
8705   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8706     {
8707       SET_DECL_RTL (new_friend, NULL);
8708       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8709     }
8710
8711   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8712     {
8713       tree old_decl;
8714       tree new_friend_template_info;
8715       tree new_friend_result_template_info;
8716       tree ns;
8717       int  new_friend_is_defn;
8718
8719       /* We must save some information from NEW_FRIEND before calling
8720          duplicate decls since that function will free NEW_FRIEND if
8721          possible.  */
8722       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8723       new_friend_is_defn =
8724             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8725                            (template_for_substitution (new_friend)))
8726              != NULL_TREE);
8727       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8728         {
8729           /* This declaration is a `primary' template.  */
8730           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8731
8732           new_friend_result_template_info
8733             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8734         }
8735       else
8736         new_friend_result_template_info = NULL_TREE;
8737
8738       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8739       if (new_friend_is_defn)
8740         DECL_INITIAL (new_friend) = error_mark_node;
8741
8742       /* Inside pushdecl_namespace_level, we will push into the
8743          current namespace. However, the friend function should go
8744          into the namespace of the template.  */
8745       ns = decl_namespace_context (new_friend);
8746       push_nested_namespace (ns);
8747       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8748       pop_nested_namespace (ns);
8749
8750       if (old_decl == error_mark_node)
8751         return error_mark_node;
8752
8753       if (old_decl != new_friend)
8754         {
8755           /* This new friend declaration matched an existing
8756              declaration.  For example, given:
8757
8758                template <class T> void f(T);
8759                template <class U> class C {
8760                  template <class T> friend void f(T) {}
8761                };
8762
8763              the friend declaration actually provides the definition
8764              of `f', once C has been instantiated for some type.  So,
8765              old_decl will be the out-of-class template declaration,
8766              while new_friend is the in-class definition.
8767
8768              But, if `f' was called before this point, the
8769              instantiation of `f' will have DECL_TI_ARGS corresponding
8770              to `T' but not to `U', references to which might appear
8771              in the definition of `f'.  Previously, the most general
8772              template for an instantiation of `f' was the out-of-class
8773              version; now it is the in-class version.  Therefore, we
8774              run through all specialization of `f', adding to their
8775              DECL_TI_ARGS appropriately.  In particular, they need a
8776              new set of outer arguments, corresponding to the
8777              arguments for this class instantiation.
8778
8779              The same situation can arise with something like this:
8780
8781                friend void f(int);
8782                template <class T> class C {
8783                  friend void f(T) {}
8784                };
8785
8786              when `C<int>' is instantiated.  Now, `f(int)' is defined
8787              in the class.  */
8788
8789           if (!new_friend_is_defn)
8790             /* On the other hand, if the in-class declaration does
8791                *not* provide a definition, then we don't want to alter
8792                existing definitions.  We can just leave everything
8793                alone.  */
8794             ;
8795           else
8796             {
8797               tree new_template = TI_TEMPLATE (new_friend_template_info);
8798               tree new_args = TI_ARGS (new_friend_template_info);
8799
8800               /* Overwrite whatever template info was there before, if
8801                  any, with the new template information pertaining to
8802                  the declaration.  */
8803               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8804
8805               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8806                 {
8807                   /* We should have called reregister_specialization in
8808                      duplicate_decls.  */
8809                   gcc_assert (retrieve_specialization (new_template,
8810                                                        new_args, 0)
8811                               == old_decl);
8812
8813                   /* Instantiate it if the global has already been used.  */
8814                   if (DECL_ODR_USED (old_decl))
8815                     instantiate_decl (old_decl, /*defer_ok=*/true,
8816                                       /*expl_inst_class_mem_p=*/false);
8817                 }
8818               else
8819                 {
8820                   tree t;
8821
8822                   /* Indicate that the old function template is a partial
8823                      instantiation.  */
8824                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8825                     = new_friend_result_template_info;
8826
8827                   gcc_assert (new_template
8828                               == most_general_template (new_template));
8829                   gcc_assert (new_template != old_decl);
8830
8831                   /* Reassign any specializations already in the hash table
8832                      to the new more general template, and add the
8833                      additional template args.  */
8834                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8835                        t != NULL_TREE;
8836                        t = TREE_CHAIN (t))
8837                     {
8838                       tree spec = TREE_VALUE (t);
8839                       spec_entry elt;
8840
8841                       elt.tmpl = old_decl;
8842                       elt.args = DECL_TI_ARGS (spec);
8843                       elt.spec = NULL_TREE;
8844
8845                       decl_specializations->remove_elt (&elt);
8846
8847                       DECL_TI_ARGS (spec)
8848                         = add_outermost_template_args (new_args,
8849                                                        DECL_TI_ARGS (spec));
8850
8851                       register_specialization
8852                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8853
8854                     }
8855                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8856                 }
8857             }
8858
8859           /* The information from NEW_FRIEND has been merged into OLD_DECL
8860              by duplicate_decls.  */
8861           new_friend = old_decl;
8862         }
8863     }
8864   else
8865     {
8866       tree context = DECL_CONTEXT (new_friend);
8867       bool dependent_p;
8868
8869       /* In the code
8870            template <class T> class C {
8871              template <class U> friend void C1<U>::f (); // case 1
8872              friend void C2<T>::f ();                    // case 2
8873            };
8874          we only need to make sure CONTEXT is a complete type for
8875          case 2.  To distinguish between the two cases, we note that
8876          CONTEXT of case 1 remains dependent type after tsubst while
8877          this isn't true for case 2.  */
8878       ++processing_template_decl;
8879       dependent_p = dependent_type_p (context);
8880       --processing_template_decl;
8881
8882       if (!dependent_p
8883           && !complete_type_or_else (context, NULL_TREE))
8884         return error_mark_node;
8885
8886       if (COMPLETE_TYPE_P (context))
8887         {
8888           tree fn = new_friend;
8889           /* do_friend adds the TEMPLATE_DECL for any member friend
8890              template even if it isn't a member template, i.e.
8891                template <class T> friend A<T>::f();
8892              Look through it in that case.  */
8893           if (TREE_CODE (fn) == TEMPLATE_DECL
8894               && !PRIMARY_TEMPLATE_P (fn))
8895             fn = DECL_TEMPLATE_RESULT (fn);
8896           /* Check to see that the declaration is really present, and,
8897              possibly obtain an improved declaration.  */
8898           fn = check_classfn (context, fn, NULL_TREE);
8899
8900           if (fn)
8901             new_friend = fn;
8902         }
8903     }
8904
8905   return new_friend;
8906 }
8907
8908 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8909    template arguments, as for tsubst.
8910
8911    Returns an appropriate tsubst'd friend type or error_mark_node on
8912    failure.  */
8913
8914 static tree
8915 tsubst_friend_class (tree friend_tmpl, tree args)
8916 {
8917   tree friend_type;
8918   tree tmpl;
8919   tree context;
8920
8921   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
8922     {
8923       tree t = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
8924       return TREE_TYPE (t);
8925     }
8926
8927   context = CP_DECL_CONTEXT (friend_tmpl);
8928
8929   if (context != global_namespace)
8930     {
8931       if (TREE_CODE (context) == NAMESPACE_DECL)
8932         push_nested_namespace (context);
8933       else
8934         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8935     }
8936
8937   /* Look for a class template declaration.  We look for hidden names
8938      because two friend declarations of the same template are the
8939      same.  For example, in:
8940
8941        struct A { 
8942          template <typename> friend class F;
8943        };
8944        template <typename> struct B { 
8945          template <typename> friend class F;
8946        };
8947
8948      both F templates are the same.  */
8949   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8950                            /*block_p=*/true, 0, LOOKUP_HIDDEN);
8951
8952   /* But, if we don't find one, it might be because we're in a
8953      situation like this:
8954
8955        template <class T>
8956        struct S {
8957          template <class U>
8958          friend struct S;
8959        };
8960
8961      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8962      for `S<int>', not the TEMPLATE_DECL.  */
8963   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8964     {
8965       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8966       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8967     }
8968
8969   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8970     {
8971       /* The friend template has already been declared.  Just
8972          check to see that the declarations match, and install any new
8973          default parameters.  We must tsubst the default parameters,
8974          of course.  We only need the innermost template parameters
8975          because that is all that redeclare_class_template will look
8976          at.  */
8977       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8978           > TMPL_ARGS_DEPTH (args))
8979         {
8980           tree parms;
8981           location_t saved_input_location;
8982           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8983                                          args, tf_warning_or_error);
8984
8985           saved_input_location = input_location;
8986           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8987           redeclare_class_template (TREE_TYPE (tmpl), parms);
8988           input_location = saved_input_location;
8989           
8990         }
8991
8992       friend_type = TREE_TYPE (tmpl);
8993     }
8994   else
8995     {
8996       /* The friend template has not already been declared.  In this
8997          case, the instantiation of the template class will cause the
8998          injection of this template into the global scope.  */
8999       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
9000       if (tmpl == error_mark_node)
9001         return error_mark_node;
9002
9003       /* The new TMPL is not an instantiation of anything, so we
9004          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
9005          the new type because that is supposed to be the corresponding
9006          template decl, i.e., TMPL.  */
9007       DECL_USE_TEMPLATE (tmpl) = 0;
9008       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
9009       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
9010       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
9011         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
9012
9013       /* Inject this template into the global scope.  */
9014       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
9015     }
9016
9017   if (context != global_namespace)
9018     {
9019       if (TREE_CODE (context) == NAMESPACE_DECL)
9020         pop_nested_namespace (context);
9021       else
9022         pop_nested_class ();
9023     }
9024
9025   return friend_type;
9026 }
9027
9028 /* Returns zero if TYPE cannot be completed later due to circularity.
9029    Otherwise returns one.  */
9030
9031 static int
9032 can_complete_type_without_circularity (tree type)
9033 {
9034   if (type == NULL_TREE || type == error_mark_node)
9035     return 0;
9036   else if (COMPLETE_TYPE_P (type))
9037     return 1;
9038   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
9039     return can_complete_type_without_circularity (TREE_TYPE (type));
9040   else if (CLASS_TYPE_P (type)
9041            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
9042     return 0;
9043   else
9044     return 1;
9045 }
9046
9047 static tree tsubst_omp_clauses (tree, bool, tree, tsubst_flags_t, tree);
9048
9049 /* Apply any attributes which had to be deferred until instantiation
9050    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
9051    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
9052
9053 static void
9054 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
9055                                 tree args, tsubst_flags_t complain, tree in_decl)
9056 {
9057   tree last_dep = NULL_TREE;
9058   tree t;
9059   tree *p;
9060
9061   for (t = attributes; t; t = TREE_CHAIN (t))
9062     if (ATTR_IS_DEPENDENT (t))
9063       {
9064         last_dep = t;
9065         attributes = copy_list (attributes);
9066         break;
9067       }
9068
9069   if (DECL_P (*decl_p))
9070     {
9071       if (TREE_TYPE (*decl_p) == error_mark_node)
9072         return;
9073       p = &DECL_ATTRIBUTES (*decl_p);
9074     }
9075   else
9076     p = &TYPE_ATTRIBUTES (*decl_p);
9077
9078   if (last_dep)
9079     {
9080       tree late_attrs = NULL_TREE;
9081       tree *q = &late_attrs;
9082
9083       for (*p = attributes; *p; )
9084         {
9085           t = *p;
9086           if (ATTR_IS_DEPENDENT (t))
9087             {
9088               *p = TREE_CHAIN (t);
9089               TREE_CHAIN (t) = NULL_TREE;
9090               if ((flag_openmp || flag_openmp_simd || flag_cilkplus)
9091                   && is_attribute_p ("omp declare simd",
9092                                      get_attribute_name (t))
9093                   && TREE_VALUE (t))
9094                 {
9095                   tree clauses = TREE_VALUE (TREE_VALUE (t));
9096                   clauses = tsubst_omp_clauses (clauses, true, args,
9097                                                 complain, in_decl);
9098                   c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
9099                   clauses = finish_omp_clauses (clauses);
9100                   tree parms = DECL_ARGUMENTS (*decl_p);
9101                   clauses
9102                     = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
9103                   if (clauses)
9104                     TREE_VALUE (TREE_VALUE (t)) = clauses;
9105                   else
9106                     TREE_VALUE (t) = NULL_TREE;
9107                 }
9108               /* If the first attribute argument is an identifier, don't
9109                  pass it through tsubst.  Attributes like mode, format,
9110                  cleanup and several target specific attributes expect it
9111                  unmodified.  */
9112               else if (attribute_takes_identifier_p (get_attribute_name (t))
9113                        && TREE_VALUE (t))
9114                 {
9115                   tree chain
9116                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
9117                                    in_decl,
9118                                    /*integral_constant_expression_p=*/false);
9119                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
9120                     TREE_VALUE (t)
9121                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
9122                                    chain);
9123                 }
9124               else if (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t)))
9125                 {
9126                   /* An attribute pack expansion.  */
9127                   tree purp = TREE_PURPOSE (t);
9128                   tree pack = (tsubst_pack_expansion
9129                                (TREE_VALUE (t), args, complain, in_decl));
9130                   int len = TREE_VEC_LENGTH (pack);
9131                   for (int i = 0; i < len; ++i)
9132                     {
9133                       tree elt = TREE_VEC_ELT (pack, i);
9134                       *q = build_tree_list (purp, elt);
9135                       q = &TREE_CHAIN (*q);
9136                     }
9137                   continue;
9138                 }
9139               else
9140                 TREE_VALUE (t)
9141                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
9142                                  /*integral_constant_expression_p=*/false);
9143               *q = t;
9144               q = &TREE_CHAIN (t);
9145             }
9146           else
9147             p = &TREE_CHAIN (t);
9148         }
9149
9150       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
9151     }
9152 }
9153
9154 /* Perform (or defer) access check for typedefs that were referenced
9155    from within the template TMPL code.
9156    This is a subroutine of instantiate_decl and instantiate_class_template.
9157    TMPL is the template to consider and TARGS is the list of arguments of
9158    that template.  */
9159
9160 static void
9161 perform_typedefs_access_check (tree tmpl, tree targs)
9162 {
9163   location_t saved_location;
9164   unsigned i;
9165   qualified_typedef_usage_t *iter;
9166
9167   if (!tmpl
9168       || (!CLASS_TYPE_P (tmpl)
9169           && TREE_CODE (tmpl) != FUNCTION_DECL))
9170     return;
9171
9172   saved_location = input_location;
9173   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
9174     {
9175       tree type_decl = iter->typedef_decl;
9176       tree type_scope = iter->context;
9177
9178       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
9179         continue;
9180
9181       if (uses_template_parms (type_decl))
9182         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
9183       if (uses_template_parms (type_scope))
9184         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
9185
9186       /* Make access check error messages point to the location
9187          of the use of the typedef.  */
9188       input_location = iter->locus;
9189       perform_or_defer_access_check (TYPE_BINFO (type_scope),
9190                                      type_decl, type_decl,
9191                                      tf_warning_or_error);
9192     }
9193     input_location = saved_location;
9194 }
9195
9196 static tree
9197 instantiate_class_template_1 (tree type)
9198 {
9199   tree templ, args, pattern, t, member;
9200   tree typedecl;
9201   tree pbinfo;
9202   tree base_list;
9203   unsigned int saved_maximum_field_alignment;
9204   tree fn_context;
9205
9206   if (type == error_mark_node)
9207     return error_mark_node;
9208
9209   if (COMPLETE_OR_OPEN_TYPE_P (type)
9210       || uses_template_parms (type))
9211     return type;
9212
9213   /* Figure out which template is being instantiated.  */
9214   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
9215   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
9216
9217   /* Determine what specialization of the original template to
9218      instantiate.  */
9219   t = most_specialized_partial_spec (type, tf_warning_or_error);
9220   if (t == error_mark_node)
9221     {
9222       TYPE_BEING_DEFINED (type) = 1;
9223       return error_mark_node;
9224     }
9225   else if (t)
9226     {
9227       /* This TYPE is actually an instantiation of a partial
9228          specialization.  We replace the innermost set of ARGS with
9229          the arguments appropriate for substitution.  For example,
9230          given:
9231
9232            template <class T> struct S {};
9233            template <class T> struct S<T*> {};
9234
9235          and supposing that we are instantiating S<int*>, ARGS will
9236          presently be {int*} -- but we need {int}.  */
9237       pattern = TREE_TYPE (t);
9238       args = TREE_PURPOSE (t);
9239     }
9240   else
9241     {
9242       pattern = TREE_TYPE (templ);
9243       args = CLASSTYPE_TI_ARGS (type);
9244     }
9245
9246   /* If the template we're instantiating is incomplete, then clearly
9247      there's nothing we can do.  */
9248   if (!COMPLETE_TYPE_P (pattern))
9249     return type;
9250
9251   /* If we've recursively instantiated too many templates, stop.  */
9252   if (! push_tinst_level (type))
9253     return type;
9254
9255   /* Now we're really doing the instantiation.  Mark the type as in
9256      the process of being defined.  */
9257   TYPE_BEING_DEFINED (type) = 1;
9258
9259   /* We may be in the middle of deferred access check.  Disable
9260      it now.  */
9261   push_deferring_access_checks (dk_no_deferred);
9262
9263   int saved_unevaluated_operand = cp_unevaluated_operand;
9264   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9265
9266   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
9267   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
9268   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
9269     fn_context = error_mark_node;
9270   if (!fn_context)
9271     push_to_top_level ();
9272   else
9273     {
9274       cp_unevaluated_operand = 0;
9275       c_inhibit_evaluation_warnings = 0;
9276     }
9277   /* Use #pragma pack from the template context.  */
9278   saved_maximum_field_alignment = maximum_field_alignment;
9279   maximum_field_alignment = TYPE_PRECISION (pattern);
9280
9281   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
9282
9283   /* Set the input location to the most specialized template definition.
9284      This is needed if tsubsting causes an error.  */
9285   typedecl = TYPE_MAIN_DECL (pattern);
9286   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
9287     DECL_SOURCE_LOCATION (typedecl);
9288
9289   TYPE_PACKED (type) = TYPE_PACKED (pattern);
9290   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
9291   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
9292   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
9293   if (ANON_AGGR_TYPE_P (pattern))
9294     SET_ANON_AGGR_TYPE_P (type);
9295   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
9296     {
9297       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
9298       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
9299       /* Adjust visibility for template arguments.  */
9300       determine_visibility (TYPE_MAIN_DECL (type));
9301     }
9302   if (CLASS_TYPE_P (type))
9303     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
9304
9305   pbinfo = TYPE_BINFO (pattern);
9306
9307   /* We should never instantiate a nested class before its enclosing
9308      class; we need to look up the nested class by name before we can
9309      instantiate it, and that lookup should instantiate the enclosing
9310      class.  */
9311   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
9312               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
9313
9314   base_list = NULL_TREE;
9315   if (BINFO_N_BASE_BINFOS (pbinfo))
9316     {
9317       tree pbase_binfo;
9318       tree pushed_scope;
9319       int i;
9320
9321       /* We must enter the scope containing the type, as that is where
9322          the accessibility of types named in dependent bases are
9323          looked up from.  */
9324       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
9325
9326       /* Substitute into each of the bases to determine the actual
9327          basetypes.  */
9328       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
9329         {
9330           tree base;
9331           tree access = BINFO_BASE_ACCESS (pbinfo, i);
9332           tree expanded_bases = NULL_TREE;
9333           int idx, len = 1;
9334
9335           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
9336             {
9337               expanded_bases = 
9338                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
9339                                        args, tf_error, NULL_TREE);
9340               if (expanded_bases == error_mark_node)
9341                 continue;
9342
9343               len = TREE_VEC_LENGTH (expanded_bases);
9344             }
9345
9346           for (idx = 0; idx < len; idx++)
9347             {
9348               if (expanded_bases)
9349                 /* Extract the already-expanded base class.  */
9350                 base = TREE_VEC_ELT (expanded_bases, idx);
9351               else
9352                 /* Substitute to figure out the base class.  */
9353                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
9354                                NULL_TREE);
9355
9356               if (base == error_mark_node)
9357                 continue;
9358
9359               base_list = tree_cons (access, base, base_list);
9360               if (BINFO_VIRTUAL_P (pbase_binfo))
9361                 TREE_TYPE (base_list) = integer_type_node;
9362             }
9363         }
9364
9365       /* The list is now in reverse order; correct that.  */
9366       base_list = nreverse (base_list);
9367
9368       if (pushed_scope)
9369         pop_scope (pushed_scope);
9370     }
9371   /* Now call xref_basetypes to set up all the base-class
9372      information.  */
9373   xref_basetypes (type, base_list);
9374
9375   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
9376                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
9377                                   args, tf_error, NULL_TREE);
9378   fixup_attribute_variants (type);
9379
9380   /* Now that our base classes are set up, enter the scope of the
9381      class, so that name lookups into base classes, etc. will work
9382      correctly.  This is precisely analogous to what we do in
9383      begin_class_definition when defining an ordinary non-template
9384      class, except we also need to push the enclosing classes.  */
9385   push_nested_class (type);
9386
9387   /* Now members are processed in the order of declaration.  */
9388   for (member = CLASSTYPE_DECL_LIST (pattern);
9389        member; member = TREE_CHAIN (member))
9390     {
9391       tree t = TREE_VALUE (member);
9392
9393       if (TREE_PURPOSE (member))
9394         {
9395           if (TYPE_P (t))
9396             {
9397               /* Build new CLASSTYPE_NESTED_UTDS.  */
9398
9399               tree newtag;
9400               bool class_template_p;
9401
9402               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
9403                                   && TYPE_LANG_SPECIFIC (t)
9404                                   && CLASSTYPE_IS_TEMPLATE (t));
9405               /* If the member is a class template, then -- even after
9406                  substitution -- there may be dependent types in the
9407                  template argument list for the class.  We increment
9408                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
9409                  that function will assume that no types are dependent
9410                  when outside of a template.  */
9411               if (class_template_p)
9412                 ++processing_template_decl;
9413               newtag = tsubst (t, args, tf_error, NULL_TREE);
9414               if (class_template_p)
9415                 --processing_template_decl;
9416               if (newtag == error_mark_node)
9417                 continue;
9418
9419               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
9420                 {
9421                   tree name = TYPE_IDENTIFIER (t);
9422
9423                   if (class_template_p)
9424                     /* Unfortunately, lookup_template_class sets
9425                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
9426                        instantiation (i.e., for the type of a member
9427                        template class nested within a template class.)
9428                        This behavior is required for
9429                        maybe_process_partial_specialization to work
9430                        correctly, but is not accurate in this case;
9431                        the TAG is not an instantiation of anything.
9432                        (The corresponding TEMPLATE_DECL is an
9433                        instantiation, but the TYPE is not.) */
9434                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
9435
9436                   /* Now, we call pushtag to put this NEWTAG into the scope of
9437                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
9438                      pushtag calling push_template_decl.  We don't have to do
9439                      this for enums because it will already have been done in
9440                      tsubst_enum.  */
9441                   if (name)
9442                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
9443                   pushtag (name, newtag, /*tag_scope=*/ts_current);
9444                 }
9445             }
9446           else if (DECL_DECLARES_FUNCTION_P (t))
9447             {
9448               /* Build new TYPE_METHODS.  */
9449               tree r;
9450
9451               if (TREE_CODE (t) == TEMPLATE_DECL)
9452                 ++processing_template_decl;
9453               r = tsubst (t, args, tf_error, NULL_TREE);
9454               if (TREE_CODE (t) == TEMPLATE_DECL)
9455                 --processing_template_decl;
9456               set_current_access_from_decl (r);
9457               finish_member_declaration (r);
9458               /* Instantiate members marked with attribute used.  */
9459               if (r != error_mark_node && DECL_PRESERVE_P (r))
9460                 mark_used (r);
9461               if (TREE_CODE (r) == FUNCTION_DECL
9462                   && DECL_OMP_DECLARE_REDUCTION_P (r))
9463                 cp_check_omp_declare_reduction (r);
9464             }
9465           else if (DECL_CLASS_TEMPLATE_P (t)
9466                    && LAMBDA_TYPE_P (TREE_TYPE (t)))
9467             /* A closure type for a lambda in a default argument for a
9468                member template.  Ignore it; it will be instantiated with
9469                the default argument.  */;
9470           else
9471             {
9472               /* Build new TYPE_FIELDS.  */
9473               if (TREE_CODE (t) == STATIC_ASSERT)
9474                 {
9475                   tree condition;
9476  
9477                   ++c_inhibit_evaluation_warnings;
9478                   condition =
9479                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
9480                                  tf_warning_or_error, NULL_TREE,
9481                                  /*integral_constant_expression_p=*/true);
9482                   --c_inhibit_evaluation_warnings;
9483
9484                   finish_static_assert (condition,
9485                                         STATIC_ASSERT_MESSAGE (t), 
9486                                         STATIC_ASSERT_SOURCE_LOCATION (t),
9487                                         /*member_p=*/true);
9488                 }
9489               else if (TREE_CODE (t) != CONST_DECL)
9490                 {
9491                   tree r;
9492                   tree vec = NULL_TREE;
9493                   int len = 1;
9494
9495                   /* The file and line for this declaration, to
9496                      assist in error message reporting.  Since we
9497                      called push_tinst_level above, we don't need to
9498                      restore these.  */
9499                   input_location = DECL_SOURCE_LOCATION (t);
9500
9501                   if (TREE_CODE (t) == TEMPLATE_DECL)
9502                     ++processing_template_decl;
9503                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
9504                   if (TREE_CODE (t) == TEMPLATE_DECL)
9505                     --processing_template_decl;
9506
9507                   if (TREE_CODE (r) == TREE_VEC)
9508                     {
9509                       /* A capture pack became multiple fields.  */
9510                       vec = r;
9511                       len = TREE_VEC_LENGTH (vec);
9512                     }
9513
9514                   for (int i = 0; i < len; ++i)
9515                     {
9516                       if (vec)
9517                         r = TREE_VEC_ELT (vec, i);
9518                       if (VAR_P (r))
9519                         {
9520                           /* In [temp.inst]:
9521
9522                              [t]he initialization (and any associated
9523                              side-effects) of a static data member does
9524                              not occur unless the static data member is
9525                              itself used in a way that requires the
9526                              definition of the static data member to
9527                              exist.
9528
9529                              Therefore, we do not substitute into the
9530                              initialized for the static data member here.  */
9531                           finish_static_data_member_decl
9532                             (r,
9533                              /*init=*/NULL_TREE,
9534                              /*init_const_expr_p=*/false,
9535                              /*asmspec_tree=*/NULL_TREE,
9536                              /*flags=*/0);
9537                           /* Instantiate members marked with attribute used. */
9538                           if (r != error_mark_node && DECL_PRESERVE_P (r))
9539                             mark_used (r);
9540                         }
9541                       else if (TREE_CODE (r) == FIELD_DECL)
9542                         {
9543                           /* Determine whether R has a valid type and can be
9544                              completed later.  If R is invalid, then its type
9545                              is replaced by error_mark_node.  */
9546                           tree rtype = TREE_TYPE (r);
9547                           if (can_complete_type_without_circularity (rtype))
9548                             complete_type (rtype);
9549
9550                           if (!COMPLETE_TYPE_P (rtype))
9551                             {
9552                               cxx_incomplete_type_error (r, rtype);
9553                               TREE_TYPE (r) = error_mark_node;
9554                             }
9555                         }
9556
9557                       /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
9558                          such a thing will already have been added to the field
9559                          list by tsubst_enum in finish_member_declaration in the
9560                          CLASSTYPE_NESTED_UTDS case above.  */
9561                       if (!(TREE_CODE (r) == TYPE_DECL
9562                             && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
9563                             && DECL_ARTIFICIAL (r)))
9564                         {
9565                           set_current_access_from_decl (r);
9566                           finish_member_declaration (r);
9567                         }
9568                     }
9569                 }
9570             }
9571         }
9572       else
9573         {
9574           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
9575               || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9576             {
9577               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
9578
9579               tree friend_type = t;
9580               bool adjust_processing_template_decl = false;
9581
9582               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
9583                 {
9584                   /* template <class T> friend class C;  */
9585                   friend_type = tsubst_friend_class (friend_type, args);
9586                   adjust_processing_template_decl = true;
9587                 }
9588               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
9589                 {
9590                   /* template <class T> friend class C::D;  */
9591                   friend_type = tsubst (friend_type, args,
9592                                         tf_warning_or_error, NULL_TREE);
9593                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
9594                     friend_type = TREE_TYPE (friend_type);
9595                   adjust_processing_template_decl = true;
9596                 }
9597               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
9598                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
9599                 {
9600                   /* This could be either
9601
9602                        friend class T::C;
9603
9604                      when dependent_type_p is false or
9605
9606                        template <class U> friend class T::C;
9607
9608                      otherwise.  */
9609                   friend_type = tsubst (friend_type, args,
9610                                         tf_warning_or_error, NULL_TREE);
9611                   /* Bump processing_template_decl for correct
9612                      dependent_type_p calculation.  */
9613                   ++processing_template_decl;
9614                   if (dependent_type_p (friend_type))
9615                     adjust_processing_template_decl = true;
9616                   --processing_template_decl;
9617                 }
9618               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
9619                        && hidden_name_p (TYPE_NAME (friend_type)))
9620                 {
9621                   /* friend class C;
9622
9623                      where C hasn't been declared yet.  Let's lookup name
9624                      from namespace scope directly, bypassing any name that
9625                      come from dependent base class.  */
9626                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
9627
9628                   /* The call to xref_tag_from_type does injection for friend
9629                      classes.  */
9630                   push_nested_namespace (ns);
9631                   friend_type =
9632                     xref_tag_from_type (friend_type, NULL_TREE,
9633                                         /*tag_scope=*/ts_current);
9634                   pop_nested_namespace (ns);
9635                 }
9636               else if (uses_template_parms (friend_type))
9637                 /* friend class C<T>;  */
9638                 friend_type = tsubst (friend_type, args,
9639                                       tf_warning_or_error, NULL_TREE);
9640               /* Otherwise it's
9641
9642                    friend class C;
9643
9644                  where C is already declared or
9645
9646                    friend class C<int>;
9647
9648                  We don't have to do anything in these cases.  */
9649
9650               if (adjust_processing_template_decl)
9651                 /* Trick make_friend_class into realizing that the friend
9652                    we're adding is a template, not an ordinary class.  It's
9653                    important that we use make_friend_class since it will
9654                    perform some error-checking and output cross-reference
9655                    information.  */
9656                 ++processing_template_decl;
9657
9658               if (friend_type != error_mark_node)
9659                 make_friend_class (type, friend_type, /*complain=*/false);
9660
9661               if (adjust_processing_template_decl)
9662                 --processing_template_decl;
9663             }
9664           else
9665             {
9666               /* Build new DECL_FRIENDLIST.  */
9667               tree r;
9668
9669               /* The file and line for this declaration, to
9670                  assist in error message reporting.  Since we
9671                  called push_tinst_level above, we don't need to
9672                  restore these.  */
9673               input_location = DECL_SOURCE_LOCATION (t);
9674
9675               if (TREE_CODE (t) == TEMPLATE_DECL)
9676                 {
9677                   ++processing_template_decl;
9678                   push_deferring_access_checks (dk_no_check);
9679                 }
9680
9681               r = tsubst_friend_function (t, args);
9682               add_friend (type, r, /*complain=*/false);
9683               if (TREE_CODE (t) == TEMPLATE_DECL)
9684                 {
9685                   pop_deferring_access_checks ();
9686                   --processing_template_decl;
9687                 }
9688             }
9689         }
9690     }
9691
9692   if (fn_context)
9693     {
9694       /* Restore these before substituting into the lambda capture
9695          initializers.  */
9696       cp_unevaluated_operand = saved_unevaluated_operand;
9697       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9698     }
9699
9700   if (tree expr = CLASSTYPE_LAMBDA_EXPR (type))
9701     {
9702       tree decl = lambda_function (type);
9703       if (decl)
9704         {
9705           if (!DECL_TEMPLATE_INFO (decl)
9706               || DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) != decl)
9707             instantiate_decl (decl, false, false);
9708
9709           /* We need to instantiate the capture list from the template
9710              after we've instantiated the closure members, but before we
9711              consider adding the conversion op.  Also keep any captures
9712              that may have been added during instantiation of the op().  */
9713           tree tmpl_expr = CLASSTYPE_LAMBDA_EXPR (pattern);
9714           tree tmpl_cap
9715             = tsubst_copy_and_build (LAMBDA_EXPR_CAPTURE_LIST (tmpl_expr),
9716                                      args, tf_warning_or_error, NULL_TREE,
9717                                      false, false);
9718
9719           LAMBDA_EXPR_CAPTURE_LIST (expr)
9720             = chainon (tmpl_cap, nreverse (LAMBDA_EXPR_CAPTURE_LIST (expr)));
9721
9722           maybe_add_lambda_conv_op (type);
9723         }
9724       else
9725         gcc_assert (errorcount);
9726     }
9727
9728   /* Set the file and line number information to whatever is given for
9729      the class itself.  This puts error messages involving generated
9730      implicit functions at a predictable point, and the same point
9731      that would be used for non-template classes.  */
9732   input_location = DECL_SOURCE_LOCATION (typedecl);
9733
9734   unreverse_member_declarations (type);
9735   finish_struct_1 (type);
9736   TYPE_BEING_DEFINED (type) = 0;
9737
9738   /* We don't instantiate default arguments for member functions.  14.7.1:
9739
9740      The implicit instantiation of a class template specialization causes
9741      the implicit instantiation of the declarations, but not of the
9742      definitions or default arguments, of the class member functions,
9743      member classes, static data members and member templates....  */
9744
9745   /* Some typedefs referenced from within the template code need to be access
9746      checked at template instantiation time, i.e now. These types were
9747      added to the template at parsing time. Let's get those and perform
9748      the access checks then.  */
9749   perform_typedefs_access_check (pattern, args);
9750   perform_deferred_access_checks (tf_warning_or_error);
9751   pop_nested_class ();
9752   maximum_field_alignment = saved_maximum_field_alignment;
9753   if (!fn_context)
9754     pop_from_top_level ();
9755   pop_deferring_access_checks ();
9756   pop_tinst_level ();
9757
9758   /* The vtable for a template class can be emitted in any translation
9759      unit in which the class is instantiated.  When there is no key
9760      method, however, finish_struct_1 will already have added TYPE to
9761      the keyed_classes list.  */
9762   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9763     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9764
9765   return type;
9766 }
9767
9768 /* Wrapper for instantiate_class_template_1.  */
9769
9770 tree
9771 instantiate_class_template (tree type)
9772 {
9773   tree ret;
9774   timevar_push (TV_TEMPLATE_INST);
9775   ret = instantiate_class_template_1 (type);
9776   timevar_pop (TV_TEMPLATE_INST);
9777   return ret;
9778 }
9779
9780 static tree
9781 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9782 {
9783   tree r;
9784
9785   if (!t)
9786     r = t;
9787   else if (TYPE_P (t))
9788     r = tsubst (t, args, complain, in_decl);
9789   else
9790     {
9791       if (!(complain & tf_warning))
9792         ++c_inhibit_evaluation_warnings;
9793       r = tsubst_expr (t, args, complain, in_decl,
9794                        /*integral_constant_expression_p=*/true);
9795       if (!(complain & tf_warning))
9796         --c_inhibit_evaluation_warnings;
9797     }
9798   return r;
9799 }
9800
9801 /* Given a function parameter pack TMPL_PARM and some function parameters
9802    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9803    and set *SPEC_P to point at the next point in the list.  */
9804
9805 static tree
9806 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9807 {
9808   /* Collect all of the extra "packed" parameters into an
9809      argument pack.  */
9810   tree parmvec;
9811   tree parmtypevec;
9812   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9813   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9814   tree spec_parm = *spec_p;
9815   int i, len;
9816
9817   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9818     if (tmpl_parm
9819         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9820       break;
9821
9822   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9823   parmvec = make_tree_vec (len);
9824   parmtypevec = make_tree_vec (len);
9825   spec_parm = *spec_p;
9826   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9827     {
9828       TREE_VEC_ELT (parmvec, i) = spec_parm;
9829       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9830     }
9831
9832   /* Build the argument packs.  */
9833   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9834   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9835   TREE_TYPE (argpack) = argtypepack;
9836   *spec_p = spec_parm;
9837
9838   return argpack;
9839 }
9840
9841 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9842    NONTYPE_ARGUMENT_PACK.  */
9843
9844 static tree
9845 make_fnparm_pack (tree spec_parm)
9846 {
9847   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9848 }
9849
9850 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
9851    pack expansion with no extra args, 2 if it has extra args, or 0
9852    if it is not a pack expansion.  */
9853
9854 static int
9855 argument_pack_element_is_expansion_p (tree arg_pack, int i)
9856 {
9857   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
9858   if (i >= TREE_VEC_LENGTH (vec))
9859     return 0;
9860   tree elt = TREE_VEC_ELT (vec, i);
9861   if (!PACK_EXPANSION_P (elt))
9862     return 0;
9863   if (PACK_EXPANSION_EXTRA_ARGS (elt))
9864     return 2;
9865   return 1;
9866 }
9867
9868
9869 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
9870
9871 static tree
9872 make_argument_pack_select (tree arg_pack, unsigned index)
9873 {
9874   tree aps = make_node (ARGUMENT_PACK_SELECT);
9875
9876   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
9877   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
9878
9879   return aps;
9880 }
9881
9882 /*  This is a subroutine of tsubst_pack_expansion.
9883
9884     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
9885     mechanism to store the (non complete list of) arguments of the
9886     substitution and return a non substituted pack expansion, in order
9887     to wait for when we have enough arguments to really perform the
9888     substitution.  */
9889
9890 static bool
9891 use_pack_expansion_extra_args_p (tree parm_packs,
9892                                  int arg_pack_len,
9893                                  bool has_empty_arg)
9894 {
9895   /* If one pack has an expansion and another pack has a normal
9896      argument or if one pack has an empty argument and an another
9897      one hasn't then tsubst_pack_expansion cannot perform the
9898      substitution and need to fall back on the
9899      PACK_EXPANSION_EXTRA mechanism.  */
9900   if (parm_packs == NULL_TREE)
9901     return false;
9902   else if (has_empty_arg)
9903     return true;
9904
9905   bool has_expansion_arg = false;
9906   for (int i = 0 ; i < arg_pack_len; ++i)
9907     {
9908       bool has_non_expansion_arg = false;
9909       for (tree parm_pack = parm_packs;
9910            parm_pack;
9911            parm_pack = TREE_CHAIN (parm_pack))
9912         {
9913           tree arg = TREE_VALUE (parm_pack);
9914
9915           int exp = argument_pack_element_is_expansion_p (arg, i);
9916           if (exp == 2)
9917             /* We can't substitute a pack expansion with extra args into
9918                our pattern.  */
9919             return true;
9920           else if (exp)
9921             has_expansion_arg = true;
9922           else
9923             has_non_expansion_arg = true;
9924         }
9925
9926       if (has_expansion_arg && has_non_expansion_arg)
9927         return true;
9928     }
9929   return false;
9930 }
9931
9932 /* [temp.variadic]/6 says that:
9933
9934        The instantiation of a pack expansion [...]
9935        produces a list E1,E2, ..., En, where N is the number of elements
9936        in the pack expansion parameters.
9937
9938    This subroutine of tsubst_pack_expansion produces one of these Ei.
9939
9940    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
9941    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
9942    PATTERN, and each TREE_VALUE is its corresponding argument pack.
9943    INDEX is the index 'i' of the element Ei to produce.  ARGS,
9944    COMPLAIN, and IN_DECL are the same parameters as for the
9945    tsubst_pack_expansion function.
9946
9947    The function returns the resulting Ei upon successful completion,
9948    or error_mark_node.
9949
9950    Note that this function possibly modifies the ARGS parameter, so
9951    it's the responsibility of the caller to restore it.  */
9952
9953 static tree
9954 gen_elem_of_pack_expansion_instantiation (tree pattern,
9955                                           tree parm_packs,
9956                                           unsigned index,
9957                                           tree args /* This parm gets
9958                                                        modified.  */,
9959                                           tsubst_flags_t complain,
9960                                           tree in_decl)
9961 {
9962   tree t;
9963   bool ith_elem_is_expansion = false;
9964
9965   /* For each parameter pack, change the substitution of the parameter
9966      pack to the ith argument in its argument pack, then expand the
9967      pattern.  */
9968   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
9969     {
9970       tree parm = TREE_PURPOSE (pack);
9971       tree arg_pack = TREE_VALUE (pack);
9972       tree aps;                 /* instance of ARGUMENT_PACK_SELECT.  */
9973
9974       ith_elem_is_expansion |=
9975         argument_pack_element_is_expansion_p (arg_pack, index);
9976
9977       /* Select the Ith argument from the pack.  */
9978       if (TREE_CODE (parm) == PARM_DECL
9979           || TREE_CODE (parm) == FIELD_DECL)
9980         {
9981           if (index == 0)
9982             {
9983               aps = make_argument_pack_select (arg_pack, index);
9984               mark_used (parm);
9985               register_local_specialization (aps, parm);
9986             }
9987           else
9988             aps = retrieve_local_specialization (parm);
9989         }
9990       else
9991         {
9992           int idx, level;
9993           template_parm_level_and_index (parm, &level, &idx);
9994
9995           if (index == 0)
9996             {
9997               aps = make_argument_pack_select (arg_pack, index);
9998               /* Update the corresponding argument.  */
9999               TMPL_ARG (args, level, idx) = aps;
10000             }
10001           else
10002             /* Re-use the ARGUMENT_PACK_SELECT.  */
10003             aps = TMPL_ARG (args, level, idx);
10004         }
10005       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
10006     }
10007
10008   /* Substitute into the PATTERN with the (possibly altered)
10009      arguments.  */
10010   if (pattern == in_decl)
10011     /* Expanding a fixed parameter pack from
10012        coerce_template_parameter_pack.  */
10013     t = tsubst_decl (pattern, args, complain);
10014   else if (!TYPE_P (pattern))
10015     t = tsubst_expr (pattern, args, complain, in_decl,
10016                      /*integral_constant_expression_p=*/false);
10017   else
10018     t = tsubst (pattern, args, complain, in_decl);
10019
10020   /*  If the Ith argument pack element is a pack expansion, then
10021       the Ith element resulting from the substituting is going to
10022       be a pack expansion as well.  */
10023   if (ith_elem_is_expansion)
10024     t = make_pack_expansion (t);
10025
10026   return t;
10027 }
10028
10029 /* Substitute ARGS into T, which is an pack expansion
10030    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
10031    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
10032    (if only a partial substitution could be performed) or
10033    ERROR_MARK_NODE if there was an error.  */
10034 tree
10035 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
10036                        tree in_decl)
10037 {
10038   tree pattern;
10039   tree pack, packs = NULL_TREE;
10040   bool unsubstituted_packs = false;
10041   int i, len = -1;
10042   tree result;
10043   hash_map<tree, tree> *saved_local_specializations = NULL;
10044   bool need_local_specializations = false;
10045   int levels;
10046
10047   gcc_assert (PACK_EXPANSION_P (t));
10048   pattern = PACK_EXPANSION_PATTERN (t);
10049
10050   /* Add in any args remembered from an earlier partial instantiation.  */
10051   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
10052
10053   levels = TMPL_ARGS_DEPTH (args);
10054
10055   /* Determine the argument packs that will instantiate the parameter
10056      packs used in the expansion expression. While we're at it,
10057      compute the number of arguments to be expanded and make sure it
10058      is consistent.  */
10059   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
10060        pack = TREE_CHAIN (pack))
10061     {
10062       tree parm_pack = TREE_VALUE (pack);
10063       tree arg_pack = NULL_TREE;
10064       tree orig_arg = NULL_TREE;
10065       int level = 0;
10066
10067       if (TREE_CODE (parm_pack) == BASES)
10068        {
10069          if (BASES_DIRECT (parm_pack))
10070            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
10071                                                         args, complain, in_decl, false));
10072          else
10073            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
10074                                                  args, complain, in_decl, false));
10075        }
10076       if (TREE_CODE (parm_pack) == PARM_DECL)
10077         {
10078           if (PACK_EXPANSION_LOCAL_P (t))
10079             arg_pack = retrieve_local_specialization (parm_pack);
10080           else
10081             {
10082               /* We can't rely on local_specializations for a parameter
10083                  name used later in a function declaration (such as in a
10084                  late-specified return type).  Even if it exists, it might
10085                  have the wrong value for a recursive call.  Just make a
10086                  dummy decl, since it's only used for its type.  */
10087               arg_pack = tsubst_decl (parm_pack, args, complain);
10088               if (arg_pack && DECL_PACK_P (arg_pack))
10089                 /* Partial instantiation of the parm_pack, we can't build
10090                    up an argument pack yet.  */
10091                 arg_pack = NULL_TREE;
10092               else
10093                 arg_pack = make_fnparm_pack (arg_pack);
10094               need_local_specializations = true;
10095             }
10096         }
10097       else if (TREE_CODE (parm_pack) == FIELD_DECL)
10098         arg_pack = tsubst_copy (parm_pack, args, complain, in_decl);
10099       else
10100         {
10101           int idx;
10102           template_parm_level_and_index (parm_pack, &level, &idx);
10103
10104           if (level <= levels)
10105             arg_pack = TMPL_ARG (args, level, idx);
10106         }
10107
10108       orig_arg = arg_pack;
10109       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
10110         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
10111       
10112       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
10113         /* This can only happen if we forget to expand an argument
10114            pack somewhere else. Just return an error, silently.  */
10115         {
10116           result = make_tree_vec (1);
10117           TREE_VEC_ELT (result, 0) = error_mark_node;
10118           return result;
10119         }
10120
10121       if (arg_pack)
10122         {
10123           int my_len = 
10124             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
10125
10126           /* Don't bother trying to do a partial substitution with
10127              incomplete packs; we'll try again after deduction.  */
10128           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
10129             return t;
10130
10131           if (len < 0)
10132             len = my_len;
10133           else if (len != my_len)
10134             {
10135               if (!(complain & tf_error))
10136                 /* Fail quietly.  */;
10137               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
10138                 error ("mismatched argument pack lengths while expanding "
10139                        "%<%T%>",
10140                        pattern);
10141               else
10142                 error ("mismatched argument pack lengths while expanding "
10143                        "%<%E%>",
10144                        pattern);
10145               return error_mark_node;
10146             }
10147
10148           /* Keep track of the parameter packs and their corresponding
10149              argument packs.  */
10150           packs = tree_cons (parm_pack, arg_pack, packs);
10151           TREE_TYPE (packs) = orig_arg;
10152         }
10153       else
10154         {
10155           /* We can't substitute for this parameter pack.  We use a flag as
10156              well as the missing_level counter because function parameter
10157              packs don't have a level.  */
10158           unsubstituted_packs = true;
10159         }
10160     }
10161
10162   /* If the expansion is just T..., return the matching argument pack.  */
10163   if (!unsubstituted_packs
10164       && TREE_PURPOSE (packs) == pattern)
10165     {
10166       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
10167       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
10168           || pack_expansion_args_count (args))
10169         return args;
10170       /* Otherwise use the normal path so we get convert_from_reference.  */
10171     }
10172
10173   /* We cannot expand this expansion expression, because we don't have
10174      all of the argument packs we need.  */
10175   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
10176     {
10177       /* We got some full packs, but we can't substitute them in until we
10178          have values for all the packs.  So remember these until then.  */
10179
10180       t = make_pack_expansion (pattern);
10181       PACK_EXPANSION_EXTRA_ARGS (t) = args;
10182       return t;
10183     }
10184   else if (unsubstituted_packs)
10185     {
10186       /* There were no real arguments, we're just replacing a parameter
10187          pack with another version of itself. Substitute into the
10188          pattern and return a PACK_EXPANSION_*. The caller will need to
10189          deal with that.  */
10190       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
10191         t = tsubst_expr (pattern, args, complain, in_decl,
10192                          /*integral_constant_expression_p=*/false);
10193       else
10194         t = tsubst (pattern, args, complain, in_decl);
10195       t = make_pack_expansion (t);
10196       return t;
10197     }
10198
10199   gcc_assert (len >= 0);
10200
10201   if (need_local_specializations)
10202     {
10203       /* We're in a late-specified return type, so create our own local
10204          specializations map; the current map is either NULL or (in the
10205          case of recursive unification) might have bindings that we don't
10206          want to use or alter.  */
10207       saved_local_specializations = local_specializations;
10208       local_specializations = new hash_map<tree, tree>;
10209     }
10210
10211   /* For each argument in each argument pack, substitute into the
10212      pattern.  */
10213   result = make_tree_vec (len);
10214   for (i = 0; i < len; ++i)
10215     {
10216       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
10217                                                     i,
10218                                                     args, complain,
10219                                                     in_decl);
10220       TREE_VEC_ELT (result, i) = t;
10221       if (t == error_mark_node)
10222         {
10223           result = error_mark_node;
10224           break;
10225         }
10226     }
10227
10228   /* Update ARGS to restore the substitution from parameter packs to
10229      their argument packs.  */
10230   for (pack = packs; pack; pack = TREE_CHAIN (pack))
10231     {
10232       tree parm = TREE_PURPOSE (pack);
10233
10234       if (TREE_CODE (parm) == PARM_DECL
10235           || TREE_CODE (parm) == FIELD_DECL)
10236         register_local_specialization (TREE_TYPE (pack), parm);
10237       else
10238         {
10239           int idx, level;
10240
10241           if (TREE_VALUE (pack) == NULL_TREE)
10242             continue;
10243
10244           template_parm_level_and_index (parm, &level, &idx);
10245           
10246           /* Update the corresponding argument.  */
10247           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
10248             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
10249               TREE_TYPE (pack);
10250           else
10251             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
10252         }
10253     }
10254
10255   if (need_local_specializations)
10256     {
10257       delete local_specializations;
10258       local_specializations = saved_local_specializations;
10259     }
10260   
10261   return result;
10262 }
10263
10264 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
10265    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
10266    parameter packs; all parms generated from a function parameter pack will
10267    have the same DECL_PARM_INDEX.  */
10268
10269 tree
10270 get_pattern_parm (tree parm, tree tmpl)
10271 {
10272   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
10273   tree patparm;
10274
10275   if (DECL_ARTIFICIAL (parm))
10276     {
10277       for (patparm = DECL_ARGUMENTS (pattern);
10278            patparm; patparm = DECL_CHAIN (patparm))
10279         if (DECL_ARTIFICIAL (patparm)
10280             && DECL_NAME (parm) == DECL_NAME (patparm))
10281           break;
10282     }
10283   else
10284     {
10285       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
10286       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
10287       gcc_assert (DECL_PARM_INDEX (patparm)
10288                   == DECL_PARM_INDEX (parm));
10289     }
10290
10291   return patparm;
10292 }
10293
10294 /* Substitute ARGS into the vector or list of template arguments T.  */
10295
10296 static tree
10297 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10298 {
10299   tree orig_t = t;
10300   int len, need_new = 0, i, expanded_len_adjust = 0, out;
10301   tree *elts;
10302
10303   if (t == error_mark_node)
10304     return error_mark_node;
10305
10306   len = TREE_VEC_LENGTH (t);
10307   elts = XALLOCAVEC (tree, len);
10308
10309   for (i = 0; i < len; i++)
10310     {
10311       tree orig_arg = TREE_VEC_ELT (t, i);
10312       tree new_arg;
10313
10314       if (TREE_CODE (orig_arg) == TREE_VEC)
10315         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
10316       else if (PACK_EXPANSION_P (orig_arg))
10317         {
10318           /* Substitute into an expansion expression.  */
10319           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
10320
10321           if (TREE_CODE (new_arg) == TREE_VEC)
10322             /* Add to the expanded length adjustment the number of
10323                expanded arguments. We subtract one from this
10324                measurement, because the argument pack expression
10325                itself is already counted as 1 in
10326                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
10327                the argument pack is empty.  */
10328             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
10329         }
10330       else if (ARGUMENT_PACK_P (orig_arg))
10331         {
10332           /* Substitute into each of the arguments.  */
10333           new_arg = TYPE_P (orig_arg)
10334             ? cxx_make_type (TREE_CODE (orig_arg))
10335             : make_node (TREE_CODE (orig_arg));
10336           
10337           SET_ARGUMENT_PACK_ARGS (
10338             new_arg,
10339             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
10340                                   args, complain, in_decl));
10341
10342           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
10343             new_arg = error_mark_node;
10344
10345           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
10346             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
10347                                           complain, in_decl);
10348             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
10349
10350             if (TREE_TYPE (new_arg) == error_mark_node)
10351               new_arg = error_mark_node;
10352           }
10353         }
10354       else
10355         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
10356
10357       if (new_arg == error_mark_node)
10358         return error_mark_node;
10359
10360       elts[i] = new_arg;
10361       if (new_arg != orig_arg)
10362         need_new = 1;
10363     }
10364
10365   if (!need_new)
10366     return t;
10367
10368   /* Make space for the expanded arguments coming from template
10369      argument packs.  */
10370   t = make_tree_vec (len + expanded_len_adjust);
10371   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
10372      arguments for a member template.
10373      In that case each TREE_VEC in ORIG_T represents a level of template
10374      arguments, and ORIG_T won't carry any non defaulted argument count.
10375      It will rather be the nested TREE_VECs that will carry one.
10376      In other words, ORIG_T carries a non defaulted argument count only
10377      if it doesn't contain any nested TREE_VEC.  */
10378   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
10379     {
10380       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
10381       count += expanded_len_adjust;
10382       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
10383     }
10384   for (i = 0, out = 0; i < len; i++)
10385     {
10386       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
10387            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
10388           && TREE_CODE (elts[i]) == TREE_VEC)
10389         {
10390           int idx;
10391
10392           /* Now expand the template argument pack "in place".  */
10393           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
10394             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
10395         }
10396       else
10397         {
10398           TREE_VEC_ELT (t, out) = elts[i];
10399           out++;
10400         }
10401     }
10402
10403   return t;
10404 }
10405
10406 /* Return the result of substituting ARGS into the template parameters
10407    given by PARMS.  If there are m levels of ARGS and m + n levels of
10408    PARMS, then the result will contain n levels of PARMS.  For
10409    example, if PARMS is `template <class T> template <class U>
10410    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
10411    result will be `template <int*, double, class V>'.  */
10412
10413 static tree
10414 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
10415 {
10416   tree r = NULL_TREE;
10417   tree* new_parms;
10418
10419   /* When substituting into a template, we must set
10420      PROCESSING_TEMPLATE_DECL as the template parameters may be
10421      dependent if they are based on one-another, and the dependency
10422      predicates are short-circuit outside of templates.  */
10423   ++processing_template_decl;
10424
10425   for (new_parms = &r;
10426        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
10427        new_parms = &(TREE_CHAIN (*new_parms)),
10428          parms = TREE_CHAIN (parms))
10429     {
10430       tree new_vec =
10431         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
10432       int i;
10433
10434       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
10435         {
10436           tree tuple;
10437
10438           if (parms == error_mark_node)
10439             continue;
10440
10441           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
10442
10443           if (tuple == error_mark_node)
10444             continue;
10445
10446           TREE_VEC_ELT (new_vec, i) =
10447             tsubst_template_parm (tuple, args, complain);
10448         }
10449
10450       *new_parms =
10451         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
10452                              - TMPL_ARGS_DEPTH (args)),
10453                    new_vec, NULL_TREE);
10454     }
10455
10456   --processing_template_decl;
10457
10458   return r;
10459 }
10460
10461 /* Return the result of substituting ARGS into one template parameter
10462    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
10463    parameter and which TREE_PURPOSE is the default argument of the
10464    template parameter.  */
10465
10466 static tree
10467 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
10468 {
10469   tree default_value, parm_decl;
10470
10471   if (args == NULL_TREE
10472       || t == NULL_TREE
10473       || t == error_mark_node)
10474     return t;
10475
10476   gcc_assert (TREE_CODE (t) == TREE_LIST);
10477
10478   default_value = TREE_PURPOSE (t);
10479   parm_decl = TREE_VALUE (t);
10480
10481   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
10482   if (TREE_CODE (parm_decl) == PARM_DECL
10483       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
10484     parm_decl = error_mark_node;
10485   default_value = tsubst_template_arg (default_value, args,
10486                                        complain, NULL_TREE);
10487
10488   return build_tree_list (default_value, parm_decl);
10489 }
10490
10491 /* Substitute the ARGS into the indicated aggregate (or enumeration)
10492    type T.  If T is not an aggregate or enumeration type, it is
10493    handled as if by tsubst.  IN_DECL is as for tsubst.  If
10494    ENTERING_SCOPE is nonzero, T is the context for a template which
10495    we are presently tsubst'ing.  Return the substituted value.  */
10496
10497 static tree
10498 tsubst_aggr_type (tree t,
10499                   tree args,
10500                   tsubst_flags_t complain,
10501                   tree in_decl,
10502                   int entering_scope)
10503 {
10504   if (t == NULL_TREE)
10505     return NULL_TREE;
10506
10507   switch (TREE_CODE (t))
10508     {
10509     case RECORD_TYPE:
10510       if (TYPE_PTRMEMFUNC_P (t))
10511         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
10512
10513       /* Else fall through.  */
10514     case ENUMERAL_TYPE:
10515     case UNION_TYPE:
10516       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
10517         {
10518           tree argvec;
10519           tree context;
10520           tree r;
10521           int saved_unevaluated_operand;
10522           int saved_inhibit_evaluation_warnings;
10523
10524           /* In "sizeof(X<I>)" we need to evaluate "I".  */
10525           saved_unevaluated_operand = cp_unevaluated_operand;
10526           cp_unevaluated_operand = 0;
10527           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10528           c_inhibit_evaluation_warnings = 0;
10529
10530           /* First, determine the context for the type we are looking
10531              up.  */
10532           context = TYPE_CONTEXT (t);
10533           if (context && TYPE_P (context))
10534             {
10535               context = tsubst_aggr_type (context, args, complain,
10536                                           in_decl, /*entering_scope=*/1);
10537               /* If context is a nested class inside a class template,
10538                  it may still need to be instantiated (c++/33959).  */
10539               context = complete_type (context);
10540             }
10541
10542           /* Then, figure out what arguments are appropriate for the
10543              type we are trying to find.  For example, given:
10544
10545                template <class T> struct S;
10546                template <class T, class U> void f(T, U) { S<U> su; }
10547
10548              and supposing that we are instantiating f<int, double>,
10549              then our ARGS will be {int, double}, but, when looking up
10550              S we only want {double}.  */
10551           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
10552                                          complain, in_decl);
10553           if (argvec == error_mark_node)
10554             r = error_mark_node;
10555           else
10556             {
10557               r = lookup_template_class (t, argvec, in_decl, context,
10558                                          entering_scope, complain);
10559               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10560             }
10561
10562           cp_unevaluated_operand = saved_unevaluated_operand;
10563           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
10564
10565           return r;
10566         }
10567       else
10568         /* This is not a template type, so there's nothing to do.  */
10569         return t;
10570
10571     default:
10572       return tsubst (t, args, complain, in_decl);
10573     }
10574 }
10575
10576 /* Substitute into the default argument ARG (a default argument for
10577    FN), which has the indicated TYPE.  */
10578
10579 tree
10580 tsubst_default_argument (tree fn, tree type, tree arg, tsubst_flags_t complain)
10581 {
10582   tree saved_class_ptr = NULL_TREE;
10583   tree saved_class_ref = NULL_TREE;
10584   int errs = errorcount + sorrycount;
10585
10586   /* This can happen in invalid code.  */
10587   if (TREE_CODE (arg) == DEFAULT_ARG)
10588     return arg;
10589
10590   /* This default argument came from a template.  Instantiate the
10591      default argument here, not in tsubst.  In the case of
10592      something like:
10593
10594        template <class T>
10595        struct S {
10596          static T t();
10597          void f(T = t());
10598        };
10599
10600      we must be careful to do name lookup in the scope of S<T>,
10601      rather than in the current class.  */
10602   push_access_scope (fn);
10603   /* The "this" pointer is not valid in a default argument.  */
10604   if (cfun)
10605     {
10606       saved_class_ptr = current_class_ptr;
10607       cp_function_chain->x_current_class_ptr = NULL_TREE;
10608       saved_class_ref = current_class_ref;
10609       cp_function_chain->x_current_class_ref = NULL_TREE;
10610     }
10611
10612   push_deferring_access_checks(dk_no_deferred);
10613   /* The default argument expression may cause implicitly defined
10614      member functions to be synthesized, which will result in garbage
10615      collection.  We must treat this situation as if we were within
10616      the body of function so as to avoid collecting live data on the
10617      stack.  */
10618   ++function_depth;
10619   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
10620                      complain, NULL_TREE,
10621                      /*integral_constant_expression_p=*/false);
10622   --function_depth;
10623   pop_deferring_access_checks();
10624
10625   /* Restore the "this" pointer.  */
10626   if (cfun)
10627     {
10628       cp_function_chain->x_current_class_ptr = saved_class_ptr;
10629       cp_function_chain->x_current_class_ref = saved_class_ref;
10630     }
10631
10632   if (errorcount+sorrycount > errs
10633       && (complain & tf_warning_or_error))
10634     inform (input_location,
10635             "  when instantiating default argument for call to %D", fn);
10636
10637   /* Make sure the default argument is reasonable.  */
10638   arg = check_default_argument (type, arg, complain);
10639
10640   pop_access_scope (fn);
10641
10642   return arg;
10643 }
10644
10645 /* Substitute into all the default arguments for FN.  */
10646
10647 static void
10648 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
10649 {
10650   tree arg;
10651   tree tmpl_args;
10652
10653   tmpl_args = DECL_TI_ARGS (fn);
10654
10655   /* If this function is not yet instantiated, we certainly don't need
10656      its default arguments.  */
10657   if (uses_template_parms (tmpl_args))
10658     return;
10659   /* Don't do this again for clones.  */
10660   if (DECL_CLONED_FUNCTION_P (fn))
10661     return;
10662
10663   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
10664        arg;
10665        arg = TREE_CHAIN (arg))
10666     if (TREE_PURPOSE (arg))
10667       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
10668                                                     TREE_VALUE (arg),
10669                                                     TREE_PURPOSE (arg),
10670                                                     complain);
10671 }
10672
10673 /* Substitute the ARGS into the T, which is a _DECL.  Return the
10674    result of the substitution.  Issue error and warning messages under
10675    control of COMPLAIN.  */
10676
10677 static tree
10678 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
10679 {
10680 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
10681   location_t saved_loc;
10682   tree r = NULL_TREE;
10683   tree in_decl = t;
10684   hashval_t hash = 0;
10685
10686   /* Set the filename and linenumber to improve error-reporting.  */
10687   saved_loc = input_location;
10688   input_location = DECL_SOURCE_LOCATION (t);
10689
10690   switch (TREE_CODE (t))
10691     {
10692     case TEMPLATE_DECL:
10693       {
10694         /* We can get here when processing a member function template,
10695            member class template, or template template parameter.  */
10696         tree decl = DECL_TEMPLATE_RESULT (t);
10697         tree spec;
10698         tree tmpl_args;
10699         tree full_args;
10700
10701         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10702           {
10703             /* Template template parameter is treated here.  */
10704             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10705             if (new_type == error_mark_node)
10706               RETURN (error_mark_node);
10707             /* If we get a real template back, return it.  This can happen in
10708                the context of most_specialized_partial_spec.  */
10709             if (TREE_CODE (new_type) == TEMPLATE_DECL)
10710               return new_type;
10711
10712             r = copy_decl (t);
10713             DECL_CHAIN (r) = NULL_TREE;
10714             TREE_TYPE (r) = new_type;
10715             DECL_TEMPLATE_RESULT (r)
10716               = build_decl (DECL_SOURCE_LOCATION (decl),
10717                             TYPE_DECL, DECL_NAME (decl), new_type);
10718             DECL_TEMPLATE_PARMS (r)
10719               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
10720                                        complain);
10721             TYPE_NAME (new_type) = r;
10722             break;
10723           }
10724
10725         /* We might already have an instance of this template.
10726            The ARGS are for the surrounding class type, so the
10727            full args contain the tsubst'd args for the context,
10728            plus the innermost args from the template decl.  */
10729         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
10730           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
10731           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
10732         /* Because this is a template, the arguments will still be
10733            dependent, even after substitution.  If
10734            PROCESSING_TEMPLATE_DECL is not set, the dependency
10735            predicates will short-circuit.  */
10736         ++processing_template_decl;
10737         full_args = tsubst_template_args (tmpl_args, args,
10738                                           complain, in_decl);
10739         --processing_template_decl;
10740         if (full_args == error_mark_node)
10741           RETURN (error_mark_node);
10742
10743         /* If this is a default template template argument,
10744            tsubst might not have changed anything.  */
10745         if (full_args == tmpl_args)
10746           RETURN (t);
10747
10748         hash = hash_tmpl_and_args (t, full_args);
10749         spec = retrieve_specialization (t, full_args, hash);
10750         if (spec != NULL_TREE)
10751           {
10752             r = spec;
10753             break;
10754           }
10755
10756         /* Make a new template decl.  It will be similar to the
10757            original, but will record the current template arguments.
10758            We also create a new function declaration, which is just
10759            like the old one, but points to this new template, rather
10760            than the old one.  */
10761         r = copy_decl (t);
10762         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
10763         DECL_CHAIN (r) = NULL_TREE;
10764
10765         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10766
10767         if (TREE_CODE (decl) == TYPE_DECL
10768             && !TYPE_DECL_ALIAS_P (decl))
10769           {
10770             tree new_type;
10771             ++processing_template_decl;
10772             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10773             --processing_template_decl;
10774             if (new_type == error_mark_node)
10775               RETURN (error_mark_node);
10776
10777             TREE_TYPE (r) = new_type;
10778             /* For a partial specialization, we need to keep pointing to
10779                the primary template.  */
10780             if (!DECL_TEMPLATE_SPECIALIZATION (t))
10781               CLASSTYPE_TI_TEMPLATE (new_type) = r;
10782             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
10783             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
10784             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
10785           }
10786         else
10787           {
10788             tree new_decl;
10789             ++processing_template_decl;
10790             new_decl = tsubst (decl, args, complain, in_decl);
10791             --processing_template_decl;
10792             if (new_decl == error_mark_node)
10793               RETURN (error_mark_node);
10794
10795             DECL_TEMPLATE_RESULT (r) = new_decl;
10796             DECL_TI_TEMPLATE (new_decl) = r;
10797             TREE_TYPE (r) = TREE_TYPE (new_decl);
10798             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
10799             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
10800           }
10801
10802         SET_DECL_IMPLICIT_INSTANTIATION (r);
10803         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
10804         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
10805
10806         /* The template parameters for this new template are all the
10807            template parameters for the old template, except the
10808            outermost level of parameters.  */
10809         DECL_TEMPLATE_PARMS (r)
10810           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
10811                                    complain);
10812
10813         if (PRIMARY_TEMPLATE_P (t))
10814           DECL_PRIMARY_TEMPLATE (r) = r;
10815
10816         if (TREE_CODE (decl) != TYPE_DECL && TREE_CODE (decl) != VAR_DECL)
10817           /* Record this non-type partial instantiation.  */
10818           register_specialization (r, t,
10819                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
10820                                    false, hash);
10821       }
10822       break;
10823
10824     case FUNCTION_DECL:
10825       {
10826         tree ctx;
10827         tree argvec = NULL_TREE;
10828         tree *friends;
10829         tree gen_tmpl;
10830         tree type;
10831         int member;
10832         int args_depth;
10833         int parms_depth;
10834
10835         /* Nobody should be tsubst'ing into non-template functions.  */
10836         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
10837
10838         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
10839           {
10840             tree spec;
10841             bool dependent_p;
10842
10843             /* If T is not dependent, just return it.  We have to
10844                increment PROCESSING_TEMPLATE_DECL because
10845                value_dependent_expression_p assumes that nothing is
10846                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
10847             ++processing_template_decl;
10848             dependent_p = value_dependent_expression_p (t);
10849             --processing_template_decl;
10850             if (!dependent_p)
10851               RETURN (t);
10852
10853             /* Calculate the most general template of which R is a
10854                specialization, and the complete set of arguments used to
10855                specialize R.  */
10856             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
10857             argvec = tsubst_template_args (DECL_TI_ARGS
10858                                           (DECL_TEMPLATE_RESULT
10859                                                  (DECL_TI_TEMPLATE (t))),
10860                                            args, complain, in_decl);
10861             if (argvec == error_mark_node)
10862               RETURN (error_mark_node);
10863
10864             /* Check to see if we already have this specialization.  */
10865             hash = hash_tmpl_and_args (gen_tmpl, argvec);
10866             spec = retrieve_specialization (gen_tmpl, argvec, hash);
10867
10868             if (spec)
10869               {
10870                 r = spec;
10871                 break;
10872               }
10873
10874             /* We can see more levels of arguments than parameters if
10875                there was a specialization of a member template, like
10876                this:
10877
10878                  template <class T> struct S { template <class U> void f(); }
10879                  template <> template <class U> void S<int>::f(U);
10880
10881                Here, we'll be substituting into the specialization,
10882                because that's where we can find the code we actually
10883                want to generate, but we'll have enough arguments for
10884                the most general template.
10885
10886                We also deal with the peculiar case:
10887
10888                  template <class T> struct S {
10889                    template <class U> friend void f();
10890                  };
10891                  template <class U> void f() {}
10892                  template S<int>;
10893                  template void f<double>();
10894
10895                Here, the ARGS for the instantiation of will be {int,
10896                double}.  But, we only need as many ARGS as there are
10897                levels of template parameters in CODE_PATTERN.  We are
10898                careful not to get fooled into reducing the ARGS in
10899                situations like:
10900
10901                  template <class T> struct S { template <class U> void f(U); }
10902                  template <class T> template <> void S<T>::f(int) {}
10903
10904                which we can spot because the pattern will be a
10905                specialization in this case.  */
10906             args_depth = TMPL_ARGS_DEPTH (args);
10907             parms_depth =
10908               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
10909             if (args_depth > parms_depth
10910                 && !DECL_TEMPLATE_SPECIALIZATION (t))
10911               args = get_innermost_template_args (args, parms_depth);
10912           }
10913         else
10914           {
10915             /* This special case arises when we have something like this:
10916
10917                  template <class T> struct S {
10918                    friend void f<int>(int, double);
10919                  };
10920
10921                Here, the DECL_TI_TEMPLATE for the friend declaration
10922                will be an IDENTIFIER_NODE.  We are being called from
10923                tsubst_friend_function, and we want only to create a
10924                new decl (R) with appropriate types so that we can call
10925                determine_specialization.  */
10926             gen_tmpl = NULL_TREE;
10927           }
10928
10929         if (DECL_CLASS_SCOPE_P (t))
10930           {
10931             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10932               member = 2;
10933             else
10934               member = 1;
10935             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10936                                     complain, t, /*entering_scope=*/1);
10937           }
10938         else
10939           {
10940             member = 0;
10941             ctx = DECL_CONTEXT (t);
10942           }
10943         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10944         if (type == error_mark_node)
10945           RETURN (error_mark_node);
10946
10947         /* If we hit excessive deduction depth, the type is bogus even if
10948            it isn't error_mark_node, so don't build a decl.  */
10949         if (excessive_deduction_depth)
10950           RETURN (error_mark_node);
10951
10952         /* We do NOT check for matching decls pushed separately at this
10953            point, as they may not represent instantiations of this
10954            template, and in any case are considered separate under the
10955            discrete model.  */
10956         r = copy_decl (t);
10957         DECL_USE_TEMPLATE (r) = 0;
10958         TREE_TYPE (r) = type;
10959         /* Clear out the mangled name and RTL for the instantiation.  */
10960         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10961         SET_DECL_RTL (r, NULL);
10962         /* Leave DECL_INITIAL set on deleted instantiations.  */
10963         if (!DECL_DELETED_FN (r))
10964           DECL_INITIAL (r) = NULL_TREE;
10965         DECL_CONTEXT (r) = ctx;
10966
10967         /* OpenMP UDRs have the only argument a reference to the declared
10968            type.  We want to diagnose if the declared type is a reference,
10969            which is invalid, but as references to references are usually
10970            quietly merged, diagnose it here.  */
10971         if (DECL_OMP_DECLARE_REDUCTION_P (t))
10972           {
10973             tree argtype
10974               = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
10975             argtype = tsubst (argtype, args, complain, in_decl);
10976             if (TREE_CODE (argtype) == REFERENCE_TYPE)
10977               error_at (DECL_SOURCE_LOCATION (t),
10978                         "reference type %qT in "
10979                         "%<#pragma omp declare reduction%>", argtype);
10980             if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
10981               DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
10982                                                 argtype);
10983           }
10984
10985         if (member && DECL_CONV_FN_P (r))
10986           /* Type-conversion operator.  Reconstruct the name, in
10987              case it's the name of one of the template's parameters.  */
10988           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10989
10990         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10991                                      complain, t);
10992         DECL_RESULT (r) = NULL_TREE;
10993
10994         TREE_STATIC (r) = 0;
10995         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10996         DECL_EXTERNAL (r) = 1;
10997         /* If this is an instantiation of a function with internal
10998            linkage, we already know what object file linkage will be
10999            assigned to the instantiation.  */
11000         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
11001         DECL_DEFER_OUTPUT (r) = 0;
11002         DECL_CHAIN (r) = NULL_TREE;
11003         DECL_PENDING_INLINE_INFO (r) = 0;
11004         DECL_PENDING_INLINE_P (r) = 0;
11005         DECL_SAVED_TREE (r) = NULL_TREE;
11006         DECL_STRUCT_FUNCTION (r) = NULL;
11007         TREE_USED (r) = 0;
11008         /* We'll re-clone as appropriate in instantiate_template.  */
11009         DECL_CLONED_FUNCTION (r) = NULL_TREE;
11010
11011         /* If we aren't complaining now, return on error before we register
11012            the specialization so that we'll complain eventually.  */
11013         if ((complain & tf_error) == 0
11014             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
11015             && !grok_op_properties (r, /*complain=*/false))
11016           RETURN (error_mark_node);
11017
11018         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
11019            this in the special friend case mentioned above where
11020            GEN_TMPL is NULL.  */
11021         if (gen_tmpl)
11022           {
11023             DECL_TEMPLATE_INFO (r)
11024               = build_template_info (gen_tmpl, argvec);
11025             SET_DECL_IMPLICIT_INSTANTIATION (r);
11026
11027             tree new_r
11028               = register_specialization (r, gen_tmpl, argvec, false, hash);
11029             if (new_r != r)
11030               /* We instantiated this while substituting into
11031                  the type earlier (template/friend54.C).  */
11032               RETURN (new_r);
11033
11034             /* We're not supposed to instantiate default arguments
11035                until they are called, for a template.  But, for a
11036                declaration like:
11037
11038                  template <class T> void f ()
11039                  { extern void g(int i = T()); }
11040
11041                we should do the substitution when the template is
11042                instantiated.  We handle the member function case in
11043                instantiate_class_template since the default arguments
11044                might refer to other members of the class.  */
11045             if (!member
11046                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
11047                 && !uses_template_parms (argvec))
11048               tsubst_default_arguments (r, complain);
11049           }
11050         else
11051           DECL_TEMPLATE_INFO (r) = NULL_TREE;
11052
11053         /* Copy the list of befriending classes.  */
11054         for (friends = &DECL_BEFRIENDING_CLASSES (r);
11055              *friends;
11056              friends = &TREE_CHAIN (*friends))
11057           {
11058             *friends = copy_node (*friends);
11059             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
11060                                             args, complain,
11061                                             in_decl);
11062           }
11063
11064         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
11065           {
11066             maybe_retrofit_in_chrg (r);
11067             if (DECL_CONSTRUCTOR_P (r))
11068               grok_ctor_properties (ctx, r);
11069             if (DECL_INHERITED_CTOR_BASE (r))
11070               deduce_inheriting_ctor (r);
11071             /* If this is an instantiation of a member template, clone it.
11072                If it isn't, that'll be handled by
11073                clone_constructors_and_destructors.  */
11074             if (PRIMARY_TEMPLATE_P (gen_tmpl))
11075               clone_function_decl (r, /*update_method_vec_p=*/0);
11076           }
11077         else if ((complain & tf_error) != 0
11078                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
11079                  && !grok_op_properties (r, /*complain=*/true))
11080           RETURN (error_mark_node);
11081
11082         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
11083           SET_DECL_FRIEND_CONTEXT (r,
11084                                    tsubst (DECL_FRIEND_CONTEXT (t),
11085                                             args, complain, in_decl));
11086
11087         /* Possibly limit visibility based on template args.  */
11088         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
11089         if (DECL_VISIBILITY_SPECIFIED (t))
11090           {
11091             DECL_VISIBILITY_SPECIFIED (r) = 0;
11092             DECL_ATTRIBUTES (r)
11093               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
11094           }
11095         determine_visibility (r);
11096         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
11097             && !processing_template_decl)
11098           defaulted_late_check (r);
11099
11100         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
11101                                         args, complain, in_decl);
11102       }
11103       break;
11104
11105     case PARM_DECL:
11106       {
11107         tree type = NULL_TREE;
11108         int i, len = 1;
11109         tree expanded_types = NULL_TREE;
11110         tree prev_r = NULL_TREE;
11111         tree first_r = NULL_TREE;
11112
11113         if (DECL_PACK_P (t))
11114           {
11115             /* If there is a local specialization that isn't a
11116                parameter pack, it means that we're doing a "simple"
11117                substitution from inside tsubst_pack_expansion. Just
11118                return the local specialization (which will be a single
11119                parm).  */
11120             tree spec = retrieve_local_specialization (t);
11121             if (spec 
11122                 && TREE_CODE (spec) == PARM_DECL
11123                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
11124               RETURN (spec);
11125
11126             /* Expand the TYPE_PACK_EXPANSION that provides the types for
11127                the parameters in this function parameter pack.  */
11128             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
11129                                                     complain, in_decl);
11130             if (TREE_CODE (expanded_types) == TREE_VEC)
11131               {
11132                 len = TREE_VEC_LENGTH (expanded_types);
11133
11134                 /* Zero-length parameter packs are boring. Just substitute
11135                    into the chain.  */
11136                 if (len == 0)
11137                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
11138                                   TREE_CHAIN (t)));
11139               }
11140             else
11141               {
11142                 /* All we did was update the type. Make a note of that.  */
11143                 type = expanded_types;
11144                 expanded_types = NULL_TREE;
11145               }
11146           }
11147
11148         /* Loop through all of the parameters we'll build. When T is
11149            a function parameter pack, LEN is the number of expanded
11150            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
11151         r = NULL_TREE;
11152         for (i = 0; i < len; ++i)
11153           {
11154             prev_r = r;
11155             r = copy_node (t);
11156             if (DECL_TEMPLATE_PARM_P (t))
11157               SET_DECL_TEMPLATE_PARM_P (r);
11158
11159             if (expanded_types)
11160               /* We're on the Ith parameter of the function parameter
11161                  pack.  */
11162               {
11163                 /* Get the Ith type.  */
11164                 type = TREE_VEC_ELT (expanded_types, i);
11165
11166                 /* Rename the parameter to include the index.  */
11167                 DECL_NAME (r)
11168                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
11169               }
11170             else if (!type)
11171               /* We're dealing with a normal parameter.  */
11172               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11173
11174             type = type_decays_to (type);
11175             TREE_TYPE (r) = type;
11176             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
11177
11178             if (DECL_INITIAL (r))
11179               {
11180                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
11181                   DECL_INITIAL (r) = TREE_TYPE (r);
11182                 else
11183                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
11184                                              complain, in_decl);
11185               }
11186
11187             DECL_CONTEXT (r) = NULL_TREE;
11188
11189             if (!DECL_TEMPLATE_PARM_P (r))
11190               DECL_ARG_TYPE (r) = type_passed_as (type);
11191
11192             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
11193                                             args, complain, in_decl);
11194
11195             /* Keep track of the first new parameter we
11196                generate. That's what will be returned to the
11197                caller.  */
11198             if (!first_r)
11199               first_r = r;
11200
11201             /* Build a proper chain of parameters when substituting
11202                into a function parameter pack.  */
11203             if (prev_r)
11204               DECL_CHAIN (prev_r) = r;
11205           }
11206
11207         /* If cp_unevaluated_operand is set, we're just looking for a
11208            single dummy parameter, so don't keep going.  */
11209         if (DECL_CHAIN (t) && !cp_unevaluated_operand)
11210           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
11211                                    complain, DECL_CHAIN (t));
11212
11213         /* FIRST_R contains the start of the chain we've built.  */
11214         r = first_r;
11215       }
11216       break;
11217
11218     case FIELD_DECL:
11219       {
11220         tree type = NULL_TREE;
11221         tree vec = NULL_TREE;
11222         tree expanded_types = NULL_TREE;
11223         int len = 1;
11224
11225         if (PACK_EXPANSION_P (TREE_TYPE (t)))
11226           {
11227             /* This field is a lambda capture pack.  Return a TREE_VEC of
11228                the expanded fields to instantiate_class_template_1 and
11229                store them in the specializations hash table as a
11230                NONTYPE_ARGUMENT_PACK so that tsubst_copy can find them.  */
11231             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
11232                                                     complain, in_decl);
11233             if (TREE_CODE (expanded_types) == TREE_VEC)
11234               {
11235                 len = TREE_VEC_LENGTH (expanded_types);
11236                 vec = make_tree_vec (len);
11237               }
11238             else
11239               {
11240                 /* All we did was update the type. Make a note of that.  */
11241                 type = expanded_types;
11242                 expanded_types = NULL_TREE;
11243               }
11244           }
11245
11246         for (int i = 0; i < len; ++i)
11247           {
11248             r = copy_decl (t);
11249             if (expanded_types)
11250               {
11251                 type = TREE_VEC_ELT (expanded_types, i);
11252                 DECL_NAME (r)
11253                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
11254               }
11255             else if (!type)
11256               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11257
11258             if (type == error_mark_node)
11259               RETURN (error_mark_node);
11260             TREE_TYPE (r) = type;
11261             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
11262
11263             if (DECL_C_BIT_FIELD (r))
11264               /* For bit-fields, DECL_INITIAL gives the number of bits.  For
11265                  non-bit-fields DECL_INITIAL is a non-static data member
11266                  initializer, which gets deferred instantiation.  */
11267               DECL_INITIAL (r)
11268                 = tsubst_expr (DECL_INITIAL (t), args,
11269                                complain, in_decl,
11270                                /*integral_constant_expression_p=*/true);
11271             else if (DECL_INITIAL (t))
11272               {
11273                 /* Set up DECL_TEMPLATE_INFO so that we can get at the
11274                    NSDMI in perform_member_init.  Still set DECL_INITIAL
11275                    so that we know there is one.  */
11276                 DECL_INITIAL (r) = void_node;
11277                 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
11278                 retrofit_lang_decl (r);
11279                 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
11280               }
11281             /* We don't have to set DECL_CONTEXT here; it is set by
11282                finish_member_declaration.  */
11283             DECL_CHAIN (r) = NULL_TREE;
11284
11285             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
11286                                             args, complain, in_decl);
11287
11288             if (vec)
11289               TREE_VEC_ELT (vec, i) = r;
11290           }
11291
11292         if (vec)
11293           {
11294             r = vec;
11295             tree pack = make_node (NONTYPE_ARGUMENT_PACK);
11296             tree tpack = cxx_make_type (TYPE_ARGUMENT_PACK);
11297             SET_ARGUMENT_PACK_ARGS (pack, vec);
11298             SET_ARGUMENT_PACK_ARGS (tpack, expanded_types);
11299             TREE_TYPE (pack) = tpack;
11300             register_specialization (pack, t, args, false, 0);
11301           }
11302       }
11303       break;
11304
11305     case USING_DECL:
11306       /* We reach here only for member using decls.  We also need to check
11307          uses_template_parms because DECL_DEPENDENT_P is not set for a
11308          using-declaration that designates a member of the current
11309          instantiation (c++/53549).  */
11310       if (DECL_DEPENDENT_P (t)
11311           || uses_template_parms (USING_DECL_SCOPE (t)))
11312         {
11313           tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
11314                                          complain, in_decl);
11315           tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
11316           r = do_class_using_decl (inst_scope, name);
11317           if (!r)
11318             r = error_mark_node;
11319           else
11320             {
11321               TREE_PROTECTED (r) = TREE_PROTECTED (t);
11322               TREE_PRIVATE (r) = TREE_PRIVATE (t);
11323             }
11324         }
11325       else
11326         {
11327           r = copy_node (t);
11328           DECL_CHAIN (r) = NULL_TREE;
11329         }
11330       break;
11331
11332     case TYPE_DECL:
11333     case VAR_DECL:
11334       {
11335         tree argvec = NULL_TREE;
11336         tree gen_tmpl = NULL_TREE;
11337         tree spec;
11338         tree tmpl = NULL_TREE;
11339         tree ctx;
11340         tree type = NULL_TREE;
11341         bool local_p;
11342
11343         if (TREE_TYPE (t) == error_mark_node)
11344           RETURN (error_mark_node);
11345
11346         if (TREE_CODE (t) == TYPE_DECL
11347             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
11348           {
11349             /* If this is the canonical decl, we don't have to
11350                mess with instantiations, and often we can't (for
11351                typename, template type parms and such).  Note that
11352                TYPE_NAME is not correct for the above test if
11353                we've copied the type for a typedef.  */
11354             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11355             if (type == error_mark_node)
11356               RETURN (error_mark_node);
11357             r = TYPE_NAME (type);
11358             break;
11359           }
11360
11361         /* Check to see if we already have the specialization we
11362            need.  */
11363         spec = NULL_TREE;
11364         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
11365           {
11366             /* T is a static data member or namespace-scope entity.
11367                We have to substitute into namespace-scope variables
11368                (not just variable templates) because of cases like:
11369                
11370                  template <class T> void f() { extern T t; }
11371
11372                where the entity referenced is not known until
11373                instantiation time.  */
11374             local_p = false;
11375             ctx = DECL_CONTEXT (t);
11376             if (DECL_CLASS_SCOPE_P (t))
11377               {
11378                 ctx = tsubst_aggr_type (ctx, args,
11379                                         complain,
11380                                         in_decl, /*entering_scope=*/1);
11381                 /* If CTX is unchanged, then T is in fact the
11382                    specialization we want.  That situation occurs when
11383                    referencing a static data member within in its own
11384                    class.  We can use pointer equality, rather than
11385                    same_type_p, because DECL_CONTEXT is always
11386                    canonical...  */
11387                 if (ctx == DECL_CONTEXT (t)
11388                     /* ... unless T is a member template; in which
11389                        case our caller can be willing to create a
11390                        specialization of that template represented
11391                        by T.  */
11392                     && !(DECL_TI_TEMPLATE (t)
11393                          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
11394                   spec = t;
11395               }
11396
11397             if (!spec)
11398               {
11399                 tmpl = DECL_TI_TEMPLATE (t);
11400                 gen_tmpl = most_general_template (tmpl);
11401                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
11402                 if (argvec != error_mark_node)
11403                   argvec = (coerce_innermost_template_parms
11404                             (DECL_TEMPLATE_PARMS (gen_tmpl),
11405                              argvec, t, complain,
11406                              /*all*/true, /*defarg*/true));
11407                 if (argvec == error_mark_node)
11408                   RETURN (error_mark_node);
11409                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
11410                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
11411               }
11412           }
11413         else
11414           {
11415             /* A local variable.  */
11416             local_p = true;
11417             /* Subsequent calls to pushdecl will fill this in.  */
11418             ctx = NULL_TREE;
11419             spec = retrieve_local_specialization (t);
11420           }
11421         /* If we already have the specialization we need, there is
11422            nothing more to do.  */ 
11423         if (spec)
11424           {
11425             r = spec;
11426             break;
11427           }
11428
11429         /* Create a new node for the specialization we need.  */
11430         r = copy_decl (t);
11431         if (type == NULL_TREE)
11432           {
11433             if (is_typedef_decl (t))
11434               type = DECL_ORIGINAL_TYPE (t);
11435             else
11436               type = TREE_TYPE (t);
11437             if (VAR_P (t)
11438                 && VAR_HAD_UNKNOWN_BOUND (t)
11439                 && type != error_mark_node)
11440               type = strip_array_domain (type);
11441             type = tsubst (type, args, complain, in_decl);
11442           }
11443         if (VAR_P (r))
11444           {
11445             /* Even if the original location is out of scope, the
11446                newly substituted one is not.  */
11447             DECL_DEAD_FOR_LOCAL (r) = 0;
11448             DECL_INITIALIZED_P (r) = 0;
11449             DECL_TEMPLATE_INSTANTIATED (r) = 0;
11450             if (type == error_mark_node)
11451               RETURN (error_mark_node);
11452             if (TREE_CODE (type) == FUNCTION_TYPE)
11453               {
11454                 /* It may seem that this case cannot occur, since:
11455
11456                    typedef void f();
11457                    void g() { f x; }
11458
11459                    declares a function, not a variable.  However:
11460       
11461                    typedef void f();
11462                    template <typename T> void g() { T t; }
11463                    template void g<f>();
11464
11465                    is an attempt to declare a variable with function
11466                    type.  */
11467                 error ("variable %qD has function type",
11468                        /* R is not yet sufficiently initialized, so we
11469                           just use its name.  */
11470                        DECL_NAME (r));
11471                 RETURN (error_mark_node);
11472               }
11473             type = complete_type (type);
11474             /* Wait until cp_finish_decl to set this again, to handle
11475                circular dependency (template/instantiate6.C). */
11476             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
11477             type = check_var_type (DECL_NAME (r), type);
11478
11479             if (DECL_HAS_VALUE_EXPR_P (t))
11480               {
11481                 tree ve = DECL_VALUE_EXPR (t);
11482                 ve = tsubst_expr (ve, args, complain, in_decl,
11483                                   /*constant_expression_p=*/false);
11484                 if (REFERENCE_REF_P (ve))
11485                   {
11486                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
11487                     ve = TREE_OPERAND (ve, 0);
11488                   }
11489                 SET_DECL_VALUE_EXPR (r, ve);
11490               }
11491             if (TREE_STATIC (r) || DECL_EXTERNAL (r))
11492               set_decl_tls_model (r, decl_tls_model (t));
11493           }
11494         else if (DECL_SELF_REFERENCE_P (t))
11495           SET_DECL_SELF_REFERENCE_P (r);
11496         TREE_TYPE (r) = type;
11497         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
11498         DECL_CONTEXT (r) = ctx;
11499         /* Clear out the mangled name and RTL for the instantiation.  */
11500         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
11501         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
11502           SET_DECL_RTL (r, NULL);
11503         /* The initializer must not be expanded until it is required;
11504            see [temp.inst].  */
11505         DECL_INITIAL (r) = NULL_TREE;
11506         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
11507           SET_DECL_RTL (r, NULL);
11508         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
11509         if (VAR_P (r))
11510           {
11511             /* Possibly limit visibility based on template args.  */
11512             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
11513             if (DECL_VISIBILITY_SPECIFIED (t))
11514               {
11515                 DECL_VISIBILITY_SPECIFIED (r) = 0;
11516                 DECL_ATTRIBUTES (r)
11517                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
11518               }
11519             determine_visibility (r);
11520           }
11521
11522         if (!local_p)
11523           {
11524             /* A static data member declaration is always marked
11525                external when it is declared in-class, even if an
11526                initializer is present.  We mimic the non-template
11527                processing here.  */
11528             DECL_EXTERNAL (r) = 1;
11529             if (DECL_NAMESPACE_SCOPE_P (t))
11530               DECL_NOT_REALLY_EXTERN (r) = 1;
11531
11532             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
11533             SET_DECL_IMPLICIT_INSTANTIATION (r);
11534             register_specialization (r, gen_tmpl, argvec, false, hash);
11535           }
11536         else if (!cp_unevaluated_operand)
11537           register_local_specialization (r, t);
11538
11539         DECL_CHAIN (r) = NULL_TREE;
11540
11541         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
11542                                         /*flags=*/0,
11543                                         args, complain, in_decl);
11544
11545         /* Preserve a typedef that names a type.  */
11546         if (is_typedef_decl (r))
11547           {
11548             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
11549             set_underlying_type (r);
11550           }
11551
11552         layout_decl (r, 0);
11553       }
11554       break;
11555
11556     default:
11557       gcc_unreachable ();
11558     }
11559 #undef RETURN
11560
11561  out:
11562   /* Restore the file and line information.  */
11563   input_location = saved_loc;
11564
11565   return r;
11566 }
11567
11568 /* Substitute into the ARG_TYPES of a function type.
11569    If END is a TREE_CHAIN, leave it and any following types
11570    un-substituted.  */
11571
11572 static tree
11573 tsubst_arg_types (tree arg_types,
11574                   tree args,
11575                   tree end,
11576                   tsubst_flags_t complain,
11577                   tree in_decl)
11578 {
11579   tree remaining_arg_types;
11580   tree type = NULL_TREE;
11581   int i = 1;
11582   tree expanded_args = NULL_TREE;
11583   tree default_arg;
11584
11585   if (!arg_types || arg_types == void_list_node || arg_types == end)
11586     return arg_types;
11587
11588   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
11589                                           args, end, complain, in_decl);
11590   if (remaining_arg_types == error_mark_node)
11591     return error_mark_node;
11592
11593   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
11594     {
11595       /* For a pack expansion, perform substitution on the
11596          entire expression. Later on, we'll handle the arguments
11597          one-by-one.  */
11598       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
11599                                             args, complain, in_decl);
11600
11601       if (TREE_CODE (expanded_args) == TREE_VEC)
11602         /* So that we'll spin through the parameters, one by one.  */
11603         i = TREE_VEC_LENGTH (expanded_args);
11604       else
11605         {
11606           /* We only partially substituted into the parameter
11607              pack. Our type is TYPE_PACK_EXPANSION.  */
11608           type = expanded_args;
11609           expanded_args = NULL_TREE;
11610         }
11611     }
11612
11613   while (i > 0) {
11614     --i;
11615     
11616     if (expanded_args)
11617       type = TREE_VEC_ELT (expanded_args, i);
11618     else if (!type)
11619       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
11620
11621     if (type == error_mark_node)
11622       return error_mark_node;
11623     if (VOID_TYPE_P (type))
11624       {
11625         if (complain & tf_error)
11626           {
11627             error ("invalid parameter type %qT", type);
11628             if (in_decl)
11629               error ("in declaration %q+D", in_decl);
11630           }
11631         return error_mark_node;
11632     }
11633     /* DR 657. */
11634     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
11635       return error_mark_node;
11636     
11637     /* Do array-to-pointer, function-to-pointer conversion, and ignore
11638        top-level qualifiers as required.  */
11639     type = cv_unqualified (type_decays_to (type));
11640
11641     /* We do not substitute into default arguments here.  The standard
11642        mandates that they be instantiated only when needed, which is
11643        done in build_over_call.  */
11644     default_arg = TREE_PURPOSE (arg_types);
11645
11646     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
11647       {
11648         /* We've instantiated a template before its default arguments
11649            have been parsed.  This can happen for a nested template
11650            class, and is not an error unless we require the default
11651            argument in a call of this function.  */
11652         remaining_arg_types = 
11653           tree_cons (default_arg, type, remaining_arg_types);
11654         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
11655       }
11656     else
11657       remaining_arg_types = 
11658         hash_tree_cons (default_arg, type, remaining_arg_types);
11659   }
11660         
11661   return remaining_arg_types;
11662 }
11663
11664 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
11665    *not* handle the exception-specification for FNTYPE, because the
11666    initial substitution of explicitly provided template parameters
11667    during argument deduction forbids substitution into the
11668    exception-specification:
11669
11670      [temp.deduct]
11671
11672      All references in the function type of the function template to  the
11673      corresponding template parameters are replaced by the specified tem-
11674      plate argument values.  If a substitution in a template parameter or
11675      in  the function type of the function template results in an invalid
11676      type, type deduction fails.  [Note: The equivalent  substitution  in
11677      exception specifications is done only when the function is instanti-
11678      ated, at which point a program is  ill-formed  if  the  substitution
11679      results in an invalid type.]  */
11680
11681 static tree
11682 tsubst_function_type (tree t,
11683                       tree args,
11684                       tsubst_flags_t complain,
11685                       tree in_decl)
11686 {
11687   tree return_type;
11688   tree arg_types = NULL_TREE;
11689   tree fntype;
11690
11691   /* The TYPE_CONTEXT is not used for function/method types.  */
11692   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
11693
11694   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
11695      failure.  */
11696   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
11697
11698   if (late_return_type_p)
11699     {
11700       /* Substitute the argument types.  */
11701       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
11702                                     complain, in_decl);
11703       if (arg_types == error_mark_node)
11704         return error_mark_node;
11705
11706       tree save_ccp = current_class_ptr;
11707       tree save_ccr = current_class_ref;
11708       tree this_type = (TREE_CODE (t) == METHOD_TYPE
11709                         ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
11710       bool do_inject = this_type && CLASS_TYPE_P (this_type);
11711       if (do_inject)
11712         {
11713           /* DR 1207: 'this' is in scope in the trailing return type.  */
11714           inject_this_parameter (this_type, cp_type_quals (this_type));
11715         }
11716
11717       /* Substitute the return type.  */
11718       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11719
11720       if (do_inject)
11721         {
11722           current_class_ptr = save_ccp;
11723           current_class_ref = save_ccr;
11724         }
11725     }
11726   else
11727     /* Substitute the return type.  */
11728     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11729
11730   if (return_type == error_mark_node)
11731     return error_mark_node;
11732   /* DR 486 clarifies that creation of a function type with an
11733      invalid return type is a deduction failure.  */
11734   if (TREE_CODE (return_type) == ARRAY_TYPE
11735       || TREE_CODE (return_type) == FUNCTION_TYPE)
11736     {
11737       if (complain & tf_error)
11738         {
11739           if (TREE_CODE (return_type) == ARRAY_TYPE)
11740             error ("function returning an array");
11741           else
11742             error ("function returning a function");
11743         }
11744       return error_mark_node;
11745     }
11746   /* And DR 657. */
11747   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
11748     return error_mark_node;
11749
11750   if (!late_return_type_p)
11751     {
11752       /* Substitute the argument types.  */
11753       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
11754                                     complain, in_decl);
11755       if (arg_types == error_mark_node)
11756         return error_mark_node;
11757     }
11758
11759   /* Construct a new type node and return it.  */
11760   if (TREE_CODE (t) == FUNCTION_TYPE)
11761     {
11762       fntype = build_function_type (return_type, arg_types);
11763       fntype = apply_memfn_quals (fntype,
11764                                   type_memfn_quals (t),
11765                                   type_memfn_rqual (t));
11766     }
11767   else
11768     {
11769       tree r = TREE_TYPE (TREE_VALUE (arg_types));
11770       /* Don't pick up extra function qualifiers from the basetype.  */
11771       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
11772       if (! MAYBE_CLASS_TYPE_P (r))
11773         {
11774           /* [temp.deduct]
11775
11776              Type deduction may fail for any of the following
11777              reasons:
11778
11779              -- Attempting to create "pointer to member of T" when T
11780              is not a class type.  */
11781           if (complain & tf_error)
11782             error ("creating pointer to member function of non-class type %qT",
11783                       r);
11784           return error_mark_node;
11785         }
11786
11787       fntype = build_method_type_directly (r, return_type,
11788                                            TREE_CHAIN (arg_types));
11789       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
11790     }
11791   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
11792
11793   if (late_return_type_p)
11794     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
11795
11796   return fntype;
11797 }
11798
11799 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
11800    ARGS into that specification, and return the substituted
11801    specification.  If there is no specification, return NULL_TREE.  */
11802
11803 static tree
11804 tsubst_exception_specification (tree fntype,
11805                                 tree args,
11806                                 tsubst_flags_t complain,
11807                                 tree in_decl,
11808                                 bool defer_ok)
11809 {
11810   tree specs;
11811   tree new_specs;
11812
11813   specs = TYPE_RAISES_EXCEPTIONS (fntype);
11814   new_specs = NULL_TREE;
11815   if (specs && TREE_PURPOSE (specs))
11816     {
11817       /* A noexcept-specifier.  */
11818       tree expr = TREE_PURPOSE (specs);
11819       if (TREE_CODE (expr) == INTEGER_CST)
11820         new_specs = expr;
11821       else if (defer_ok)
11822         {
11823           /* Defer instantiation of noexcept-specifiers to avoid
11824              excessive instantiations (c++/49107).  */
11825           new_specs = make_node (DEFERRED_NOEXCEPT);
11826           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
11827             {
11828               /* We already partially instantiated this member template,
11829                  so combine the new args with the old.  */
11830               DEFERRED_NOEXCEPT_PATTERN (new_specs)
11831                 = DEFERRED_NOEXCEPT_PATTERN (expr);
11832               DEFERRED_NOEXCEPT_ARGS (new_specs)
11833                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
11834             }
11835           else
11836             {
11837               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
11838               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
11839             }
11840         }
11841       else
11842         new_specs = tsubst_copy_and_build
11843           (expr, args, complain, in_decl, /*function_p=*/false,
11844            /*integral_constant_expression_p=*/true);
11845       new_specs = build_noexcept_spec (new_specs, complain);
11846     }
11847   else if (specs)
11848     {
11849       if (! TREE_VALUE (specs))
11850         new_specs = specs;
11851       else
11852         while (specs)
11853           {
11854             tree spec;
11855             int i, len = 1;
11856             tree expanded_specs = NULL_TREE;
11857
11858             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
11859               {
11860                 /* Expand the pack expansion type.  */
11861                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
11862                                                        args, complain,
11863                                                        in_decl);
11864
11865                 if (expanded_specs == error_mark_node)
11866                   return error_mark_node;
11867                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
11868                   len = TREE_VEC_LENGTH (expanded_specs);
11869                 else
11870                   {
11871                     /* We're substituting into a member template, so
11872                        we got a TYPE_PACK_EXPANSION back.  Add that
11873                        expansion and move on.  */
11874                     gcc_assert (TREE_CODE (expanded_specs) 
11875                                 == TYPE_PACK_EXPANSION);
11876                     new_specs = add_exception_specifier (new_specs,
11877                                                          expanded_specs,
11878                                                          complain);
11879                     specs = TREE_CHAIN (specs);
11880                     continue;
11881                   }
11882               }
11883
11884             for (i = 0; i < len; ++i)
11885               {
11886                 if (expanded_specs)
11887                   spec = TREE_VEC_ELT (expanded_specs, i);
11888                 else
11889                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
11890                 if (spec == error_mark_node)
11891                   return spec;
11892                 new_specs = add_exception_specifier (new_specs, spec, 
11893                                                      complain);
11894               }
11895
11896             specs = TREE_CHAIN (specs);
11897           }
11898     }
11899   return new_specs;
11900 }
11901
11902 /* Take the tree structure T and replace template parameters used
11903    therein with the argument vector ARGS.  IN_DECL is an associated
11904    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
11905    Issue error and warning messages under control of COMPLAIN.  Note
11906    that we must be relatively non-tolerant of extensions here, in
11907    order to preserve conformance; if we allow substitutions that
11908    should not be allowed, we may allow argument deductions that should
11909    not succeed, and therefore report ambiguous overload situations
11910    where there are none.  In theory, we could allow the substitution,
11911    but indicate that it should have failed, and allow our caller to
11912    make sure that the right thing happens, but we don't try to do this
11913    yet.
11914
11915    This function is used for dealing with types, decls and the like;
11916    for expressions, use tsubst_expr or tsubst_copy.  */
11917
11918 tree
11919 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11920 {
11921   enum tree_code code;
11922   tree type, r = NULL_TREE;
11923
11924   if (t == NULL_TREE || t == error_mark_node
11925       || t == integer_type_node
11926       || t == void_type_node
11927       || t == char_type_node
11928       || t == unknown_type_node
11929       || TREE_CODE (t) == NAMESPACE_DECL
11930       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
11931     return t;
11932
11933   if (DECL_P (t))
11934     return tsubst_decl (t, args, complain);
11935
11936   if (args == NULL_TREE)
11937     return t;
11938
11939   code = TREE_CODE (t);
11940
11941   if (code == IDENTIFIER_NODE)
11942     type = IDENTIFIER_TYPE_VALUE (t);
11943   else
11944     type = TREE_TYPE (t);
11945
11946   gcc_assert (type != unknown_type_node);
11947
11948   /* Reuse typedefs.  We need to do this to handle dependent attributes,
11949      such as attribute aligned.  */
11950   if (TYPE_P (t)
11951       && typedef_variant_p (t))
11952     {
11953       tree decl = TYPE_NAME (t);
11954
11955       if (alias_template_specialization_p (t))
11956         {
11957           /* DECL represents an alias template and we want to
11958              instantiate it.  */
11959           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11960           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11961           r = instantiate_alias_template (tmpl, gen_args, complain);
11962         }
11963       else if (DECL_CLASS_SCOPE_P (decl)
11964                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
11965                && uses_template_parms (DECL_CONTEXT (decl)))
11966         {
11967           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11968           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11969           r = retrieve_specialization (tmpl, gen_args, 0);
11970         }
11971       else if (DECL_FUNCTION_SCOPE_P (decl)
11972                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
11973                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
11974         r = retrieve_local_specialization (decl);
11975       else
11976         /* The typedef is from a non-template context.  */
11977         return t;
11978
11979       if (r)
11980         {
11981           r = TREE_TYPE (r);
11982           r = cp_build_qualified_type_real
11983             (r, cp_type_quals (t) | cp_type_quals (r),
11984              complain | tf_ignore_bad_quals);
11985           return r;
11986         }
11987       else
11988         {
11989           /* We don't have an instantiation yet, so drop the typedef.  */
11990           int quals = cp_type_quals (t);
11991           t = DECL_ORIGINAL_TYPE (decl);
11992           t = cp_build_qualified_type_real (t, quals,
11993                                             complain | tf_ignore_bad_quals);
11994         }
11995     }
11996
11997   if (type
11998       && code != TYPENAME_TYPE
11999       && code != TEMPLATE_TYPE_PARM
12000       && code != IDENTIFIER_NODE
12001       && code != FUNCTION_TYPE
12002       && code != METHOD_TYPE)
12003     type = tsubst (type, args, complain, in_decl);
12004   if (type == error_mark_node)
12005     return error_mark_node;
12006
12007   switch (code)
12008     {
12009     case RECORD_TYPE:
12010     case UNION_TYPE:
12011     case ENUMERAL_TYPE:
12012       return tsubst_aggr_type (t, args, complain, in_decl,
12013                                /*entering_scope=*/0);
12014
12015     case ERROR_MARK:
12016     case IDENTIFIER_NODE:
12017     case VOID_TYPE:
12018     case REAL_TYPE:
12019     case COMPLEX_TYPE:
12020     case VECTOR_TYPE:
12021     case BOOLEAN_TYPE:
12022     case NULLPTR_TYPE:
12023     case LANG_TYPE:
12024       return t;
12025
12026     case INTEGER_TYPE:
12027       if (t == integer_type_node)
12028         return t;
12029
12030       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
12031           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
12032         return t;
12033
12034       {
12035         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
12036
12037         max = tsubst_expr (omax, args, complain, in_decl,
12038                            /*integral_constant_expression_p=*/false);
12039
12040         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
12041            needed.  */
12042         if (TREE_CODE (max) == NOP_EXPR
12043             && TREE_SIDE_EFFECTS (omax)
12044             && !TREE_TYPE (max))
12045           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
12046
12047         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
12048            with TREE_SIDE_EFFECTS that indicates this is not an integral
12049            constant expression.  */
12050         if (processing_template_decl
12051             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
12052           {
12053             gcc_assert (TREE_CODE (max) == NOP_EXPR);
12054             TREE_SIDE_EFFECTS (max) = 1;
12055           }
12056
12057         return compute_array_index_type (NULL_TREE, max, complain);
12058       }
12059
12060     case TEMPLATE_TYPE_PARM:
12061     case TEMPLATE_TEMPLATE_PARM:
12062     case BOUND_TEMPLATE_TEMPLATE_PARM:
12063     case TEMPLATE_PARM_INDEX:
12064       {
12065         int idx;
12066         int level;
12067         int levels;
12068         tree arg = NULL_TREE;
12069
12070         r = NULL_TREE;
12071
12072         gcc_assert (TREE_VEC_LENGTH (args) > 0);
12073         template_parm_level_and_index (t, &level, &idx); 
12074
12075         levels = TMPL_ARGS_DEPTH (args);
12076         if (level <= levels)
12077           {
12078             arg = TMPL_ARG (args, level, idx);
12079
12080             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
12081               {
12082                 /* See through ARGUMENT_PACK_SELECT arguments. */
12083                 arg = ARGUMENT_PACK_SELECT_ARG (arg);
12084                 /* If the selected argument is an expansion E, that most
12085                    likely means we were called from
12086                    gen_elem_of_pack_expansion_instantiation during the
12087                    substituting of pack an argument pack (which Ith
12088                    element is a pack expansion, where I is
12089                    ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
12090                    In this case, the Ith element resulting from this
12091                    substituting is going to be a pack expansion, which
12092                    pattern is the pattern of E.  Let's return the
12093                    pattern of E, and
12094                    gen_elem_of_pack_expansion_instantiation will
12095                    build the resulting pack expansion from it.  */
12096                 if (PACK_EXPANSION_P (arg))
12097                   {
12098                     /* Make sure we aren't throwing away arg info.  */
12099                     gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
12100                     arg = PACK_EXPANSION_PATTERN (arg);
12101                   }
12102               }
12103           }
12104
12105         if (arg == error_mark_node)
12106           return error_mark_node;
12107         else if (arg != NULL_TREE)
12108           {
12109             if (ARGUMENT_PACK_P (arg))
12110               /* If ARG is an argument pack, we don't actually want to
12111                  perform a substitution here, because substitutions
12112                  for argument packs are only done
12113                  element-by-element. We can get to this point when
12114                  substituting the type of a non-type template
12115                  parameter pack, when that type actually contains
12116                  template parameter packs from an outer template, e.g.,
12117
12118                  template<typename... Types> struct A {
12119                    template<Types... Values> struct B { };
12120                  };  */
12121               return t;
12122
12123             if (code == TEMPLATE_TYPE_PARM)
12124               {
12125                 int quals;
12126                 gcc_assert (TYPE_P (arg));
12127
12128                 quals = cp_type_quals (arg) | cp_type_quals (t);
12129                   
12130                 return cp_build_qualified_type_real
12131                   (arg, quals, complain | tf_ignore_bad_quals);
12132               }
12133             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
12134               {
12135                 /* We are processing a type constructed from a
12136                    template template parameter.  */
12137                 tree argvec = tsubst (TYPE_TI_ARGS (t),
12138                                       args, complain, in_decl);
12139                 if (argvec == error_mark_node)
12140                   return error_mark_node;
12141
12142                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
12143                             || TREE_CODE (arg) == TEMPLATE_DECL
12144                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
12145
12146                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
12147                   /* Consider this code:
12148
12149                         template <template <class> class Template>
12150                         struct Internal {
12151                         template <class Arg> using Bind = Template<Arg>;
12152                         };
12153
12154                         template <template <class> class Template, class Arg>
12155                         using Instantiate = Template<Arg>; //#0
12156
12157                         template <template <class> class Template,
12158                                   class Argument>
12159                         using Bind =
12160                           Instantiate<Internal<Template>::template Bind,
12161                                       Argument>; //#1
12162
12163                      When #1 is parsed, the
12164                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
12165                      parameter `Template' in #0 matches the
12166                      UNBOUND_CLASS_TEMPLATE representing the argument
12167                      `Internal<Template>::template Bind'; We then want
12168                      to assemble the type `Bind<Argument>' that can't
12169                      be fully created right now, because
12170                      `Internal<Template>' not being complete, the Bind
12171                      template cannot be looked up in that context.  So
12172                      we need to "store" `Bind<Argument>' for later
12173                      when the context of Bind becomes complete.  Let's
12174                      store that in a TYPENAME_TYPE.  */
12175                   return make_typename_type (TYPE_CONTEXT (arg),
12176                                              build_nt (TEMPLATE_ID_EXPR,
12177                                                        TYPE_IDENTIFIER (arg),
12178                                                        argvec),
12179                                              typename_type,
12180                                              complain);
12181
12182                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
12183                    are resolving nested-types in the signature of a
12184                    member function templates.  Otherwise ARG is a
12185                    TEMPLATE_DECL and is the real template to be
12186                    instantiated.  */
12187                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
12188                   arg = TYPE_NAME (arg);
12189
12190                 r = lookup_template_class (arg,
12191                                            argvec, in_decl,
12192                                            DECL_CONTEXT (arg),
12193                                             /*entering_scope=*/0,
12194                                            complain);
12195                 return cp_build_qualified_type_real
12196                   (r, cp_type_quals (t) | cp_type_quals (r), complain);
12197               }
12198             else
12199               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
12200               return convert_from_reference (unshare_expr (arg));
12201           }
12202
12203         if (level == 1)
12204           /* This can happen during the attempted tsubst'ing in
12205              unify.  This means that we don't yet have any information
12206              about the template parameter in question.  */
12207           return t;
12208
12209         /* Early in template argument deduction substitution, we don't
12210            want to reduce the level of 'auto', or it will be confused
12211            with a normal template parm in subsequent deduction.  */
12212         if (is_auto (t) && (complain & tf_partial))
12213           return t;
12214
12215         /* If we get here, we must have been looking at a parm for a
12216            more deeply nested template.  Make a new version of this
12217            template parameter, but with a lower level.  */
12218         switch (code)
12219           {
12220           case TEMPLATE_TYPE_PARM:
12221           case TEMPLATE_TEMPLATE_PARM:
12222           case BOUND_TEMPLATE_TEMPLATE_PARM:
12223             if (cp_type_quals (t))
12224               {
12225                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
12226                 r = cp_build_qualified_type_real
12227                   (r, cp_type_quals (t),
12228                    complain | (code == TEMPLATE_TYPE_PARM
12229                                ? tf_ignore_bad_quals : 0));
12230               }
12231             else
12232               {
12233                 r = copy_type (t);
12234                 TEMPLATE_TYPE_PARM_INDEX (r)
12235                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
12236                                                 r, levels, args, complain);
12237                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
12238                 TYPE_MAIN_VARIANT (r) = r;
12239                 TYPE_POINTER_TO (r) = NULL_TREE;
12240                 TYPE_REFERENCE_TO (r) = NULL_TREE;
12241
12242                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
12243                   /* We have reduced the level of the template
12244                      template parameter, but not the levels of its
12245                      template parameters, so canonical_type_parameter
12246                      will not be able to find the canonical template
12247                      template parameter for this level. Thus, we
12248                      require structural equality checking to compare
12249                      TEMPLATE_TEMPLATE_PARMs. */
12250                   SET_TYPE_STRUCTURAL_EQUALITY (r);
12251                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
12252                   SET_TYPE_STRUCTURAL_EQUALITY (r);
12253                 else
12254                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
12255
12256                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
12257                   {
12258                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
12259                                           complain, in_decl);
12260                     if (argvec == error_mark_node)
12261                       return error_mark_node;
12262
12263                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
12264                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
12265                   }
12266               }
12267             break;
12268
12269           case TEMPLATE_PARM_INDEX:
12270             r = reduce_template_parm_level (t, type, levels, args, complain);
12271             break;
12272
12273           default:
12274             gcc_unreachable ();
12275           }
12276
12277         return r;
12278       }
12279
12280     case TREE_LIST:
12281       {
12282         tree purpose, value, chain;
12283
12284         if (t == void_list_node)
12285           return t;
12286
12287         purpose = TREE_PURPOSE (t);
12288         if (purpose)
12289           {
12290             purpose = tsubst (purpose, args, complain, in_decl);
12291             if (purpose == error_mark_node)
12292               return error_mark_node;
12293           }
12294         value = TREE_VALUE (t);
12295         if (value)
12296           {
12297             value = tsubst (value, args, complain, in_decl);
12298             if (value == error_mark_node)
12299               return error_mark_node;
12300           }
12301         chain = TREE_CHAIN (t);
12302         if (chain && chain != void_type_node)
12303           {
12304             chain = tsubst (chain, args, complain, in_decl);
12305             if (chain == error_mark_node)
12306               return error_mark_node;
12307           }
12308         if (purpose == TREE_PURPOSE (t)
12309             && value == TREE_VALUE (t)
12310             && chain == TREE_CHAIN (t))
12311           return t;
12312         return hash_tree_cons (purpose, value, chain);
12313       }
12314
12315     case TREE_BINFO:
12316       /* We should never be tsubsting a binfo.  */
12317       gcc_unreachable ();
12318
12319     case TREE_VEC:
12320       /* A vector of template arguments.  */
12321       gcc_assert (!type);
12322       return tsubst_template_args (t, args, complain, in_decl);
12323
12324     case POINTER_TYPE:
12325     case REFERENCE_TYPE:
12326       {
12327         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
12328           return t;
12329
12330         /* [temp.deduct]
12331
12332            Type deduction may fail for any of the following
12333            reasons:
12334
12335            -- Attempting to create a pointer to reference type.
12336            -- Attempting to create a reference to a reference type or
12337               a reference to void.
12338
12339           Core issue 106 says that creating a reference to a reference
12340           during instantiation is no longer a cause for failure. We
12341           only enforce this check in strict C++98 mode.  */
12342         if ((TREE_CODE (type) == REFERENCE_TYPE
12343              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
12344             || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
12345           {
12346             static location_t last_loc;
12347
12348             /* We keep track of the last time we issued this error
12349                message to avoid spewing a ton of messages during a
12350                single bad template instantiation.  */
12351             if (complain & tf_error
12352                 && last_loc != input_location)
12353               {
12354                 if (VOID_TYPE_P (type))
12355                   error ("forming reference to void");
12356                else if (code == POINTER_TYPE)
12357                  error ("forming pointer to reference type %qT", type);
12358                else
12359                   error ("forming reference to reference type %qT", type);
12360                 last_loc = input_location;
12361               }
12362
12363             return error_mark_node;
12364           }
12365         else if (TREE_CODE (type) == FUNCTION_TYPE
12366                  && (type_memfn_quals (type) != TYPE_UNQUALIFIED
12367                      || type_memfn_rqual (type) != REF_QUAL_NONE))
12368           {
12369             if (complain & tf_error)
12370               {
12371                 if (code == POINTER_TYPE)
12372                   error ("forming pointer to qualified function type %qT",
12373                          type);
12374                 else
12375                   error ("forming reference to qualified function type %qT",
12376                          type);
12377               }
12378             return error_mark_node;
12379           }
12380         else if (code == POINTER_TYPE)
12381           {
12382             r = build_pointer_type (type);
12383             if (TREE_CODE (type) == METHOD_TYPE)
12384               r = build_ptrmemfunc_type (r);
12385           }
12386         else if (TREE_CODE (type) == REFERENCE_TYPE)
12387           /* In C++0x, during template argument substitution, when there is an
12388              attempt to create a reference to a reference type, reference
12389              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
12390
12391              "If a template-argument for a template-parameter T names a type
12392              that is a reference to a type A, an attempt to create the type
12393              'lvalue reference to cv T' creates the type 'lvalue reference to
12394              A,' while an attempt to create the type type rvalue reference to
12395              cv T' creates the type T"
12396           */
12397           r = cp_build_reference_type
12398               (TREE_TYPE (type),
12399                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
12400         else
12401           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
12402         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12403
12404         if (r != error_mark_node)
12405           /* Will this ever be needed for TYPE_..._TO values?  */
12406           layout_type (r);
12407
12408         return r;
12409       }
12410     case OFFSET_TYPE:
12411       {
12412         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
12413         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
12414           {
12415             /* [temp.deduct]
12416
12417                Type deduction may fail for any of the following
12418                reasons:
12419
12420                -- Attempting to create "pointer to member of T" when T
12421                   is not a class type.  */
12422             if (complain & tf_error)
12423               error ("creating pointer to member of non-class type %qT", r);
12424             return error_mark_node;
12425           }
12426         if (TREE_CODE (type) == REFERENCE_TYPE)
12427           {
12428             if (complain & tf_error)
12429               error ("creating pointer to member reference type %qT", type);
12430             return error_mark_node;
12431           }
12432         if (VOID_TYPE_P (type))
12433           {
12434             if (complain & tf_error)
12435               error ("creating pointer to member of type void");
12436             return error_mark_node;
12437           }
12438         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
12439         if (TREE_CODE (type) == FUNCTION_TYPE)
12440           {
12441             /* The type of the implicit object parameter gets its
12442                cv-qualifiers from the FUNCTION_TYPE. */
12443             tree memptr;
12444             tree method_type
12445               = build_memfn_type (type, r, type_memfn_quals (type),
12446                                   type_memfn_rqual (type));
12447             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
12448             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
12449                                                  complain);
12450           }
12451         else
12452           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
12453                                                cp_type_quals (t),
12454                                                complain);
12455       }
12456     case FUNCTION_TYPE:
12457     case METHOD_TYPE:
12458       {
12459         tree fntype;
12460         tree specs;
12461         fntype = tsubst_function_type (t, args, complain, in_decl);
12462         if (fntype == error_mark_node)
12463           return error_mark_node;
12464
12465         /* Substitute the exception specification.  */
12466         specs = tsubst_exception_specification (t, args, complain,
12467                                                 in_decl, /*defer_ok*/true);
12468         if (specs == error_mark_node)
12469           return error_mark_node;
12470         if (specs)
12471           fntype = build_exception_variant (fntype, specs);
12472         return fntype;
12473       }
12474     case ARRAY_TYPE:
12475       {
12476         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
12477         if (domain == error_mark_node)
12478           return error_mark_node;
12479
12480         /* As an optimization, we avoid regenerating the array type if
12481            it will obviously be the same as T.  */
12482         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
12483           return t;
12484
12485         /* These checks should match the ones in create_array_type_for_decl.
12486
12487            [temp.deduct]
12488
12489            The deduction may fail for any of the following reasons:
12490
12491            -- Attempting to create an array with an element type that
12492               is void, a function type, or a reference type, or [DR337]
12493               an abstract class type.  */
12494         if (VOID_TYPE_P (type)
12495             || TREE_CODE (type) == FUNCTION_TYPE
12496             || (TREE_CODE (type) == ARRAY_TYPE
12497                 && TYPE_DOMAIN (type) == NULL_TREE)
12498             || TREE_CODE (type) == REFERENCE_TYPE)
12499           {
12500             if (complain & tf_error)
12501               error ("creating array of %qT", type);
12502             return error_mark_node;
12503           }
12504
12505         if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
12506           return error_mark_node;
12507
12508         r = build_cplus_array_type (type, domain);
12509
12510         if (TYPE_USER_ALIGN (t))
12511           {
12512             TYPE_ALIGN (r) = TYPE_ALIGN (t);
12513             TYPE_USER_ALIGN (r) = 1;
12514           }
12515
12516         return r;
12517       }
12518
12519     case TYPENAME_TYPE:
12520       {
12521         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
12522                                      in_decl, /*entering_scope=*/1);
12523         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
12524                               complain, in_decl);
12525
12526         if (ctx == error_mark_node || f == error_mark_node)
12527           return error_mark_node;
12528
12529         if (!MAYBE_CLASS_TYPE_P (ctx))
12530           {
12531             if (complain & tf_error)
12532               error ("%qT is not a class, struct, or union type", ctx);
12533             return error_mark_node;
12534           }
12535         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
12536           {
12537             /* Normally, make_typename_type does not require that the CTX
12538                have complete type in order to allow things like:
12539
12540                  template <class T> struct S { typename S<T>::X Y; };
12541
12542                But, such constructs have already been resolved by this
12543                point, so here CTX really should have complete type, unless
12544                it's a partial instantiation.  */
12545             ctx = complete_type (ctx);
12546             if (!COMPLETE_TYPE_P (ctx))
12547               {
12548                 if (complain & tf_error)
12549                   cxx_incomplete_type_error (NULL_TREE, ctx);
12550                 return error_mark_node;
12551               }
12552           }
12553
12554         f = make_typename_type (ctx, f, typename_type,
12555                                 complain | tf_keep_type_decl);
12556         if (f == error_mark_node)
12557           return f;
12558         if (TREE_CODE (f) == TYPE_DECL)
12559           {
12560             complain |= tf_ignore_bad_quals;
12561             f = TREE_TYPE (f);
12562           }
12563
12564         if (TREE_CODE (f) != TYPENAME_TYPE)
12565           {
12566             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
12567               {
12568                 if (complain & tf_error)
12569                   error ("%qT resolves to %qT, which is not an enumeration type",
12570                          t, f);
12571                 else
12572                   return error_mark_node;
12573               }
12574             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
12575               {
12576                 if (complain & tf_error)
12577                   error ("%qT resolves to %qT, which is is not a class type",
12578                          t, f);
12579                 else
12580                   return error_mark_node;
12581               }
12582           }
12583
12584         return cp_build_qualified_type_real
12585           (f, cp_type_quals (f) | cp_type_quals (t), complain);
12586       }
12587
12588     case UNBOUND_CLASS_TEMPLATE:
12589       {
12590         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
12591                                      in_decl, /*entering_scope=*/1);
12592         tree name = TYPE_IDENTIFIER (t);
12593         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
12594
12595         if (ctx == error_mark_node || name == error_mark_node)
12596           return error_mark_node;
12597
12598         if (parm_list)
12599           parm_list = tsubst_template_parms (parm_list, args, complain);
12600         return make_unbound_class_template (ctx, name, parm_list, complain);
12601       }
12602
12603     case TYPEOF_TYPE:
12604       {
12605         tree type;
12606
12607         ++cp_unevaluated_operand;
12608         ++c_inhibit_evaluation_warnings;
12609
12610         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
12611                             complain, in_decl,
12612                             /*integral_constant_expression_p=*/false);
12613
12614         --cp_unevaluated_operand;
12615         --c_inhibit_evaluation_warnings;
12616
12617         type = finish_typeof (type);
12618         return cp_build_qualified_type_real (type,
12619                                              cp_type_quals (t)
12620                                              | cp_type_quals (type),
12621                                              complain);
12622       }
12623
12624     case DECLTYPE_TYPE:
12625       {
12626         tree type;
12627
12628         ++cp_unevaluated_operand;
12629         ++c_inhibit_evaluation_warnings;
12630
12631         type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
12632                                       complain|tf_decltype, in_decl,
12633                                       /*function_p*/false,
12634                                       /*integral_constant_expression*/false);
12635
12636         --cp_unevaluated_operand;
12637         --c_inhibit_evaluation_warnings;
12638
12639         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
12640           type = lambda_capture_field_type (type,
12641                                             DECLTYPE_FOR_INIT_CAPTURE (t));
12642         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
12643           type = lambda_proxy_type (type);
12644         else
12645           {
12646             bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
12647             if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
12648                 && EXPR_P (type))
12649               /* In a template ~id could be either a complement expression
12650                  or an unqualified-id naming a destructor; if instantiating
12651                  it produces an expression, it's not an id-expression or
12652                  member access.  */
12653               id = false;
12654             type = finish_decltype_type (type, id, complain);
12655           }
12656         return cp_build_qualified_type_real (type,
12657                                              cp_type_quals (t)
12658                                              | cp_type_quals (type),
12659                                              complain | tf_ignore_bad_quals);
12660       }
12661
12662     case UNDERLYING_TYPE:
12663       {
12664         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
12665                             complain, in_decl);
12666         return finish_underlying_type (type);
12667       }
12668
12669     case TYPE_ARGUMENT_PACK:
12670     case NONTYPE_ARGUMENT_PACK:
12671       {
12672         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
12673         tree packed_out = 
12674           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
12675                                 args,
12676                                 complain,
12677                                 in_decl);
12678         SET_ARGUMENT_PACK_ARGS (r, packed_out);
12679
12680         /* For template nontype argument packs, also substitute into
12681            the type.  */
12682         if (code == NONTYPE_ARGUMENT_PACK)
12683           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
12684
12685         return r;
12686       }
12687       break;
12688
12689     case VOID_CST:
12690     case INTEGER_CST:
12691     case REAL_CST:
12692     case STRING_CST:
12693     case PLUS_EXPR:
12694     case MINUS_EXPR:
12695     case NEGATE_EXPR:
12696     case NOP_EXPR:
12697     case INDIRECT_REF:
12698     case ADDR_EXPR:
12699     case CALL_EXPR:
12700     case ARRAY_REF:
12701     case SCOPE_REF:
12702       /* We should use one of the expression tsubsts for these codes.  */
12703       gcc_unreachable ();
12704
12705     default:
12706       sorry ("use of %qs in template", get_tree_code_name (code));
12707       return error_mark_node;
12708     }
12709 }
12710
12711 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
12712    type of the expression on the left-hand side of the "." or "->"
12713    operator.  */
12714
12715 static tree
12716 tsubst_baselink (tree baselink, tree object_type,
12717                  tree args, tsubst_flags_t complain, tree in_decl)
12718 {
12719     tree name;
12720     tree qualifying_scope;
12721     tree fns;
12722     tree optype;
12723     tree template_args = 0;
12724     bool template_id_p = false;
12725     bool qualified = BASELINK_QUALIFIED_P (baselink);
12726
12727     /* A baselink indicates a function from a base class.  Both the
12728        BASELINK_ACCESS_BINFO and the base class referenced may
12729        indicate bases of the template class, rather than the
12730        instantiated class.  In addition, lookups that were not
12731        ambiguous before may be ambiguous now.  Therefore, we perform
12732        the lookup again.  */
12733     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
12734     qualifying_scope = tsubst (qualifying_scope, args,
12735                                complain, in_decl);
12736     fns = BASELINK_FUNCTIONS (baselink);
12737     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
12738     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
12739       {
12740         template_id_p = true;
12741         template_args = TREE_OPERAND (fns, 1);
12742         fns = TREE_OPERAND (fns, 0);
12743         if (template_args)
12744           template_args = tsubst_template_args (template_args, args,
12745                                                 complain, in_decl);
12746       }
12747     name = DECL_NAME (get_first_fn (fns));
12748     if (IDENTIFIER_TYPENAME_P (name))
12749       name = mangle_conv_op_name_for_type (optype);
12750     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
12751     if (!baselink)
12752       return error_mark_node;
12753
12754     /* If lookup found a single function, mark it as used at this
12755        point.  (If it lookup found multiple functions the one selected
12756        later by overload resolution will be marked as used at that
12757        point.)  */
12758     if (BASELINK_P (baselink))
12759       fns = BASELINK_FUNCTIONS (baselink);
12760     if (!template_id_p && !really_overloaded_fn (fns))
12761       mark_used (OVL_CURRENT (fns));
12762
12763     /* Add back the template arguments, if present.  */
12764     if (BASELINK_P (baselink) && template_id_p)
12765       BASELINK_FUNCTIONS (baselink)
12766         = build_nt (TEMPLATE_ID_EXPR,
12767                     BASELINK_FUNCTIONS (baselink),
12768                     template_args);
12769     /* Update the conversion operator type.  */
12770     BASELINK_OPTYPE (baselink) = optype;
12771
12772     if (!object_type)
12773       object_type = current_class_type;
12774
12775     if (qualified)
12776       baselink = adjust_result_of_qualified_name_lookup (baselink,
12777                                                          qualifying_scope,
12778                                                          object_type);
12779     return baselink;
12780 }
12781
12782 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
12783    true if the qualified-id will be a postfix-expression in-and-of
12784    itself; false if more of the postfix-expression follows the
12785    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
12786    of "&".  */
12787
12788 static tree
12789 tsubst_qualified_id (tree qualified_id, tree args,
12790                      tsubst_flags_t complain, tree in_decl,
12791                      bool done, bool address_p)
12792 {
12793   tree expr;
12794   tree scope;
12795   tree name;
12796   bool is_template;
12797   tree template_args;
12798   location_t loc = UNKNOWN_LOCATION;
12799
12800   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
12801
12802   /* Figure out what name to look up.  */
12803   name = TREE_OPERAND (qualified_id, 1);
12804   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
12805     {
12806       is_template = true;
12807       loc = EXPR_LOCATION (name);
12808       template_args = TREE_OPERAND (name, 1);
12809       if (template_args)
12810         template_args = tsubst_template_args (template_args, args,
12811                                               complain, in_decl);
12812       name = TREE_OPERAND (name, 0);
12813     }
12814   else
12815     {
12816       is_template = false;
12817       template_args = NULL_TREE;
12818     }
12819
12820   /* Substitute into the qualifying scope.  When there are no ARGS, we
12821      are just trying to simplify a non-dependent expression.  In that
12822      case the qualifying scope may be dependent, and, in any case,
12823      substituting will not help.  */
12824   scope = TREE_OPERAND (qualified_id, 0);
12825   if (args)
12826     {
12827       scope = tsubst (scope, args, complain, in_decl);
12828       expr = tsubst_copy (name, args, complain, in_decl);
12829     }
12830   else
12831     expr = name;
12832
12833   if (dependent_scope_p (scope))
12834     {
12835       if (is_template)
12836         expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
12837       return build_qualified_name (NULL_TREE, scope, expr,
12838                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
12839     }
12840
12841   if (!BASELINK_P (name) && !DECL_P (expr))
12842     {
12843       if (TREE_CODE (expr) == BIT_NOT_EXPR)
12844         {
12845           /* A BIT_NOT_EXPR is used to represent a destructor.  */
12846           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
12847             {
12848               error ("qualifying type %qT does not match destructor name ~%qT",
12849                      scope, TREE_OPERAND (expr, 0));
12850               expr = error_mark_node;
12851             }
12852           else
12853             expr = lookup_qualified_name (scope, complete_dtor_identifier,
12854                                           /*is_type_p=*/0, false);
12855         }
12856       else
12857         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
12858       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
12859                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
12860         {
12861           if (complain & tf_error)
12862             {
12863               error ("dependent-name %qE is parsed as a non-type, but "
12864                      "instantiation yields a type", qualified_id);
12865               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
12866             }
12867           return error_mark_node;
12868         }
12869     }
12870
12871   if (DECL_P (expr))
12872     {
12873       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
12874                                            scope);
12875       /* Remember that there was a reference to this entity.  */
12876       mark_used (expr);
12877     }
12878
12879   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
12880     {
12881       if (complain & tf_error)
12882         qualified_name_lookup_error (scope,
12883                                      TREE_OPERAND (qualified_id, 1),
12884                                      expr, input_location);
12885       return error_mark_node;
12886     }
12887
12888   if (is_template)
12889     expr = lookup_template_function (expr, template_args);
12890
12891   if (expr == error_mark_node && complain & tf_error)
12892     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
12893                                  expr, input_location);
12894   else if (TYPE_P (scope))
12895     {
12896       expr = (adjust_result_of_qualified_name_lookup
12897               (expr, scope, current_nonlambda_class_type ()));
12898       expr = (finish_qualified_id_expr
12899               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
12900                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
12901                /*template_arg_p=*/false, complain));
12902     }
12903
12904   /* Expressions do not generally have reference type.  */
12905   if (TREE_CODE (expr) != SCOPE_REF
12906       /* However, if we're about to form a pointer-to-member, we just
12907          want the referenced member referenced.  */
12908       && TREE_CODE (expr) != OFFSET_REF)
12909     expr = convert_from_reference (expr);
12910
12911   return expr;
12912 }
12913
12914 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
12915    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
12916    for tsubst.  */
12917
12918 static tree
12919 tsubst_init (tree init, tree decl, tree args,
12920              tsubst_flags_t complain, tree in_decl)
12921 {
12922   if (!init)
12923     return NULL_TREE;
12924
12925   init = tsubst_expr (init, args, complain, in_decl, false);
12926
12927   if (!init)
12928     {
12929       /* If we had an initializer but it
12930          instantiated to nothing,
12931          value-initialize the object.  This will
12932          only occur when the initializer was a
12933          pack expansion where the parameter packs
12934          used in that expansion were of length
12935          zero.  */
12936       init = build_value_init (TREE_TYPE (decl),
12937                                complain);
12938       if (TREE_CODE (init) == AGGR_INIT_EXPR)
12939         init = get_target_expr_sfinae (init, complain);
12940     }
12941
12942   return init;
12943 }
12944
12945 /* Like tsubst, but deals with expressions.  This function just replaces
12946    template parms; to finish processing the resultant expression, use
12947    tsubst_copy_and_build or tsubst_expr.  */
12948
12949 static tree
12950 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12951 {
12952   enum tree_code code;
12953   tree r;
12954
12955   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
12956     return t;
12957
12958   code = TREE_CODE (t);
12959
12960   switch (code)
12961     {
12962     case PARM_DECL:
12963       r = retrieve_local_specialization (t);
12964
12965       if (r == NULL_TREE)
12966         {
12967           /* We get here for a use of 'this' in an NSDMI.  */
12968           if (DECL_NAME (t) == this_identifier
12969               && current_function_decl
12970               && DECL_CONSTRUCTOR_P (current_function_decl))
12971             return current_class_ptr;
12972
12973           /* This can happen for a parameter name used later in a function
12974              declaration (such as in a late-specified return type).  Just
12975              make a dummy decl, since it's only used for its type.  */
12976           gcc_assert (cp_unevaluated_operand != 0);
12977           r = tsubst_decl (t, args, complain);
12978           /* Give it the template pattern as its context; its true context
12979              hasn't been instantiated yet and this is good enough for
12980              mangling.  */
12981           DECL_CONTEXT (r) = DECL_CONTEXT (t);
12982         }
12983       
12984       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
12985         r = ARGUMENT_PACK_SELECT_ARG (r);
12986       mark_used (r);
12987       return r;
12988
12989     case CONST_DECL:
12990       {
12991         tree enum_type;
12992         tree v;
12993
12994         if (DECL_TEMPLATE_PARM_P (t))
12995           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
12996         /* There is no need to substitute into namespace-scope
12997            enumerators.  */
12998         if (DECL_NAMESPACE_SCOPE_P (t))
12999           return t;
13000         /* If ARGS is NULL, then T is known to be non-dependent.  */
13001         if (args == NULL_TREE)
13002           return scalar_constant_value (t);
13003
13004         /* Unfortunately, we cannot just call lookup_name here.
13005            Consider:
13006
13007              template <int I> int f() {
13008              enum E { a = I };
13009              struct S { void g() { E e = a; } };
13010              };
13011
13012            When we instantiate f<7>::S::g(), say, lookup_name is not
13013            clever enough to find f<7>::a.  */
13014         enum_type
13015           = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
13016                               /*entering_scope=*/0);
13017
13018         for (v = TYPE_VALUES (enum_type);
13019              v != NULL_TREE;
13020              v = TREE_CHAIN (v))
13021           if (TREE_PURPOSE (v) == DECL_NAME (t))
13022             return TREE_VALUE (v);
13023
13024           /* We didn't find the name.  That should never happen; if
13025              name-lookup found it during preliminary parsing, we
13026              should find it again here during instantiation.  */
13027         gcc_unreachable ();
13028       }
13029       return t;
13030
13031     case FIELD_DECL:
13032       if (PACK_EXPANSION_P (TREE_TYPE (t)))
13033         {
13034           /* Check for a local specialization set up by
13035              tsubst_pack_expansion.  */
13036           if (tree r = retrieve_local_specialization (t))
13037             {
13038               if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
13039                 r = ARGUMENT_PACK_SELECT_ARG (r);
13040               return r;
13041             }
13042
13043           /* When retrieving a capture pack from a generic lambda, remove the
13044              lambda call op's own template argument list from ARGS.  Only the
13045              template arguments active for the closure type should be used to
13046              retrieve the pack specialization.  */
13047           if (LAMBDA_FUNCTION_P (current_function_decl)
13048               && (template_class_depth (DECL_CONTEXT (t))
13049                   != TMPL_ARGS_DEPTH (args)))
13050             args = strip_innermost_template_args (args, 1);
13051
13052           /* Otherwise return the full NONTYPE_ARGUMENT_PACK that
13053              tsubst_decl put in the hash table.  */
13054           return retrieve_specialization (t, args, 0);
13055         }
13056
13057       if (DECL_CONTEXT (t))
13058         {
13059           tree ctx;
13060
13061           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
13062                                   /*entering_scope=*/1);
13063           if (ctx != DECL_CONTEXT (t))
13064             {
13065               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
13066               if (!r)
13067                 {
13068                   if (complain & tf_error)
13069                     error ("using invalid field %qD", t);
13070                   return error_mark_node;
13071                 }
13072               return r;
13073             }
13074         }
13075
13076       return t;
13077
13078     case VAR_DECL:
13079     case FUNCTION_DECL:
13080       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
13081         r = tsubst (t, args, complain, in_decl);
13082       else if (local_variable_p (t))
13083         {
13084           r = retrieve_local_specialization (t);
13085           if (r == NULL_TREE)
13086             {
13087               /* First try name lookup to find the instantiation.  */
13088               r = lookup_name (DECL_NAME (t));
13089               if (r)
13090                 {
13091                   /* Make sure that the one we found is the one we want.  */
13092                   tree ctx = tsubst (DECL_CONTEXT (t), args,
13093                                      complain, in_decl);
13094                   if (ctx != DECL_CONTEXT (r))
13095                     r = NULL_TREE;
13096                 }
13097
13098               if (r)
13099                 /* OK */;
13100               else
13101                 {
13102                   /* This can happen for a variable used in a
13103                      late-specified return type of a local lambda, or for a
13104                      local static or constant.  Building a new VAR_DECL
13105                      should be OK in all those cases.  */
13106                   r = tsubst_decl (t, args, complain);
13107                   if (decl_maybe_constant_var_p (r))
13108                     {
13109                       /* We can't call cp_finish_decl, so handle the
13110                          initializer by hand.  */
13111                       tree init = tsubst_init (DECL_INITIAL (t), r, args,
13112                                                complain, in_decl);
13113                       if (!processing_template_decl)
13114                         init = maybe_constant_init (init);
13115                       if (processing_template_decl
13116                           ? potential_constant_expression (init)
13117                           : reduced_constant_expression_p (init))
13118                         DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
13119                           = TREE_CONSTANT (r) = true;
13120                       DECL_INITIAL (r) = init;
13121                     }
13122                   gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
13123                               || decl_constant_var_p (r)
13124                               || errorcount || sorrycount);
13125                   if (!processing_template_decl)
13126                     {
13127                       if (TREE_STATIC (r))
13128                         rest_of_decl_compilation (r, toplevel_bindings_p (),
13129                                                   at_eof);
13130                       else
13131                         r = process_outer_var_ref (r, complain);
13132                     }
13133                 }
13134               /* Remember this for subsequent uses.  */
13135               if (local_specializations)
13136                 register_local_specialization (r, t);
13137             }
13138         }
13139       else
13140         r = t;
13141       mark_used (r);
13142       return r;
13143
13144     case NAMESPACE_DECL:
13145       return t;
13146
13147     case OVERLOAD:
13148       /* An OVERLOAD will always be a non-dependent overload set; an
13149          overload set from function scope will just be represented with an
13150          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
13151       gcc_assert (!uses_template_parms (t));
13152       return t;
13153
13154     case BASELINK:
13155       return tsubst_baselink (t, current_nonlambda_class_type (),
13156                               args, complain, in_decl);
13157
13158     case TEMPLATE_DECL:
13159       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13160         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
13161                        args, complain, in_decl);
13162       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
13163         return tsubst (t, args, complain, in_decl);
13164       else if (DECL_CLASS_SCOPE_P (t)
13165                && uses_template_parms (DECL_CONTEXT (t)))
13166         {
13167           /* Template template argument like the following example need
13168              special treatment:
13169
13170                template <template <class> class TT> struct C {};
13171                template <class T> struct D {
13172                  template <class U> struct E {};
13173                  C<E> c;                                // #1
13174                };
13175                D<int> d;                                // #2
13176
13177              We are processing the template argument `E' in #1 for
13178              the template instantiation #2.  Originally, `E' is a
13179              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
13180              have to substitute this with one having context `D<int>'.  */
13181
13182           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
13183           return lookup_field (context, DECL_NAME(t), 0, false);
13184         }
13185       else
13186         /* Ordinary template template argument.  */
13187         return t;
13188
13189     case CAST_EXPR:
13190     case REINTERPRET_CAST_EXPR:
13191     case CONST_CAST_EXPR:
13192     case STATIC_CAST_EXPR:
13193     case DYNAMIC_CAST_EXPR:
13194     case IMPLICIT_CONV_EXPR:
13195     case CONVERT_EXPR:
13196     case NOP_EXPR:
13197       {
13198         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13199         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13200         return build1 (code, type, op0);
13201       }
13202
13203     case SIZEOF_EXPR:
13204       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13205         {
13206
13207           tree expanded, op = TREE_OPERAND (t, 0);
13208           int len = 0;
13209
13210           if (SIZEOF_EXPR_TYPE_P (t))
13211             op = TREE_TYPE (op);
13212
13213           ++cp_unevaluated_operand;
13214           ++c_inhibit_evaluation_warnings;
13215           /* We only want to compute the number of arguments.  */
13216           expanded = tsubst_pack_expansion (op, args, complain, in_decl);
13217           --cp_unevaluated_operand;
13218           --c_inhibit_evaluation_warnings;
13219
13220           if (TREE_CODE (expanded) == TREE_VEC)
13221             len = TREE_VEC_LENGTH (expanded);
13222
13223           if (expanded == error_mark_node)
13224             return error_mark_node;
13225           else if (PACK_EXPANSION_P (expanded)
13226                    || (TREE_CODE (expanded) == TREE_VEC
13227                        && len > 0
13228                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
13229             {
13230               if (TREE_CODE (expanded) == TREE_VEC)
13231                 expanded = TREE_VEC_ELT (expanded, len - 1);
13232
13233               if (TYPE_P (expanded))
13234                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
13235                                                    complain & tf_error);
13236               else
13237                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
13238                                                    complain & tf_error);
13239             }
13240           else
13241             return build_int_cst (size_type_node, len);
13242         }
13243       if (SIZEOF_EXPR_TYPE_P (t))
13244         {
13245           r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
13246                       args, complain, in_decl);
13247           r = build1 (NOP_EXPR, r, error_mark_node);
13248           r = build1 (SIZEOF_EXPR,
13249                       tsubst (TREE_TYPE (t), args, complain, in_decl), r);
13250           SIZEOF_EXPR_TYPE_P (r) = 1;
13251           return r;
13252         }
13253       /* Fall through */
13254
13255     case INDIRECT_REF:
13256     case NEGATE_EXPR:
13257     case TRUTH_NOT_EXPR:
13258     case BIT_NOT_EXPR:
13259     case ADDR_EXPR:
13260     case UNARY_PLUS_EXPR:      /* Unary + */
13261     case ALIGNOF_EXPR:
13262     case AT_ENCODE_EXPR:
13263     case ARROW_EXPR:
13264     case THROW_EXPR:
13265     case TYPEID_EXPR:
13266     case REALPART_EXPR:
13267     case IMAGPART_EXPR:
13268     case PAREN_EXPR:
13269       {
13270         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13271         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13272         return build1 (code, type, op0);
13273       }
13274
13275     case COMPONENT_REF:
13276       {
13277         tree object;
13278         tree name;
13279
13280         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13281         name = TREE_OPERAND (t, 1);
13282         if (TREE_CODE (name) == BIT_NOT_EXPR)
13283           {
13284             name = tsubst_copy (TREE_OPERAND (name, 0), args,
13285                                 complain, in_decl);
13286             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
13287           }
13288         else if (TREE_CODE (name) == SCOPE_REF
13289                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
13290           {
13291             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
13292                                      complain, in_decl);
13293             name = TREE_OPERAND (name, 1);
13294             name = tsubst_copy (TREE_OPERAND (name, 0), args,
13295                                 complain, in_decl);
13296             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
13297             name = build_qualified_name (/*type=*/NULL_TREE,
13298                                          base, name,
13299                                          /*template_p=*/false);
13300           }
13301         else if (BASELINK_P (name))
13302           name = tsubst_baselink (name,
13303                                   non_reference (TREE_TYPE (object)),
13304                                   args, complain,
13305                                   in_decl);
13306         else
13307           name = tsubst_copy (name, args, complain, in_decl);
13308         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
13309       }
13310
13311     case PLUS_EXPR:
13312     case MINUS_EXPR:
13313     case MULT_EXPR:
13314     case TRUNC_DIV_EXPR:
13315     case CEIL_DIV_EXPR:
13316     case FLOOR_DIV_EXPR:
13317     case ROUND_DIV_EXPR:
13318     case EXACT_DIV_EXPR:
13319     case BIT_AND_EXPR:
13320     case BIT_IOR_EXPR:
13321     case BIT_XOR_EXPR:
13322     case TRUNC_MOD_EXPR:
13323     case FLOOR_MOD_EXPR:
13324     case TRUTH_ANDIF_EXPR:
13325     case TRUTH_ORIF_EXPR:
13326     case TRUTH_AND_EXPR:
13327     case TRUTH_OR_EXPR:
13328     case RSHIFT_EXPR:
13329     case LSHIFT_EXPR:
13330     case RROTATE_EXPR:
13331     case LROTATE_EXPR:
13332     case EQ_EXPR:
13333     case NE_EXPR:
13334     case MAX_EXPR:
13335     case MIN_EXPR:
13336     case LE_EXPR:
13337     case GE_EXPR:
13338     case LT_EXPR:
13339     case GT_EXPR:
13340     case COMPOUND_EXPR:
13341     case DOTSTAR_EXPR:
13342     case MEMBER_REF:
13343     case PREDECREMENT_EXPR:
13344     case PREINCREMENT_EXPR:
13345     case POSTDECREMENT_EXPR:
13346     case POSTINCREMENT_EXPR:
13347       {
13348         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13349         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13350         return build_nt (code, op0, op1);
13351       }
13352
13353     case SCOPE_REF:
13354       {
13355         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13356         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13357         return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
13358                                      QUALIFIED_NAME_IS_TEMPLATE (t));
13359       }
13360
13361     case ARRAY_REF:
13362       {
13363         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13364         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13365         return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
13366       }
13367
13368     case CALL_EXPR:
13369       {
13370         int n = VL_EXP_OPERAND_LENGTH (t);
13371         tree result = build_vl_exp (CALL_EXPR, n);
13372         int i;
13373         for (i = 0; i < n; i++)
13374           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
13375                                              complain, in_decl);
13376         return result;
13377       }
13378
13379     case COND_EXPR:
13380     case MODOP_EXPR:
13381     case PSEUDO_DTOR_EXPR:
13382     case VEC_PERM_EXPR:
13383       {
13384         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13385         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13386         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
13387         r = build_nt (code, op0, op1, op2);
13388         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13389         return r;
13390       }
13391
13392     case NEW_EXPR:
13393       {
13394         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13395         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13396         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
13397         r = build_nt (code, op0, op1, op2);
13398         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
13399         return r;
13400       }
13401
13402     case DELETE_EXPR:
13403       {
13404         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13405         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13406         r = build_nt (code, op0, op1);
13407         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
13408         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
13409         return r;
13410       }
13411
13412     case TEMPLATE_ID_EXPR:
13413       {
13414         /* Substituted template arguments */
13415         tree fn = TREE_OPERAND (t, 0);
13416         tree targs = TREE_OPERAND (t, 1);
13417
13418         fn = tsubst_copy (fn, args, complain, in_decl);
13419         if (targs)
13420           targs = tsubst_template_args (targs, args, complain, in_decl);
13421
13422         return lookup_template_function (fn, targs);
13423       }
13424
13425     case TREE_LIST:
13426       {
13427         tree purpose, value, chain;
13428
13429         if (t == void_list_node)
13430           return t;
13431
13432         purpose = TREE_PURPOSE (t);
13433         if (purpose)
13434           purpose = tsubst_copy (purpose, args, complain, in_decl);
13435         value = TREE_VALUE (t);
13436         if (value)
13437           value = tsubst_copy (value, args, complain, in_decl);
13438         chain = TREE_CHAIN (t);
13439         if (chain && chain != void_type_node)
13440           chain = tsubst_copy (chain, args, complain, in_decl);
13441         if (purpose == TREE_PURPOSE (t)
13442             && value == TREE_VALUE (t)
13443             && chain == TREE_CHAIN (t))
13444           return t;
13445         return tree_cons (purpose, value, chain);
13446       }
13447
13448     case RECORD_TYPE:
13449     case UNION_TYPE:
13450     case ENUMERAL_TYPE:
13451     case INTEGER_TYPE:
13452     case TEMPLATE_TYPE_PARM:
13453     case TEMPLATE_TEMPLATE_PARM:
13454     case BOUND_TEMPLATE_TEMPLATE_PARM:
13455     case TEMPLATE_PARM_INDEX:
13456     case POINTER_TYPE:
13457     case REFERENCE_TYPE:
13458     case OFFSET_TYPE:
13459     case FUNCTION_TYPE:
13460     case METHOD_TYPE:
13461     case ARRAY_TYPE:
13462     case TYPENAME_TYPE:
13463     case UNBOUND_CLASS_TEMPLATE:
13464     case TYPEOF_TYPE:
13465     case DECLTYPE_TYPE:
13466     case TYPE_DECL:
13467       return tsubst (t, args, complain, in_decl);
13468
13469     case USING_DECL:
13470       t = DECL_NAME (t);
13471       /* Fall through.  */
13472     case IDENTIFIER_NODE:
13473       if (IDENTIFIER_TYPENAME_P (t))
13474         {
13475           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13476           return mangle_conv_op_name_for_type (new_type);
13477         }
13478       else
13479         return t;
13480
13481     case CONSTRUCTOR:
13482       /* This is handled by tsubst_copy_and_build.  */
13483       gcc_unreachable ();
13484
13485     case VA_ARG_EXPR:
13486       {
13487         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13488         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13489         return build_x_va_arg (EXPR_LOCATION (t), op0, type);
13490       }
13491
13492     case CLEANUP_POINT_EXPR:
13493       /* We shouldn't have built any of these during initial template
13494          generation.  Instead, they should be built during instantiation
13495          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
13496       gcc_unreachable ();
13497
13498     case OFFSET_REF:
13499       {
13500         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13501         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13502         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13503         r = build2 (code, type, op0, op1);
13504         PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
13505         mark_used (TREE_OPERAND (r, 1));
13506         return r;
13507       }
13508
13509     case EXPR_PACK_EXPANSION:
13510       error ("invalid use of pack expansion expression");
13511       return error_mark_node;
13512
13513     case NONTYPE_ARGUMENT_PACK:
13514       error ("use %<...%> to expand argument pack");
13515       return error_mark_node;
13516
13517     case VOID_CST:
13518       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
13519       return t;
13520
13521     case INTEGER_CST:
13522     case REAL_CST:
13523     case STRING_CST:
13524     case COMPLEX_CST:
13525       {
13526         /* Instantiate any typedefs in the type.  */
13527         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13528         r = fold_convert (type, t);
13529         gcc_assert (TREE_CODE (r) == code);
13530         return r;
13531       }
13532
13533     case PTRMEM_CST:
13534       /* These can sometimes show up in a partial instantiation, but never
13535          involve template parms.  */
13536       gcc_assert (!uses_template_parms (t));
13537       return t;
13538
13539     default:
13540       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
13541       gcc_checking_assert (false);
13542       return t;
13543     }
13544 }
13545
13546 /* Helper function for tsubst_omp_clauses, used for instantiation of
13547    OMP_CLAUSE_DECL of clauses that handles also OpenMP array sections
13548    represented with TREE_LIST.  */
13549
13550 static tree
13551 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
13552                         tree in_decl)
13553 {
13554   if (TREE_CODE (decl) == TREE_LIST)
13555     {
13556       tree low_bound
13557         = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
13558                        /*integral_constant_expression_p=*/false);
13559       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
13560                                  /*integral_constant_expression_p=*/false);
13561       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
13562                                            in_decl);
13563       if (TREE_PURPOSE (decl) == low_bound
13564           && TREE_VALUE (decl) == length
13565           && TREE_CHAIN (decl) == chain)
13566         return decl;
13567       return tree_cons (low_bound, length, chain);
13568     }
13569   return tsubst_copy (decl, args, complain, in_decl);
13570 }
13571
13572 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
13573
13574 static tree
13575 tsubst_omp_clauses (tree clauses, bool declare_simd,
13576                     tree args, tsubst_flags_t complain, tree in_decl)
13577 {
13578   tree new_clauses = NULL, nc, oc;
13579
13580   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
13581     {
13582       nc = copy_node (oc);
13583       OMP_CLAUSE_CHAIN (nc) = new_clauses;
13584       new_clauses = nc;
13585
13586       switch (OMP_CLAUSE_CODE (nc))
13587         {
13588         case OMP_CLAUSE_LASTPRIVATE:
13589           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
13590             {
13591               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
13592               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
13593                            in_decl, /*integral_constant_expression_p=*/false);
13594               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
13595                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
13596             }
13597           /* FALLTHRU */
13598         case OMP_CLAUSE_PRIVATE:
13599         case OMP_CLAUSE_SHARED:
13600         case OMP_CLAUSE_FIRSTPRIVATE:
13601         case OMP_CLAUSE_COPYIN:
13602         case OMP_CLAUSE_COPYPRIVATE:
13603         case OMP_CLAUSE_UNIFORM:
13604           OMP_CLAUSE_DECL (nc) = tsubst_copy (OMP_CLAUSE_DECL (oc), args,
13605                                               complain, in_decl);
13606           break;
13607         case OMP_CLAUSE_DEPEND:
13608         case OMP_CLAUSE_FROM:
13609         case OMP_CLAUSE_TO:
13610         case OMP_CLAUSE_MAP:
13611           OMP_CLAUSE_DECL (nc)
13612             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
13613                                       in_decl);
13614           break;
13615         case OMP_CLAUSE_IF:
13616         case OMP_CLAUSE_NUM_THREADS:
13617         case OMP_CLAUSE_SCHEDULE:
13618         case OMP_CLAUSE_COLLAPSE:
13619         case OMP_CLAUSE_FINAL:
13620         case OMP_CLAUSE_DEVICE:
13621         case OMP_CLAUSE_DIST_SCHEDULE:
13622         case OMP_CLAUSE_NUM_TEAMS:
13623         case OMP_CLAUSE_THREAD_LIMIT:
13624         case OMP_CLAUSE_SAFELEN:
13625         case OMP_CLAUSE_SIMDLEN:
13626           OMP_CLAUSE_OPERAND (nc, 0)
13627             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
13628                            in_decl, /*integral_constant_expression_p=*/false);
13629           break;
13630         case OMP_CLAUSE_REDUCTION:
13631           if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
13632             {
13633               tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
13634               if (TREE_CODE (placeholder) == SCOPE_REF)
13635                 {
13636                   tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
13637                                        complain, in_decl);
13638                   OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
13639                     = build_qualified_name (NULL_TREE, scope,
13640                                             TREE_OPERAND (placeholder, 1),
13641                                             false);
13642                 }
13643               else
13644                 gcc_assert (identifier_p (placeholder));
13645             }
13646           OMP_CLAUSE_DECL (nc) = tsubst_copy (OMP_CLAUSE_DECL (oc), args,
13647                                               complain, in_decl);
13648           break;
13649         case OMP_CLAUSE_LINEAR:
13650         case OMP_CLAUSE_ALIGNED:
13651           OMP_CLAUSE_DECL (nc) = tsubst_copy (OMP_CLAUSE_DECL (oc), args,
13652                                               complain, in_decl);
13653           OMP_CLAUSE_OPERAND (nc, 1)
13654             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
13655                            in_decl, /*integral_constant_expression_p=*/false);
13656           break;
13657         case OMP_CLAUSE_NOWAIT:
13658         case OMP_CLAUSE_ORDERED:
13659         case OMP_CLAUSE_DEFAULT:
13660         case OMP_CLAUSE_UNTIED:
13661         case OMP_CLAUSE_MERGEABLE:
13662         case OMP_CLAUSE_INBRANCH:
13663         case OMP_CLAUSE_NOTINBRANCH:
13664         case OMP_CLAUSE_PROC_BIND:
13665         case OMP_CLAUSE_FOR:
13666         case OMP_CLAUSE_PARALLEL:
13667         case OMP_CLAUSE_SECTIONS:
13668         case OMP_CLAUSE_TASKGROUP:
13669           break;
13670         default:
13671           gcc_unreachable ();
13672         }
13673     }
13674
13675   new_clauses = nreverse (new_clauses);
13676   if (!declare_simd)
13677     new_clauses = finish_omp_clauses (new_clauses);
13678   return new_clauses;
13679 }
13680
13681 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
13682
13683 static tree
13684 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
13685                           tree in_decl)
13686 {
13687 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
13688
13689   tree purpose, value, chain;
13690
13691   if (t == NULL)
13692     return t;
13693
13694   if (TREE_CODE (t) != TREE_LIST)
13695     return tsubst_copy_and_build (t, args, complain, in_decl,
13696                                   /*function_p=*/false,
13697                                   /*integral_constant_expression_p=*/false);
13698
13699   if (t == void_list_node)
13700     return t;
13701
13702   purpose = TREE_PURPOSE (t);
13703   if (purpose)
13704     purpose = RECUR (purpose);
13705   value = TREE_VALUE (t);
13706   if (value)
13707     {
13708       if (TREE_CODE (value) != LABEL_DECL)
13709         value = RECUR (value);
13710       else
13711         {
13712           value = lookup_label (DECL_NAME (value));
13713           gcc_assert (TREE_CODE (value) == LABEL_DECL);
13714           TREE_USED (value) = 1;
13715         }
13716     }
13717   chain = TREE_CHAIN (t);
13718   if (chain && chain != void_type_node)
13719     chain = RECUR (chain);
13720   return tree_cons (purpose, value, chain);
13721 #undef RECUR
13722 }
13723
13724 /* Substitute one OMP_FOR iterator.  */
13725
13726 static void
13727 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
13728                          tree condv, tree incrv, tree *clauses,
13729                          tree args, tsubst_flags_t complain, tree in_decl,
13730                          bool integral_constant_expression_p)
13731 {
13732 #define RECUR(NODE)                             \
13733   tsubst_expr ((NODE), args, complain, in_decl, \
13734                integral_constant_expression_p)
13735   tree decl, init, cond, incr;
13736
13737   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
13738   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
13739   decl = TREE_OPERAND (init, 0);
13740   init = TREE_OPERAND (init, 1);
13741   tree decl_expr = NULL_TREE;
13742   if (init && TREE_CODE (init) == DECL_EXPR)
13743     {
13744       /* We need to jump through some hoops to handle declarations in the
13745          for-init-statement, since we might need to handle auto deduction,
13746          but we need to keep control of initialization.  */
13747       decl_expr = init;
13748       init = DECL_INITIAL (DECL_EXPR_DECL (init));
13749       decl = tsubst_decl (decl, args, complain);
13750     }
13751   else
13752     decl = RECUR (decl);
13753   init = RECUR (init);
13754
13755   tree auto_node = type_uses_auto (TREE_TYPE (decl));
13756   if (auto_node && init)
13757     TREE_TYPE (decl)
13758       = do_auto_deduction (TREE_TYPE (decl), init, auto_node);
13759
13760   gcc_assert (!type_dependent_expression_p (decl));
13761
13762   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
13763     {
13764       if (decl_expr)
13765         {
13766           /* Declare the variable, but don't let that initialize it.  */
13767           tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
13768           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
13769           RECUR (decl_expr);
13770           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
13771         }
13772
13773       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
13774       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
13775       if (TREE_CODE (incr) == MODIFY_EXPR)
13776         {
13777           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13778           tree rhs = RECUR (TREE_OPERAND (incr, 1));
13779           incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
13780                                       NOP_EXPR, rhs, complain);
13781         }
13782       else
13783         incr = RECUR (incr);
13784       TREE_VEC_ELT (declv, i) = decl;
13785       TREE_VEC_ELT (initv, i) = init;
13786       TREE_VEC_ELT (condv, i) = cond;
13787       TREE_VEC_ELT (incrv, i) = incr;
13788       return;
13789     }
13790
13791   if (decl_expr)
13792     {
13793       /* Declare and initialize the variable.  */
13794       RECUR (decl_expr);
13795       init = NULL_TREE;
13796     }
13797   else if (init)
13798     {
13799       tree c;
13800       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
13801         {
13802           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
13803                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
13804               && OMP_CLAUSE_DECL (c) == decl)
13805             break;
13806           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
13807                    && OMP_CLAUSE_DECL (c) == decl)
13808             error ("iteration variable %qD should not be firstprivate", decl);
13809           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
13810                    && OMP_CLAUSE_DECL (c) == decl)
13811             error ("iteration variable %qD should not be reduction", decl);
13812         }
13813       if (c == NULL)
13814         {
13815           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
13816           OMP_CLAUSE_DECL (c) = decl;
13817           c = finish_omp_clauses (c);
13818           if (c)
13819             {
13820               OMP_CLAUSE_CHAIN (c) = *clauses;
13821               *clauses = c;
13822             }
13823         }
13824     }
13825   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
13826   if (COMPARISON_CLASS_P (cond))
13827     {
13828       tree op0 = RECUR (TREE_OPERAND (cond, 0));
13829       tree op1 = RECUR (TREE_OPERAND (cond, 1));
13830       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
13831     }
13832   else
13833     cond = RECUR (cond);
13834   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
13835   switch (TREE_CODE (incr))
13836     {
13837     case PREINCREMENT_EXPR:
13838     case PREDECREMENT_EXPR:
13839     case POSTINCREMENT_EXPR:
13840     case POSTDECREMENT_EXPR:
13841       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
13842                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
13843       break;
13844     case MODIFY_EXPR:
13845       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
13846           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
13847         {
13848           tree rhs = TREE_OPERAND (incr, 1);
13849           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13850           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
13851           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
13852           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
13853                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
13854                                  rhs0, rhs1));
13855         }
13856       else
13857         incr = RECUR (incr);
13858       break;
13859     case MODOP_EXPR:
13860       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
13861           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
13862         {
13863           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13864           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
13865                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
13866                                  TREE_TYPE (decl), lhs,
13867                                  RECUR (TREE_OPERAND (incr, 2))));
13868         }
13869       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
13870                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
13871                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
13872         {
13873           tree rhs = TREE_OPERAND (incr, 2);
13874           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13875           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
13876           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
13877           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
13878                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
13879                                  rhs0, rhs1));
13880         }
13881       else
13882         incr = RECUR (incr);
13883       break;
13884     default:
13885       incr = RECUR (incr);
13886       break;
13887     }
13888
13889   TREE_VEC_ELT (declv, i) = decl;
13890   TREE_VEC_ELT (initv, i) = init;
13891   TREE_VEC_ELT (condv, i) = cond;
13892   TREE_VEC_ELT (incrv, i) = incr;
13893 #undef RECUR
13894 }
13895
13896 /* Like tsubst_copy for expressions, etc. but also does semantic
13897    processing.  */
13898
13899 static tree
13900 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
13901              bool integral_constant_expression_p)
13902 {
13903 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13904 #define RECUR(NODE)                             \
13905   tsubst_expr ((NODE), args, complain, in_decl, \
13906                integral_constant_expression_p)
13907
13908   tree stmt, tmp;
13909   tree r;
13910   location_t loc;
13911
13912   if (t == NULL_TREE || t == error_mark_node)
13913     return t;
13914
13915   loc = input_location;
13916   if (EXPR_HAS_LOCATION (t))
13917     input_location = EXPR_LOCATION (t);
13918   if (STATEMENT_CODE_P (TREE_CODE (t)))
13919     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
13920
13921   switch (TREE_CODE (t))
13922     {
13923     case STATEMENT_LIST:
13924       {
13925         tree_stmt_iterator i;
13926         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
13927           RECUR (tsi_stmt (i));
13928         break;
13929       }
13930
13931     case CTOR_INITIALIZER:
13932       finish_mem_initializers (tsubst_initializer_list
13933                                (TREE_OPERAND (t, 0), args));
13934       break;
13935
13936     case RETURN_EXPR:
13937       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
13938       break;
13939
13940     case EXPR_STMT:
13941       tmp = RECUR (EXPR_STMT_EXPR (t));
13942       if (EXPR_STMT_STMT_EXPR_RESULT (t))
13943         finish_stmt_expr_expr (tmp, cur_stmt_expr);
13944       else
13945         finish_expr_stmt (tmp);
13946       break;
13947
13948     case USING_STMT:
13949       do_using_directive (USING_STMT_NAMESPACE (t));
13950       break;
13951
13952     case DECL_EXPR:
13953       {
13954         tree decl, pattern_decl;
13955         tree init;
13956
13957         pattern_decl = decl = DECL_EXPR_DECL (t);
13958         if (TREE_CODE (decl) == LABEL_DECL)
13959           finish_label_decl (DECL_NAME (decl));
13960         else if (TREE_CODE (decl) == USING_DECL)
13961           {
13962             tree scope = USING_DECL_SCOPE (decl);
13963             tree name = DECL_NAME (decl);
13964             tree decl;
13965
13966             scope = tsubst (scope, args, complain, in_decl);
13967             decl = lookup_qualified_name (scope, name,
13968                                           /*is_type_p=*/false,
13969                                           /*complain=*/false);
13970             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
13971               qualified_name_lookup_error (scope, name, decl, input_location);
13972             else
13973               do_local_using_decl (decl, scope, name);
13974           }
13975         else if (DECL_PACK_P (decl))
13976           {
13977             /* Don't build up decls for a variadic capture proxy, we'll
13978                instantiate the elements directly as needed.  */
13979             break;
13980           }
13981         else
13982           {
13983             init = DECL_INITIAL (decl);
13984             decl = tsubst (decl, args, complain, in_decl);
13985             if (decl != error_mark_node)
13986               {
13987                 /* By marking the declaration as instantiated, we avoid
13988                    trying to instantiate it.  Since instantiate_decl can't
13989                    handle local variables, and since we've already done
13990                    all that needs to be done, that's the right thing to
13991                    do.  */
13992                 if (VAR_P (decl))
13993                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
13994                 if (VAR_P (decl)
13995                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
13996                   /* Anonymous aggregates are a special case.  */
13997                   finish_anon_union (decl);
13998                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
13999                   {
14000                     DECL_CONTEXT (decl) = current_function_decl;
14001                     if (DECL_NAME (decl) == this_identifier)
14002                       {
14003                         tree lam = DECL_CONTEXT (current_function_decl);
14004                         lam = CLASSTYPE_LAMBDA_EXPR (lam);
14005                         LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
14006                       }
14007                     insert_capture_proxy (decl);
14008                   }
14009                 else if (DECL_IMPLICIT_TYPEDEF_P (t))
14010                   /* We already did a pushtag.  */;
14011                 else if (TREE_CODE (decl) == FUNCTION_DECL
14012                          && DECL_OMP_DECLARE_REDUCTION_P (decl)
14013                          && DECL_FUNCTION_SCOPE_P (pattern_decl))
14014                   {
14015                     DECL_CONTEXT (decl) = NULL_TREE;
14016                     pushdecl (decl);
14017                     DECL_CONTEXT (decl) = current_function_decl;
14018                     cp_check_omp_declare_reduction (decl);
14019                   }
14020                 else
14021                   {
14022                     int const_init = false;
14023                     maybe_push_decl (decl);
14024                     if (VAR_P (decl)
14025                         && DECL_PRETTY_FUNCTION_P (decl))
14026                       {
14027                         /* For __PRETTY_FUNCTION__ we have to adjust the
14028                            initializer.  */
14029                         const char *const name
14030                           = cxx_printable_name (current_function_decl, 2);
14031                         init = cp_fname_init (name, &TREE_TYPE (decl));
14032                       }
14033                     else
14034                       init = tsubst_init (init, decl, args, complain, in_decl);
14035
14036                     if (VAR_P (decl))
14037                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
14038                                     (pattern_decl));
14039                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
14040                   }
14041               }
14042           }
14043
14044         break;
14045       }
14046
14047     case FOR_STMT:
14048       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
14049       RECUR (FOR_INIT_STMT (t));
14050       finish_for_init_stmt (stmt);
14051       tmp = RECUR (FOR_COND (t));
14052       finish_for_cond (tmp, stmt, false);
14053       tmp = RECUR (FOR_EXPR (t));
14054       finish_for_expr (tmp, stmt);
14055       RECUR (FOR_BODY (t));
14056       finish_for_stmt (stmt);
14057       break;
14058
14059     case RANGE_FOR_STMT:
14060       {
14061         tree decl, expr;
14062         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
14063         decl = RANGE_FOR_DECL (t);
14064         decl = tsubst (decl, args, complain, in_decl);
14065         maybe_push_decl (decl);
14066         expr = RECUR (RANGE_FOR_EXPR (t));
14067         stmt = cp_convert_range_for (stmt, decl, expr, RANGE_FOR_IVDEP (t));
14068         RECUR (RANGE_FOR_BODY (t));
14069         finish_for_stmt (stmt);
14070       }
14071       break;
14072
14073     case WHILE_STMT:
14074       stmt = begin_while_stmt ();
14075       tmp = RECUR (WHILE_COND (t));
14076       finish_while_stmt_cond (tmp, stmt, false);
14077       RECUR (WHILE_BODY (t));
14078       finish_while_stmt (stmt);
14079       break;
14080
14081     case DO_STMT:
14082       stmt = begin_do_stmt ();
14083       RECUR (DO_BODY (t));
14084       finish_do_body (stmt);
14085       tmp = RECUR (DO_COND (t));
14086       finish_do_stmt (tmp, stmt, false);
14087       break;
14088
14089     case IF_STMT:
14090       stmt = begin_if_stmt ();
14091       tmp = RECUR (IF_COND (t));
14092       finish_if_stmt_cond (tmp, stmt);
14093       RECUR (THEN_CLAUSE (t));
14094       finish_then_clause (stmt);
14095
14096       if (ELSE_CLAUSE (t))
14097         {
14098           begin_else_clause (stmt);
14099           RECUR (ELSE_CLAUSE (t));
14100           finish_else_clause (stmt);
14101         }
14102
14103       finish_if_stmt (stmt);
14104       break;
14105
14106     case BIND_EXPR:
14107       if (BIND_EXPR_BODY_BLOCK (t))
14108         stmt = begin_function_body ();
14109       else
14110         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
14111                                     ? BCS_TRY_BLOCK : 0);
14112
14113       RECUR (BIND_EXPR_BODY (t));
14114
14115       if (BIND_EXPR_BODY_BLOCK (t))
14116         finish_function_body (stmt);
14117       else
14118         finish_compound_stmt (stmt);
14119       break;
14120
14121     case BREAK_STMT:
14122       finish_break_stmt ();
14123       break;
14124
14125     case CONTINUE_STMT:
14126       finish_continue_stmt ();
14127       break;
14128
14129     case SWITCH_STMT:
14130       stmt = begin_switch_stmt ();
14131       tmp = RECUR (SWITCH_STMT_COND (t));
14132       finish_switch_cond (tmp, stmt);
14133       RECUR (SWITCH_STMT_BODY (t));
14134       finish_switch_stmt (stmt);
14135       break;
14136
14137     case CASE_LABEL_EXPR:
14138       {
14139         tree low = RECUR (CASE_LOW (t));
14140         tree high = RECUR (CASE_HIGH (t));
14141         finish_case_label (EXPR_LOCATION (t), low, high);
14142       }
14143       break;
14144
14145     case LABEL_EXPR:
14146       {
14147         tree decl = LABEL_EXPR_LABEL (t);
14148         tree label;
14149
14150         label = finish_label_stmt (DECL_NAME (decl));
14151         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
14152           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
14153       }
14154       break;
14155
14156     case GOTO_EXPR:
14157       tmp = GOTO_DESTINATION (t);
14158       if (TREE_CODE (tmp) != LABEL_DECL)
14159         /* Computed goto's must be tsubst'd into.  On the other hand,
14160            non-computed gotos must not be; the identifier in question
14161            will have no binding.  */
14162         tmp = RECUR (tmp);
14163       else
14164         tmp = DECL_NAME (tmp);
14165       finish_goto_stmt (tmp);
14166       break;
14167
14168     case ASM_EXPR:
14169       {
14170         tree string = RECUR (ASM_STRING (t));
14171         tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
14172                                                  complain, in_decl);
14173         tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
14174                                                 complain, in_decl);
14175         tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
14176                                                   complain, in_decl);
14177         tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
14178                                                 complain, in_decl);
14179         tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
14180                                clobbers, labels);
14181         tree asm_expr = tmp;
14182         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
14183           asm_expr = TREE_OPERAND (asm_expr, 0);
14184         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
14185       }
14186       break;
14187
14188     case TRY_BLOCK:
14189       if (CLEANUP_P (t))
14190         {
14191           stmt = begin_try_block ();
14192           RECUR (TRY_STMTS (t));
14193           finish_cleanup_try_block (stmt);
14194           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
14195         }
14196       else
14197         {
14198           tree compound_stmt = NULL_TREE;
14199
14200           if (FN_TRY_BLOCK_P (t))
14201             stmt = begin_function_try_block (&compound_stmt);
14202           else
14203             stmt = begin_try_block ();
14204
14205           RECUR (TRY_STMTS (t));
14206
14207           if (FN_TRY_BLOCK_P (t))
14208             finish_function_try_block (stmt);
14209           else
14210             finish_try_block (stmt);
14211
14212           RECUR (TRY_HANDLERS (t));
14213           if (FN_TRY_BLOCK_P (t))
14214             finish_function_handler_sequence (stmt, compound_stmt);
14215           else
14216             finish_handler_sequence (stmt);
14217         }
14218       break;
14219
14220     case HANDLER:
14221       {
14222         tree decl = HANDLER_PARMS (t);
14223
14224         if (decl)
14225           {
14226             decl = tsubst (decl, args, complain, in_decl);
14227             /* Prevent instantiate_decl from trying to instantiate
14228                this variable.  We've already done all that needs to be
14229                done.  */
14230             if (decl != error_mark_node)
14231               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
14232           }
14233         stmt = begin_handler ();
14234         finish_handler_parms (decl, stmt);
14235         RECUR (HANDLER_BODY (t));
14236         finish_handler (stmt);
14237       }
14238       break;
14239
14240     case TAG_DEFN:
14241       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
14242       if (CLASS_TYPE_P (tmp))
14243         {
14244           /* Local classes are not independent templates; they are
14245              instantiated along with their containing function.  And this
14246              way we don't have to deal with pushing out of one local class
14247              to instantiate a member of another local class.  */
14248           tree fn;
14249           /* Closures are handled by the LAMBDA_EXPR.  */
14250           gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
14251           complete_type (tmp);
14252           for (fn = TYPE_METHODS (tmp); fn; fn = DECL_CHAIN (fn))
14253             if (!DECL_ARTIFICIAL (fn))
14254               instantiate_decl (fn, /*defer_ok*/0, /*expl_inst_class*/false);
14255         }
14256       break;
14257
14258     case STATIC_ASSERT:
14259       {
14260         tree condition;
14261
14262         ++c_inhibit_evaluation_warnings;
14263         condition = 
14264           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
14265                        args,
14266                        complain, in_decl,
14267                        /*integral_constant_expression_p=*/true);
14268         --c_inhibit_evaluation_warnings;
14269
14270         finish_static_assert (condition,
14271                               STATIC_ASSERT_MESSAGE (t),
14272                               STATIC_ASSERT_SOURCE_LOCATION (t),
14273                               /*member_p=*/false);
14274       }
14275       break;
14276
14277     case OMP_PARALLEL:
14278       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), false,
14279                                 args, complain, in_decl);
14280       stmt = begin_omp_parallel ();
14281       RECUR (OMP_PARALLEL_BODY (t));
14282       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
14283         = OMP_PARALLEL_COMBINED (t);
14284       break;
14285
14286     case OMP_TASK:
14287       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), false,
14288                                 args, complain, in_decl);
14289       stmt = begin_omp_task ();
14290       RECUR (OMP_TASK_BODY (t));
14291       finish_omp_task (tmp, stmt);
14292       break;
14293
14294     case OMP_FOR:
14295     case OMP_SIMD:
14296     case CILK_SIMD:
14297     case CILK_FOR:
14298     case OMP_DISTRIBUTE:
14299       {
14300         tree clauses, body, pre_body;
14301         tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
14302         tree incrv = NULL_TREE;
14303         int i;
14304
14305         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), false,
14306                                       args, complain, in_decl);
14307         if (OMP_FOR_INIT (t) != NULL_TREE)
14308           {
14309             declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14310             initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14311             condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14312             incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14313           }
14314
14315         stmt = begin_omp_structured_block ();
14316
14317         pre_body = push_stmt_list ();
14318         RECUR (OMP_FOR_PRE_BODY (t));
14319         pre_body = pop_stmt_list (pre_body);
14320
14321         if (OMP_FOR_INIT (t) != NULL_TREE)
14322           for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
14323             tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
14324                                      &clauses, args, complain, in_decl,
14325                                      integral_constant_expression_p);
14326
14327         body = push_stmt_list ();
14328         RECUR (OMP_FOR_BODY (t));
14329         body = pop_stmt_list (body);
14330
14331         if (OMP_FOR_INIT (t) != NULL_TREE)
14332           t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv, initv,
14333                               condv, incrv, body, pre_body, clauses);
14334         else
14335           {
14336             t = make_node (TREE_CODE (t));
14337             TREE_TYPE (t) = void_type_node;
14338             OMP_FOR_BODY (t) = body;
14339             OMP_FOR_PRE_BODY (t) = pre_body;
14340             OMP_FOR_CLAUSES (t) = clauses;
14341             SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
14342             add_stmt (t);
14343           }
14344
14345         add_stmt (finish_omp_structured_block (stmt));
14346       }
14347       break;
14348
14349     case OMP_SECTIONS:
14350     case OMP_SINGLE:
14351     case OMP_TEAMS:
14352       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false,
14353                                 args, complain, in_decl);
14354       stmt = push_stmt_list ();
14355       RECUR (OMP_BODY (t));
14356       stmt = pop_stmt_list (stmt);
14357
14358       t = copy_node (t);
14359       OMP_BODY (t) = stmt;
14360       OMP_CLAUSES (t) = tmp;
14361       add_stmt (t);
14362       break;
14363
14364     case OMP_TARGET_DATA:
14365     case OMP_TARGET:
14366       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false,
14367                                 args, complain, in_decl);
14368       keep_next_level (true);
14369       stmt = begin_omp_structured_block ();
14370
14371       RECUR (OMP_BODY (t));
14372       stmt = finish_omp_structured_block (stmt);
14373
14374       t = copy_node (t);
14375       OMP_BODY (t) = stmt;
14376       OMP_CLAUSES (t) = tmp;
14377       add_stmt (t);
14378       break;
14379
14380     case OMP_TARGET_UPDATE:
14381       tmp = tsubst_omp_clauses (OMP_TARGET_UPDATE_CLAUSES (t), false,
14382                                 args, complain, in_decl);
14383       t = copy_node (t);
14384       OMP_TARGET_UPDATE_CLAUSES (t) = tmp;
14385       add_stmt (t);
14386       break;
14387
14388     case OMP_SECTION:
14389     case OMP_CRITICAL:
14390     case OMP_MASTER:
14391     case OMP_TASKGROUP:
14392     case OMP_ORDERED:
14393       stmt = push_stmt_list ();
14394       RECUR (OMP_BODY (t));
14395       stmt = pop_stmt_list (stmt);
14396
14397       t = copy_node (t);
14398       OMP_BODY (t) = stmt;
14399       add_stmt (t);
14400       break;
14401
14402     case OMP_ATOMIC:
14403       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
14404       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
14405         {
14406           tree op1 = TREE_OPERAND (t, 1);
14407           tree rhs1 = NULL_TREE;
14408           tree lhs, rhs;
14409           if (TREE_CODE (op1) == COMPOUND_EXPR)
14410             {
14411               rhs1 = RECUR (TREE_OPERAND (op1, 0));
14412               op1 = TREE_OPERAND (op1, 1);
14413             }
14414           lhs = RECUR (TREE_OPERAND (op1, 0));
14415           rhs = RECUR (TREE_OPERAND (op1, 1));
14416           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
14417                              NULL_TREE, NULL_TREE, rhs1,
14418                              OMP_ATOMIC_SEQ_CST (t));
14419         }
14420       else
14421         {
14422           tree op1 = TREE_OPERAND (t, 1);
14423           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
14424           tree rhs1 = NULL_TREE;
14425           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
14426           enum tree_code opcode = NOP_EXPR;
14427           if (code == OMP_ATOMIC_READ)
14428             {
14429               v = RECUR (TREE_OPERAND (op1, 0));
14430               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
14431             }
14432           else if (code == OMP_ATOMIC_CAPTURE_OLD
14433                    || code == OMP_ATOMIC_CAPTURE_NEW)
14434             {
14435               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
14436               v = RECUR (TREE_OPERAND (op1, 0));
14437               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
14438               if (TREE_CODE (op11) == COMPOUND_EXPR)
14439                 {
14440                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
14441                   op11 = TREE_OPERAND (op11, 1);
14442                 }
14443               lhs = RECUR (TREE_OPERAND (op11, 0));
14444               rhs = RECUR (TREE_OPERAND (op11, 1));
14445               opcode = TREE_CODE (op11);
14446               if (opcode == MODIFY_EXPR)
14447                 opcode = NOP_EXPR;
14448             }
14449           else
14450             {
14451               code = OMP_ATOMIC;
14452               lhs = RECUR (TREE_OPERAND (op1, 0));
14453               rhs = RECUR (TREE_OPERAND (op1, 1));
14454             }
14455           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
14456                              OMP_ATOMIC_SEQ_CST (t));
14457         }
14458       break;
14459
14460     case TRANSACTION_EXPR:
14461       {
14462         int flags = 0;
14463         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
14464         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
14465
14466         if (TRANSACTION_EXPR_IS_STMT (t))
14467           {
14468             tree body = TRANSACTION_EXPR_BODY (t);
14469             tree noex = NULL_TREE;
14470             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
14471               {
14472                 noex = MUST_NOT_THROW_COND (body);
14473                 if (noex == NULL_TREE)
14474                   noex = boolean_true_node;
14475                 body = TREE_OPERAND (body, 0);
14476               }
14477             stmt = begin_transaction_stmt (input_location, NULL, flags);
14478             RECUR (body);
14479             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
14480           }
14481         else
14482           {
14483             stmt = build_transaction_expr (EXPR_LOCATION (t),
14484                                            RECUR (TRANSACTION_EXPR_BODY (t)),
14485                                            flags, NULL_TREE);
14486             RETURN (stmt);
14487           }
14488       }
14489       break;
14490
14491     case MUST_NOT_THROW_EXPR:
14492       {
14493         tree op0 = RECUR (TREE_OPERAND (t, 0));
14494         tree cond = RECUR (MUST_NOT_THROW_COND (t));
14495         RETURN (build_must_not_throw_expr (op0, cond));
14496       }
14497
14498     case EXPR_PACK_EXPANSION:
14499       error ("invalid use of pack expansion expression");
14500       RETURN (error_mark_node);
14501
14502     case NONTYPE_ARGUMENT_PACK:
14503       error ("use %<...%> to expand argument pack");
14504       RETURN (error_mark_node);
14505
14506     case CILK_SPAWN_STMT:
14507       cfun->calls_cilk_spawn = 1;
14508       RETURN (build_cilk_spawn (EXPR_LOCATION (t), RECUR (CILK_SPAWN_FN (t))));
14509
14510     case CILK_SYNC_STMT:
14511       RETURN (build_cilk_sync ());
14512
14513     case COMPOUND_EXPR:
14514       tmp = RECUR (TREE_OPERAND (t, 0));
14515       if (tmp == NULL_TREE)
14516         /* If the first operand was a statement, we're done with it.  */
14517         RETURN (RECUR (TREE_OPERAND (t, 1)));
14518       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
14519                                     RECUR (TREE_OPERAND (t, 1)),
14520                                     complain));
14521
14522     case ANNOTATE_EXPR:
14523       tmp = RECUR (TREE_OPERAND (t, 0));
14524       RETURN (build2_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
14525                           TREE_TYPE (tmp), tmp, RECUR (TREE_OPERAND (t, 1))));
14526
14527     default:
14528       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
14529
14530       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
14531                                     /*function_p=*/false,
14532                                     integral_constant_expression_p));
14533     }
14534
14535   RETURN (NULL_TREE);
14536  out:
14537   input_location = loc;
14538   return r;
14539 #undef RECUR
14540 #undef RETURN
14541 }
14542
14543 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
14544    function.  For description of the body see comment above
14545    cp_parser_omp_declare_reduction_exprs.  */
14546
14547 static void
14548 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14549 {
14550   if (t == NULL_TREE || t == error_mark_node)
14551     return;
14552
14553   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
14554
14555   tree_stmt_iterator tsi;
14556   int i;
14557   tree stmts[7];
14558   memset (stmts, 0, sizeof stmts);
14559   for (i = 0, tsi = tsi_start (t);
14560        i < 7 && !tsi_end_p (tsi);
14561        i++, tsi_next (&tsi))
14562     stmts[i] = tsi_stmt (tsi);
14563   gcc_assert (tsi_end_p (tsi));
14564
14565   if (i >= 3)
14566     {
14567       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
14568                   && TREE_CODE (stmts[1]) == DECL_EXPR);
14569       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
14570                              args, complain, in_decl);
14571       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
14572                             args, complain, in_decl);
14573       DECL_CONTEXT (omp_out) = current_function_decl;
14574       DECL_CONTEXT (omp_in) = current_function_decl;
14575       keep_next_level (true);
14576       tree block = begin_omp_structured_block ();
14577       tsubst_expr (stmts[2], args, complain, in_decl, false);
14578       block = finish_omp_structured_block (block);
14579       block = maybe_cleanup_point_expr_void (block);
14580       add_decl_expr (omp_out);
14581       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
14582         TREE_NO_WARNING (omp_out) = 1;
14583       add_decl_expr (omp_in);
14584       finish_expr_stmt (block);
14585     }
14586   if (i >= 6)
14587     {
14588       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
14589                   && TREE_CODE (stmts[4]) == DECL_EXPR);
14590       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
14591                               args, complain, in_decl);
14592       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
14593                               args, complain, in_decl);
14594       DECL_CONTEXT (omp_priv) = current_function_decl;
14595       DECL_CONTEXT (omp_orig) = current_function_decl;
14596       keep_next_level (true);
14597       tree block = begin_omp_structured_block ();
14598       tsubst_expr (stmts[5], args, complain, in_decl, false);
14599       block = finish_omp_structured_block (block);
14600       block = maybe_cleanup_point_expr_void (block);
14601       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
14602       add_decl_expr (omp_priv);
14603       add_decl_expr (omp_orig);
14604       finish_expr_stmt (block);
14605       if (i == 7)
14606         add_decl_expr (omp_orig);
14607     }
14608 }
14609
14610 /* T is a postfix-expression that is not being used in a function
14611    call.  Return the substituted version of T.  */
14612
14613 static tree
14614 tsubst_non_call_postfix_expression (tree t, tree args,
14615                                     tsubst_flags_t complain,
14616                                     tree in_decl)
14617 {
14618   if (TREE_CODE (t) == SCOPE_REF)
14619     t = tsubst_qualified_id (t, args, complain, in_decl,
14620                              /*done=*/false, /*address_p=*/false);
14621   else
14622     t = tsubst_copy_and_build (t, args, complain, in_decl,
14623                                /*function_p=*/false,
14624                                /*integral_constant_expression_p=*/false);
14625
14626   return t;
14627 }
14628
14629 /* Like tsubst but deals with expressions and performs semantic
14630    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
14631
14632 tree
14633 tsubst_copy_and_build (tree t,
14634                        tree args,
14635                        tsubst_flags_t complain,
14636                        tree in_decl,
14637                        bool function_p,
14638                        bool integral_constant_expression_p)
14639 {
14640 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
14641 #define RECUR(NODE)                                             \
14642   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
14643                          /*function_p=*/false,                  \
14644                          integral_constant_expression_p)
14645
14646   tree retval, op1;
14647   location_t loc;
14648
14649   if (t == NULL_TREE || t == error_mark_node)
14650     return t;
14651
14652   loc = input_location;
14653   if (EXPR_HAS_LOCATION (t))
14654     input_location = EXPR_LOCATION (t);
14655
14656   /* N3276 decltype magic only applies to calls at the top level or on the
14657      right side of a comma.  */
14658   tsubst_flags_t decltype_flag = (complain & tf_decltype);
14659   complain &= ~tf_decltype;
14660
14661   switch (TREE_CODE (t))
14662     {
14663     case USING_DECL:
14664       t = DECL_NAME (t);
14665       /* Fall through.  */
14666     case IDENTIFIER_NODE:
14667       {
14668         tree decl;
14669         cp_id_kind idk;
14670         bool non_integral_constant_expression_p;
14671         const char *error_msg;
14672
14673         if (IDENTIFIER_TYPENAME_P (t))
14674           {
14675             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14676             t = mangle_conv_op_name_for_type (new_type);
14677           }
14678
14679         /* Look up the name.  */
14680         decl = lookup_name (t);
14681
14682         /* By convention, expressions use ERROR_MARK_NODE to indicate
14683            failure, not NULL_TREE.  */
14684         if (decl == NULL_TREE)
14685           decl = error_mark_node;
14686
14687         decl = finish_id_expression (t, decl, NULL_TREE,
14688                                      &idk,
14689                                      integral_constant_expression_p,
14690           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
14691                                      &non_integral_constant_expression_p,
14692                                      /*template_p=*/false,
14693                                      /*done=*/true,
14694                                      /*address_p=*/false,
14695                                      /*template_arg_p=*/false,
14696                                      &error_msg,
14697                                      input_location);
14698         if (error_msg)
14699           error (error_msg);
14700         if (!function_p && identifier_p (decl))
14701           {
14702             if (complain & tf_error)
14703               unqualified_name_lookup_error (decl);
14704             decl = error_mark_node;
14705           }
14706         RETURN (decl);
14707       }
14708
14709     case TEMPLATE_ID_EXPR:
14710       {
14711         tree object;
14712         tree templ = RECUR (TREE_OPERAND (t, 0));
14713         tree targs = TREE_OPERAND (t, 1);
14714
14715         if (targs)
14716           targs = tsubst_template_args (targs, args, complain, in_decl);
14717
14718         if (TREE_CODE (templ) == COMPONENT_REF)
14719           {
14720             object = TREE_OPERAND (templ, 0);
14721             templ = TREE_OPERAND (templ, 1);
14722           }
14723         else
14724           object = NULL_TREE;
14725         templ = lookup_template_function (templ, targs);
14726
14727         if (object)
14728           RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
14729                          object, templ, NULL_TREE));
14730         else
14731           RETURN (baselink_for_fns (templ));
14732       }
14733
14734     case INDIRECT_REF:
14735       {
14736         tree r = RECUR (TREE_OPERAND (t, 0));
14737
14738         if (REFERENCE_REF_P (t))
14739           {
14740             /* A type conversion to reference type will be enclosed in
14741                such an indirect ref, but the substitution of the cast
14742                will have also added such an indirect ref.  */
14743             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
14744               r = convert_from_reference (r);
14745           }
14746         else
14747           r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
14748                                     complain|decltype_flag);
14749         RETURN (r);
14750       }
14751
14752     case NOP_EXPR:
14753       {
14754         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14755         tree op0 = RECUR (TREE_OPERAND (t, 0));
14756         RETURN (build_nop (type, op0));
14757       }
14758
14759     case IMPLICIT_CONV_EXPR:
14760       {
14761         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14762         tree expr = RECUR (TREE_OPERAND (t, 0));
14763         int flags = LOOKUP_IMPLICIT;
14764         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
14765           flags = LOOKUP_NORMAL;
14766         RETURN (perform_implicit_conversion_flags (type, expr, complain,
14767                                                   flags));
14768       }
14769
14770     case CONVERT_EXPR:
14771       {
14772         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14773         tree op0 = RECUR (TREE_OPERAND (t, 0));
14774         RETURN (build1 (CONVERT_EXPR, type, op0));
14775       }
14776
14777     case CAST_EXPR:
14778     case REINTERPRET_CAST_EXPR:
14779     case CONST_CAST_EXPR:
14780     case DYNAMIC_CAST_EXPR:
14781     case STATIC_CAST_EXPR:
14782       {
14783         tree type;
14784         tree op, r = NULL_TREE;
14785
14786         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14787         if (integral_constant_expression_p
14788             && !cast_valid_in_integral_constant_expression_p (type))
14789           {
14790             if (complain & tf_error)
14791               error ("a cast to a type other than an integral or "
14792                      "enumeration type cannot appear in a constant-expression");
14793             RETURN (error_mark_node);
14794           }
14795
14796         op = RECUR (TREE_OPERAND (t, 0));
14797
14798         warning_sentinel s(warn_useless_cast);
14799         switch (TREE_CODE (t))
14800           {
14801           case CAST_EXPR:
14802             r = build_functional_cast (type, op, complain);
14803             break;
14804           case REINTERPRET_CAST_EXPR:
14805             r = build_reinterpret_cast (type, op, complain);
14806             break;
14807           case CONST_CAST_EXPR:
14808             r = build_const_cast (type, op, complain);
14809             break;
14810           case DYNAMIC_CAST_EXPR:
14811             r = build_dynamic_cast (type, op, complain);
14812             break;
14813           case STATIC_CAST_EXPR:
14814             r = build_static_cast (type, op, complain);
14815             break;
14816           default:
14817             gcc_unreachable ();
14818           }
14819
14820         RETURN (r);
14821       }
14822
14823     case POSTDECREMENT_EXPR:
14824     case POSTINCREMENT_EXPR:
14825       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
14826                                                 args, complain, in_decl);
14827       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
14828                                 complain|decltype_flag));
14829
14830     case PREDECREMENT_EXPR:
14831     case PREINCREMENT_EXPR:
14832     case NEGATE_EXPR:
14833     case BIT_NOT_EXPR:
14834     case ABS_EXPR:
14835     case TRUTH_NOT_EXPR:
14836     case UNARY_PLUS_EXPR:  /* Unary + */
14837     case REALPART_EXPR:
14838     case IMAGPART_EXPR:
14839       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
14840                                 RECUR (TREE_OPERAND (t, 0)),
14841                                 complain|decltype_flag));
14842
14843     case FIX_TRUNC_EXPR:
14844       RETURN (cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
14845                                  0, complain));
14846
14847     case ADDR_EXPR:
14848       op1 = TREE_OPERAND (t, 0);
14849       if (TREE_CODE (op1) == LABEL_DECL)
14850         RETURN (finish_label_address_expr (DECL_NAME (op1),
14851                                           EXPR_LOCATION (op1)));
14852       if (TREE_CODE (op1) == SCOPE_REF)
14853         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
14854                                    /*done=*/true, /*address_p=*/true);
14855       else
14856         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
14857                                                   in_decl);
14858       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
14859                                 complain|decltype_flag));
14860
14861     case PLUS_EXPR:
14862     case MINUS_EXPR:
14863     case MULT_EXPR:
14864     case TRUNC_DIV_EXPR:
14865     case CEIL_DIV_EXPR:
14866     case FLOOR_DIV_EXPR:
14867     case ROUND_DIV_EXPR:
14868     case EXACT_DIV_EXPR:
14869     case BIT_AND_EXPR:
14870     case BIT_IOR_EXPR:
14871     case BIT_XOR_EXPR:
14872     case TRUNC_MOD_EXPR:
14873     case FLOOR_MOD_EXPR:
14874     case TRUTH_ANDIF_EXPR:
14875     case TRUTH_ORIF_EXPR:
14876     case TRUTH_AND_EXPR:
14877     case TRUTH_OR_EXPR:
14878     case RSHIFT_EXPR:
14879     case LSHIFT_EXPR:
14880     case RROTATE_EXPR:
14881     case LROTATE_EXPR:
14882     case EQ_EXPR:
14883     case NE_EXPR:
14884     case MAX_EXPR:
14885     case MIN_EXPR:
14886     case LE_EXPR:
14887     case GE_EXPR:
14888     case LT_EXPR:
14889     case GT_EXPR:
14890     case MEMBER_REF:
14891     case DOTSTAR_EXPR:
14892       {
14893         warning_sentinel s1(warn_type_limits);
14894         warning_sentinel s2(warn_div_by_zero);
14895         tree op0 = RECUR (TREE_OPERAND (t, 0));
14896         tree op1 = RECUR (TREE_OPERAND (t, 1));
14897         tree r = build_x_binary_op
14898           (input_location, TREE_CODE (t),
14899            op0,
14900            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
14901             ? ERROR_MARK
14902             : TREE_CODE (TREE_OPERAND (t, 0))),
14903            op1,
14904            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
14905             ? ERROR_MARK
14906             : TREE_CODE (TREE_OPERAND (t, 1))),
14907            /*overload=*/NULL,
14908            complain|decltype_flag);
14909         if (EXPR_P (r) && TREE_NO_WARNING (t))
14910           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
14911
14912         RETURN (r);
14913       }
14914
14915     case POINTER_PLUS_EXPR:
14916       {
14917         tree op0 = RECUR (TREE_OPERAND (t, 0));
14918         tree op1 = RECUR (TREE_OPERAND (t, 1));
14919         return fold_build_pointer_plus (op0, op1);
14920       }
14921
14922     case SCOPE_REF:
14923       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
14924                                   /*address_p=*/false));
14925     case ARRAY_REF:
14926       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
14927                                                 args, complain, in_decl);
14928       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
14929                                  RECUR (TREE_OPERAND (t, 1)),
14930                                  complain|decltype_flag));
14931
14932     case ARRAY_NOTATION_REF:
14933       {
14934         tree start_index, length, stride;
14935         op1 = tsubst_non_call_postfix_expression (ARRAY_NOTATION_ARRAY (t),
14936                                                   args, complain, in_decl);
14937         start_index = RECUR (ARRAY_NOTATION_START (t));
14938         length = RECUR (ARRAY_NOTATION_LENGTH (t));
14939         stride = RECUR (ARRAY_NOTATION_STRIDE (t));
14940         RETURN (build_array_notation_ref (EXPR_LOCATION (t), op1, start_index,
14941                                           length, stride, TREE_TYPE (op1)));
14942       }
14943     case SIZEOF_EXPR:
14944       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
14945         RETURN (tsubst_copy (t, args, complain, in_decl));
14946       /* Fall through */
14947       
14948     case ALIGNOF_EXPR:
14949       {
14950         tree r;
14951
14952         op1 = TREE_OPERAND (t, 0);
14953         if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
14954           op1 = TREE_TYPE (op1);
14955         if (!args)
14956           {
14957             /* When there are no ARGS, we are trying to evaluate a
14958                non-dependent expression from the parser.  Trying to do
14959                the substitutions may not work.  */
14960             if (!TYPE_P (op1))
14961               op1 = TREE_TYPE (op1);
14962           }
14963         else
14964           {
14965             ++cp_unevaluated_operand;
14966             ++c_inhibit_evaluation_warnings;
14967             if (TYPE_P (op1))
14968               op1 = tsubst (op1, args, complain, in_decl);
14969             else
14970               op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
14971                                            /*function_p=*/false,
14972                                            /*integral_constant_expression_p=*/
14973                                            false);
14974             --cp_unevaluated_operand;
14975             --c_inhibit_evaluation_warnings;
14976           }
14977         if (TYPE_P (op1))
14978           r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
14979                                           complain & tf_error);
14980         else
14981           r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
14982                                           complain & tf_error);
14983         if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
14984           {
14985             if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
14986               {
14987                 if (!processing_template_decl && TYPE_P (op1))
14988                   {
14989                     r = build_min (SIZEOF_EXPR, size_type_node,
14990                                    build1 (NOP_EXPR, op1, error_mark_node));
14991                     SIZEOF_EXPR_TYPE_P (r) = 1;
14992                   }
14993                 else
14994                   r = build_min (SIZEOF_EXPR, size_type_node, op1);
14995                 TREE_SIDE_EFFECTS (r) = 0;
14996                 TREE_READONLY (r) = 1;
14997               }
14998             SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
14999           }
15000         RETURN (r);
15001       }
15002
15003     case AT_ENCODE_EXPR:
15004       {
15005         op1 = TREE_OPERAND (t, 0);
15006         ++cp_unevaluated_operand;
15007         ++c_inhibit_evaluation_warnings;
15008         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
15009                                      /*function_p=*/false,
15010                                      /*integral_constant_expression_p=*/false);
15011         --cp_unevaluated_operand;
15012         --c_inhibit_evaluation_warnings;
15013         RETURN (objc_build_encode_expr (op1));
15014       }
15015
15016     case NOEXCEPT_EXPR:
15017       op1 = TREE_OPERAND (t, 0);
15018       ++cp_unevaluated_operand;
15019       ++c_inhibit_evaluation_warnings;
15020       ++cp_noexcept_operand;
15021       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
15022                                    /*function_p=*/false,
15023                                    /*integral_constant_expression_p=*/false);
15024       --cp_unevaluated_operand;
15025       --c_inhibit_evaluation_warnings;
15026       --cp_noexcept_operand;
15027       RETURN (finish_noexcept_expr (op1, complain));
15028
15029     case MODOP_EXPR:
15030       {
15031         warning_sentinel s(warn_div_by_zero);
15032         tree lhs = RECUR (TREE_OPERAND (t, 0));
15033         tree rhs = RECUR (TREE_OPERAND (t, 2));
15034         tree r = build_x_modify_expr
15035           (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
15036            complain|decltype_flag);
15037         /* TREE_NO_WARNING must be set if either the expression was
15038            parenthesized or it uses an operator such as >>= rather
15039            than plain assignment.  In the former case, it was already
15040            set and must be copied.  In the latter case,
15041            build_x_modify_expr sets it and it must not be reset
15042            here.  */
15043         if (TREE_NO_WARNING (t))
15044           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15045
15046         RETURN (r);
15047       }
15048
15049     case ARROW_EXPR:
15050       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
15051                                                 args, complain, in_decl);
15052       /* Remember that there was a reference to this entity.  */
15053       if (DECL_P (op1))
15054         mark_used (op1);
15055       RETURN (build_x_arrow (input_location, op1, complain));
15056
15057     case NEW_EXPR:
15058       {
15059         tree placement = RECUR (TREE_OPERAND (t, 0));
15060         tree init = RECUR (TREE_OPERAND (t, 3));
15061         vec<tree, va_gc> *placement_vec;
15062         vec<tree, va_gc> *init_vec;
15063         tree ret;
15064
15065         if (placement == NULL_TREE)
15066           placement_vec = NULL;
15067         else
15068           {
15069             placement_vec = make_tree_vector ();
15070             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
15071               vec_safe_push (placement_vec, TREE_VALUE (placement));
15072           }
15073
15074         /* If there was an initializer in the original tree, but it
15075            instantiated to an empty list, then we should pass a
15076            non-NULL empty vector to tell build_new that it was an
15077            empty initializer() rather than no initializer.  This can
15078            only happen when the initializer is a pack expansion whose
15079            parameter packs are of length zero.  */
15080         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
15081           init_vec = NULL;
15082         else
15083           {
15084             init_vec = make_tree_vector ();
15085             if (init == void_node)
15086               gcc_assert (init_vec != NULL);
15087             else
15088               {
15089                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
15090                   vec_safe_push (init_vec, TREE_VALUE (init));
15091               }
15092           }
15093
15094         tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
15095         tree op2 = RECUR (TREE_OPERAND (t, 2));
15096         ret = build_new (&placement_vec, op1, op2, &init_vec,
15097                          NEW_EXPR_USE_GLOBAL (t),
15098                          complain);
15099
15100         if (placement_vec != NULL)
15101           release_tree_vector (placement_vec);
15102         if (init_vec != NULL)
15103           release_tree_vector (init_vec);
15104
15105         RETURN (ret);
15106       }
15107
15108     case DELETE_EXPR:
15109       {
15110         tree op0 = RECUR (TREE_OPERAND (t, 0));
15111         tree op1 = RECUR (TREE_OPERAND (t, 1));
15112         RETURN (delete_sanity (op0, op1,
15113                                DELETE_EXPR_USE_VEC (t),
15114                                DELETE_EXPR_USE_GLOBAL (t),
15115                                complain));
15116       }
15117
15118     case COMPOUND_EXPR:
15119       {
15120         tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
15121                                           complain & ~tf_decltype, in_decl,
15122                                           /*function_p=*/false,
15123                                           integral_constant_expression_p);
15124         RETURN (build_x_compound_expr (EXPR_LOCATION (t),
15125                                        op0,
15126                                        RECUR (TREE_OPERAND (t, 1)),
15127                                        complain|decltype_flag));
15128       }
15129
15130     case CALL_EXPR:
15131       {
15132         tree function;
15133         vec<tree, va_gc> *call_args;
15134         unsigned int nargs, i;
15135         bool qualified_p;
15136         bool koenig_p;
15137         tree ret;
15138
15139         function = CALL_EXPR_FN (t);
15140         /* When we parsed the expression,  we determined whether or
15141            not Koenig lookup should be performed.  */
15142         koenig_p = KOENIG_LOOKUP_P (t);
15143         if (TREE_CODE (function) == SCOPE_REF)
15144           {
15145             qualified_p = true;
15146             function = tsubst_qualified_id (function, args, complain, in_decl,
15147                                             /*done=*/false,
15148                                             /*address_p=*/false);
15149           }
15150         else if (koenig_p && identifier_p (function))
15151           {
15152             /* Do nothing; calling tsubst_copy_and_build on an identifier
15153                would incorrectly perform unqualified lookup again.
15154
15155                Note that we can also have an IDENTIFIER_NODE if the earlier
15156                unqualified lookup found a member function; in that case
15157                koenig_p will be false and we do want to do the lookup
15158                again to find the instantiated member function.
15159
15160                FIXME but doing that causes c++/15272, so we need to stop
15161                using IDENTIFIER_NODE in that situation.  */
15162             qualified_p = false;
15163           }
15164         else
15165           {
15166             if (TREE_CODE (function) == COMPONENT_REF)
15167               {
15168                 tree op = TREE_OPERAND (function, 1);
15169
15170                 qualified_p = (TREE_CODE (op) == SCOPE_REF
15171                                || (BASELINK_P (op)
15172                                    && BASELINK_QUALIFIED_P (op)));
15173               }
15174             else
15175               qualified_p = false;
15176
15177             if (TREE_CODE (function) == ADDR_EXPR
15178                 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
15179               /* Avoid error about taking the address of a constructor.  */
15180               function = TREE_OPERAND (function, 0);
15181
15182             function = tsubst_copy_and_build (function, args, complain,
15183                                               in_decl,
15184                                               !qualified_p,
15185                                               integral_constant_expression_p);
15186
15187             if (BASELINK_P (function))
15188               qualified_p = true;
15189           }
15190
15191         nargs = call_expr_nargs (t);
15192         call_args = make_tree_vector ();
15193         for (i = 0; i < nargs; ++i)
15194           {
15195             tree arg = CALL_EXPR_ARG (t, i);
15196
15197             if (!PACK_EXPANSION_P (arg))
15198               vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
15199             else
15200               {
15201                 /* Expand the pack expansion and push each entry onto
15202                    CALL_ARGS.  */
15203                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
15204                 if (TREE_CODE (arg) == TREE_VEC)
15205                   {
15206                     unsigned int len, j;
15207
15208                     len = TREE_VEC_LENGTH (arg);
15209                     for (j = 0; j < len; ++j)
15210                       {
15211                         tree value = TREE_VEC_ELT (arg, j);
15212                         if (value != NULL_TREE)
15213                           value = convert_from_reference (value);
15214                         vec_safe_push (call_args, value);
15215                       }
15216                   }
15217                 else
15218                   {
15219                     /* A partial substitution.  Add one entry.  */
15220                     vec_safe_push (call_args, arg);
15221                   }
15222               }
15223           }
15224
15225         /* We do not perform argument-dependent lookup if normal
15226            lookup finds a non-function, in accordance with the
15227            expected resolution of DR 218.  */
15228         if (koenig_p
15229             && ((is_overloaded_fn (function)
15230                  /* If lookup found a member function, the Koenig lookup is
15231                     not appropriate, even if an unqualified-name was used
15232                     to denote the function.  */
15233                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
15234                 || identifier_p (function))
15235             /* Only do this when substitution turns a dependent call
15236                into a non-dependent call.  */
15237             && type_dependent_expression_p_push (t)
15238             && !any_type_dependent_arguments_p (call_args))
15239           function = perform_koenig_lookup (function, call_args, tf_none);
15240
15241         if (identifier_p (function)
15242             && !any_type_dependent_arguments_p (call_args))
15243           {
15244             if (koenig_p && (complain & tf_warning_or_error))
15245               {
15246                 /* For backwards compatibility and good diagnostics, try
15247                    the unqualified lookup again if we aren't in SFINAE
15248                    context.  */
15249                 tree unq = (tsubst_copy_and_build
15250                             (function, args, complain, in_decl, true,
15251                              integral_constant_expression_p));
15252                 if (unq == error_mark_node)
15253                   RETURN (error_mark_node);
15254
15255                 if (unq != function)
15256                   {
15257                     tree fn = unq;
15258                     if (INDIRECT_REF_P (fn))
15259                       fn = TREE_OPERAND (fn, 0);
15260                     if (TREE_CODE (fn) == COMPONENT_REF)
15261                       fn = TREE_OPERAND (fn, 1);
15262                     if (is_overloaded_fn (fn))
15263                       fn = get_first_fn (fn);
15264                     if (permerror (EXPR_LOC_OR_LOC (t, input_location),
15265                                    "%qD was not declared in this scope, "
15266                                    "and no declarations were found by "
15267                                    "argument-dependent lookup at the point "
15268                                    "of instantiation", function))
15269                       {
15270                         if (!DECL_P (fn))
15271                           /* Can't say anything more.  */;
15272                         else if (DECL_CLASS_SCOPE_P (fn))
15273                           {
15274                             location_t loc = EXPR_LOC_OR_LOC (t,
15275                                                               input_location);
15276                             inform (loc,
15277                                     "declarations in dependent base %qT are "
15278                                     "not found by unqualified lookup",
15279                                     DECL_CLASS_CONTEXT (fn));
15280                             if (current_class_ptr)
15281                               inform (loc,
15282                                       "use %<this->%D%> instead", function);
15283                             else
15284                               inform (loc,
15285                                       "use %<%T::%D%> instead",
15286                                       current_class_name, function);
15287                           }
15288                         else
15289                           inform (0, "%q+D declared here, later in the "
15290                                   "translation unit", fn);
15291                       }
15292                     function = unq;
15293                   }
15294               }
15295             if (identifier_p (function))
15296               {
15297                 if (complain & tf_error)
15298                   unqualified_name_lookup_error (function);
15299                 release_tree_vector (call_args);
15300                 RETURN (error_mark_node);
15301               }
15302           }
15303
15304         /* Remember that there was a reference to this entity.  */
15305         if (DECL_P (function))
15306           mark_used (function, complain);
15307
15308         /* Put back tf_decltype for the actual call.  */
15309         complain |= decltype_flag;
15310
15311         if (TREE_CODE (function) == OFFSET_REF)
15312           ret = build_offset_ref_call_from_tree (function, &call_args,
15313                                                  complain);
15314         else if (TREE_CODE (function) == COMPONENT_REF)
15315           {
15316             tree instance = TREE_OPERAND (function, 0);
15317             tree fn = TREE_OPERAND (function, 1);
15318
15319             if (processing_template_decl
15320                 && (type_dependent_expression_p (instance)
15321                     || (!BASELINK_P (fn)
15322                         && TREE_CODE (fn) != FIELD_DECL)
15323                     || type_dependent_expression_p (fn)
15324                     || any_type_dependent_arguments_p (call_args)))
15325               ret = build_nt_call_vec (function, call_args);
15326             else if (!BASELINK_P (fn))
15327               ret = finish_call_expr (function, &call_args,
15328                                        /*disallow_virtual=*/false,
15329                                        /*koenig_p=*/false,
15330                                        complain);
15331             else
15332               ret = (build_new_method_call
15333                       (instance, fn,
15334                        &call_args, NULL_TREE,
15335                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
15336                        /*fn_p=*/NULL,
15337                        complain));
15338           }
15339         else
15340           ret = finish_call_expr (function, &call_args,
15341                                   /*disallow_virtual=*/qualified_p,
15342                                   koenig_p,
15343                                   complain);
15344
15345         release_tree_vector (call_args);
15346
15347         RETURN (ret);
15348       }
15349
15350     case COND_EXPR:
15351       {
15352         tree cond = RECUR (TREE_OPERAND (t, 0));
15353         tree folded_cond = fold_non_dependent_expr (cond);
15354         tree exp1, exp2;
15355
15356         if (TREE_CODE (folded_cond) == INTEGER_CST)
15357           {
15358             if (integer_zerop (folded_cond))
15359               {
15360                 ++c_inhibit_evaluation_warnings;
15361                 exp1 = RECUR (TREE_OPERAND (t, 1));
15362                 --c_inhibit_evaluation_warnings;
15363                 exp2 = RECUR (TREE_OPERAND (t, 2));
15364               }
15365             else
15366               {
15367                 exp1 = RECUR (TREE_OPERAND (t, 1));
15368                 ++c_inhibit_evaluation_warnings;
15369                 exp2 = RECUR (TREE_OPERAND (t, 2));
15370                 --c_inhibit_evaluation_warnings;
15371               }
15372             cond = folded_cond;
15373           }
15374         else
15375           {
15376             exp1 = RECUR (TREE_OPERAND (t, 1));
15377             exp2 = RECUR (TREE_OPERAND (t, 2));
15378           }
15379
15380         RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
15381                                          cond, exp1, exp2, complain));
15382       }
15383
15384     case PSEUDO_DTOR_EXPR:
15385       {
15386         tree op0 = RECUR (TREE_OPERAND (t, 0));
15387         tree op1 = RECUR (TREE_OPERAND (t, 1));
15388         tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
15389         RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
15390                                                input_location));
15391       }
15392
15393     case TREE_LIST:
15394       {
15395         tree purpose, value, chain;
15396
15397         if (t == void_list_node)
15398           RETURN (t);
15399
15400         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
15401             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
15402           {
15403             /* We have pack expansions, so expand those and
15404                create a new list out of it.  */
15405             tree purposevec = NULL_TREE;
15406             tree valuevec = NULL_TREE;
15407             tree chain;
15408             int i, len = -1;
15409
15410             /* Expand the argument expressions.  */
15411             if (TREE_PURPOSE (t))
15412               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
15413                                                  complain, in_decl);
15414             if (TREE_VALUE (t))
15415               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
15416                                                complain, in_decl);
15417
15418             /* Build the rest of the list.  */
15419             chain = TREE_CHAIN (t);
15420             if (chain && chain != void_type_node)
15421               chain = RECUR (chain);
15422
15423             /* Determine the number of arguments.  */
15424             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
15425               {
15426                 len = TREE_VEC_LENGTH (purposevec);
15427                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15428               }
15429             else if (TREE_CODE (valuevec) == TREE_VEC)
15430               len = TREE_VEC_LENGTH (valuevec);
15431             else
15432               {
15433                 /* Since we only performed a partial substitution into
15434                    the argument pack, we only RETURN (a single list
15435                    node.  */
15436                 if (purposevec == TREE_PURPOSE (t)
15437                     && valuevec == TREE_VALUE (t)
15438                     && chain == TREE_CHAIN (t))
15439                   RETURN (t);
15440
15441                 RETURN (tree_cons (purposevec, valuevec, chain));
15442               }
15443             
15444             /* Convert the argument vectors into a TREE_LIST */
15445             i = len;
15446             while (i > 0)
15447               {
15448                 /* Grab the Ith values.  */
15449                 i--;
15450                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
15451                                      : NULL_TREE;
15452                 value 
15453                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
15454                              : NULL_TREE;
15455
15456                 /* Build the list (backwards).  */
15457                 chain = tree_cons (purpose, value, chain);
15458               }
15459
15460             RETURN (chain);
15461           }
15462
15463         purpose = TREE_PURPOSE (t);
15464         if (purpose)
15465           purpose = RECUR (purpose);
15466         value = TREE_VALUE (t);
15467         if (value)
15468           value = RECUR (value);
15469         chain = TREE_CHAIN (t);
15470         if (chain && chain != void_type_node)
15471           chain = RECUR (chain);
15472         if (purpose == TREE_PURPOSE (t)
15473             && value == TREE_VALUE (t)
15474             && chain == TREE_CHAIN (t))
15475           RETURN (t);
15476         RETURN (tree_cons (purpose, value, chain));
15477       }
15478
15479     case COMPONENT_REF:
15480       {
15481         tree object;
15482         tree object_type;
15483         tree member;
15484         tree r;
15485
15486         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
15487                                                      args, complain, in_decl);
15488         /* Remember that there was a reference to this entity.  */
15489         if (DECL_P (object))
15490           mark_used (object);
15491         object_type = TREE_TYPE (object);
15492
15493         member = TREE_OPERAND (t, 1);
15494         if (BASELINK_P (member))
15495           member = tsubst_baselink (member,
15496                                     non_reference (TREE_TYPE (object)),
15497                                     args, complain, in_decl);
15498         else
15499           member = tsubst_copy (member, args, complain, in_decl);
15500         if (member == error_mark_node)
15501           RETURN (error_mark_node);
15502
15503         if (type_dependent_expression_p (object))
15504           /* We can't do much here.  */;
15505         else if (!CLASS_TYPE_P (object_type))
15506           {
15507             if (scalarish_type_p (object_type))
15508               {
15509                 tree s = NULL_TREE;
15510                 tree dtor = member;
15511
15512                 if (TREE_CODE (dtor) == SCOPE_REF)
15513                   {
15514                     s = TREE_OPERAND (dtor, 0);
15515                     dtor = TREE_OPERAND (dtor, 1);
15516                   }
15517                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
15518                   {
15519                     dtor = TREE_OPERAND (dtor, 0);
15520                     if (TYPE_P (dtor))
15521                       RETURN (finish_pseudo_destructor_expr
15522                               (object, s, dtor, input_location));
15523                   }
15524               }
15525           }
15526         else if (TREE_CODE (member) == SCOPE_REF
15527                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
15528           {
15529             /* Lookup the template functions now that we know what the
15530                scope is.  */
15531             tree scope = TREE_OPERAND (member, 0);
15532             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
15533             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
15534             member = lookup_qualified_name (scope, tmpl,
15535                                             /*is_type_p=*/false,
15536                                             /*complain=*/false);
15537             if (BASELINK_P (member))
15538               {
15539                 BASELINK_FUNCTIONS (member)
15540                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
15541                               args);
15542                 member = (adjust_result_of_qualified_name_lookup
15543                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
15544                            object_type));
15545               }
15546             else
15547               {
15548                 qualified_name_lookup_error (scope, tmpl, member,
15549                                              input_location);
15550                 RETURN (error_mark_node);
15551               }
15552           }
15553         else if (TREE_CODE (member) == SCOPE_REF
15554                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
15555                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
15556           {
15557             if (complain & tf_error)
15558               {
15559                 if (TYPE_P (TREE_OPERAND (member, 0)))
15560                   error ("%qT is not a class or namespace",
15561                          TREE_OPERAND (member, 0));
15562                 else
15563                   error ("%qD is not a class or namespace",
15564                          TREE_OPERAND (member, 0));
15565               }
15566             RETURN (error_mark_node);
15567           }
15568         else if (TREE_CODE (member) == FIELD_DECL)
15569           {
15570             r = finish_non_static_data_member (member, object, NULL_TREE);
15571             if (TREE_CODE (r) == COMPONENT_REF)
15572               REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
15573             RETURN (r);
15574           }
15575
15576         r = finish_class_member_access_expr (object, member,
15577                                              /*template_p=*/false,
15578                                              complain);
15579         if (TREE_CODE (r) == COMPONENT_REF)
15580           REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
15581         RETURN (r);
15582       }
15583
15584     case THROW_EXPR:
15585       RETURN (build_throw
15586         (RECUR (TREE_OPERAND (t, 0))));
15587
15588     case CONSTRUCTOR:
15589       {
15590         vec<constructor_elt, va_gc> *n;
15591         constructor_elt *ce;
15592         unsigned HOST_WIDE_INT idx;
15593         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15594         bool process_index_p;
15595         int newlen;
15596         bool need_copy_p = false;
15597         tree r;
15598
15599         if (type == error_mark_node)
15600           RETURN (error_mark_node);
15601
15602         /* digest_init will do the wrong thing if we let it.  */
15603         if (type && TYPE_PTRMEMFUNC_P (type))
15604           RETURN (t);
15605
15606         /* We do not want to process the index of aggregate
15607            initializers as they are identifier nodes which will be
15608            looked up by digest_init.  */
15609         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
15610
15611         n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
15612         newlen = vec_safe_length (n);
15613         FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
15614           {
15615             if (ce->index && process_index_p
15616                 /* An identifier index is looked up in the type
15617                    being initialized, not the current scope.  */
15618                 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
15619               ce->index = RECUR (ce->index);
15620
15621             if (PACK_EXPANSION_P (ce->value))
15622               {
15623                 /* Substitute into the pack expansion.  */
15624                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
15625                                                   in_decl);
15626
15627                 if (ce->value == error_mark_node
15628                     || PACK_EXPANSION_P (ce->value))
15629                   ;
15630                 else if (TREE_VEC_LENGTH (ce->value) == 1)
15631                   /* Just move the argument into place.  */
15632                   ce->value = TREE_VEC_ELT (ce->value, 0);
15633                 else
15634                   {
15635                     /* Update the length of the final CONSTRUCTOR
15636                        arguments vector, and note that we will need to
15637                        copy.*/
15638                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
15639                     need_copy_p = true;
15640                   }
15641               }
15642             else
15643               ce->value = RECUR (ce->value);
15644           }
15645
15646         if (need_copy_p)
15647           {
15648             vec<constructor_elt, va_gc> *old_n = n;
15649
15650             vec_alloc (n, newlen);
15651             FOR_EACH_VEC_ELT (*old_n, idx, ce)
15652               {
15653                 if (TREE_CODE (ce->value) == TREE_VEC)
15654                   {
15655                     int i, len = TREE_VEC_LENGTH (ce->value);
15656                     for (i = 0; i < len; ++i)
15657                       CONSTRUCTOR_APPEND_ELT (n, 0,
15658                                               TREE_VEC_ELT (ce->value, i));
15659                   }
15660                 else
15661                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
15662               }
15663           }
15664
15665         r = build_constructor (init_list_type_node, n);
15666         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
15667
15668         if (TREE_HAS_CONSTRUCTOR (t))
15669           RETURN (finish_compound_literal (type, r, complain));
15670
15671         TREE_TYPE (r) = type;
15672         RETURN (r);
15673       }
15674
15675     case TYPEID_EXPR:
15676       {
15677         tree operand_0 = TREE_OPERAND (t, 0);
15678         if (TYPE_P (operand_0))
15679           {
15680             operand_0 = tsubst (operand_0, args, complain, in_decl);
15681             RETURN (get_typeid (operand_0, complain));
15682           }
15683         else
15684           {
15685             operand_0 = RECUR (operand_0);
15686             RETURN (build_typeid (operand_0, complain));
15687           }
15688       }
15689
15690     case VAR_DECL:
15691       if (!args)
15692         RETURN (t);
15693       else if (DECL_PACK_P (t))
15694         {
15695           /* We don't build decls for an instantiation of a
15696              variadic capture proxy, we instantiate the elements
15697              when needed.  */
15698           gcc_assert (DECL_HAS_VALUE_EXPR_P (t));
15699           return RECUR (DECL_VALUE_EXPR (t));
15700         }
15701       /* Fall through */
15702
15703     case PARM_DECL:
15704       {
15705         tree r = tsubst_copy (t, args, complain, in_decl);
15706         /* ??? We're doing a subset of finish_id_expression here.  */
15707         if (VAR_P (r)
15708             && !processing_template_decl
15709             && !cp_unevaluated_operand
15710             && (TREE_STATIC (r) || DECL_EXTERNAL (r))
15711             && DECL_THREAD_LOCAL_P (r))
15712           {
15713             if (tree wrap = get_tls_wrapper_fn (r))
15714               /* Replace an evaluated use of the thread_local variable with
15715                  a call to its wrapper.  */
15716               r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
15717           }
15718         else if (outer_automatic_var_p (r))
15719           {
15720             r = process_outer_var_ref (r, complain);
15721             if (is_capture_proxy (r))
15722               register_local_specialization (r, t);
15723           }
15724
15725         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
15726           /* If the original type was a reference, we'll be wrapped in
15727              the appropriate INDIRECT_REF.  */
15728           r = convert_from_reference (r);
15729         RETURN (r);
15730       }
15731
15732     case VA_ARG_EXPR:
15733       {
15734         tree op0 = RECUR (TREE_OPERAND (t, 0));
15735         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15736         RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
15737       }
15738
15739     case OFFSETOF_EXPR:
15740       RETURN (finish_offsetof (RECUR (TREE_OPERAND (t, 0)),
15741                                EXPR_LOCATION (t)));
15742
15743     case TRAIT_EXPR:
15744       {
15745         tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
15746                              complain, in_decl);
15747
15748         tree type2 = TRAIT_EXPR_TYPE2 (t);
15749         if (type2 && TREE_CODE (type2) == TREE_LIST)
15750           type2 = RECUR (type2);
15751         else if (type2)
15752           type2 = tsubst (type2, args, complain, in_decl);
15753         
15754         RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
15755       }
15756
15757     case STMT_EXPR:
15758       {
15759         tree old_stmt_expr = cur_stmt_expr;
15760         tree stmt_expr = begin_stmt_expr ();
15761
15762         cur_stmt_expr = stmt_expr;
15763         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
15764                      integral_constant_expression_p);
15765         stmt_expr = finish_stmt_expr (stmt_expr, false);
15766         cur_stmt_expr = old_stmt_expr;
15767
15768         /* If the resulting list of expression statement is empty,
15769            fold it further into void_node.  */
15770         if (empty_expr_stmt_p (stmt_expr))
15771           stmt_expr = void_node;
15772
15773         RETURN (stmt_expr);
15774       }
15775
15776     case LAMBDA_EXPR:
15777       {
15778         tree r = build_lambda_expr ();
15779
15780         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
15781         LAMBDA_EXPR_CLOSURE (r) = type;
15782         CLASSTYPE_LAMBDA_EXPR (type) = r;
15783
15784         LAMBDA_EXPR_LOCATION (r)
15785           = LAMBDA_EXPR_LOCATION (t);
15786         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
15787           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
15788         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
15789         LAMBDA_EXPR_DISCRIMINATOR (r)
15790           = (LAMBDA_EXPR_DISCRIMINATOR (t));
15791         /* For a function scope, we want to use tsubst so that we don't
15792            complain about referring to an auto function before its return
15793            type has been deduced.  Otherwise, we want to use tsubst_copy so
15794            that we look up the existing field/parameter/variable rather
15795            than build a new one.  */
15796         tree scope = LAMBDA_EXPR_EXTRA_SCOPE (t);
15797         if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15798           scope = tsubst (scope, args, complain, in_decl);
15799         else if (scope && TREE_CODE (scope) == PARM_DECL)
15800           {
15801             /* Look up the parameter we want directly, as tsubst_copy
15802                doesn't do what we need.  */
15803             tree fn = tsubst (DECL_CONTEXT (scope), args, complain, in_decl);
15804             tree parm = FUNCTION_FIRST_USER_PARM (fn);
15805             while (DECL_PARM_INDEX (parm) != DECL_PARM_INDEX (scope))
15806               parm = DECL_CHAIN (parm);
15807             scope = parm;
15808             /* FIXME Work around the parm not having DECL_CONTEXT set.  */
15809             if (DECL_CONTEXT (scope) == NULL_TREE)
15810               DECL_CONTEXT (scope) = fn;
15811           }
15812         else
15813           scope = RECUR (scope);
15814         LAMBDA_EXPR_EXTRA_SCOPE (r) = scope;
15815         LAMBDA_EXPR_RETURN_TYPE (r)
15816           = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
15817
15818         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
15819                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
15820
15821         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
15822         determine_visibility (TYPE_NAME (type));
15823         /* Now that we know visibility, instantiate the type so we have a
15824            declaration of the op() for later calls to lambda_function.  */
15825         complete_type (type);
15826
15827         LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
15828
15829         RETURN (build_lambda_object (r));
15830       }
15831
15832     case TARGET_EXPR:
15833       /* We can get here for a constant initializer of non-dependent type.
15834          FIXME stop folding in cp_parser_initializer_clause.  */
15835       {
15836         tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
15837                                          complain);
15838         RETURN (r);
15839       }
15840
15841     case TRANSACTION_EXPR:
15842       RETURN (tsubst_expr(t, args, complain, in_decl,
15843              integral_constant_expression_p));
15844
15845     case PAREN_EXPR:
15846       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
15847
15848     case VEC_PERM_EXPR:
15849       {
15850         tree op0 = RECUR (TREE_OPERAND (t, 0));
15851         tree op1 = RECUR (TREE_OPERAND (t, 1));
15852         tree op2 = RECUR (TREE_OPERAND (t, 2));
15853         RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
15854                                        complain));
15855       }
15856
15857     default:
15858       /* Handle Objective-C++ constructs, if appropriate.  */
15859       {
15860         tree subst
15861           = objcp_tsubst_copy_and_build (t, args, complain,
15862                                          in_decl, /*function_p=*/false);
15863         if (subst)
15864           RETURN (subst);
15865       }
15866       RETURN (tsubst_copy (t, args, complain, in_decl));
15867     }
15868
15869 #undef RECUR
15870 #undef RETURN
15871  out:
15872   input_location = loc;
15873   return retval;
15874 }
15875
15876 /* Verify that the instantiated ARGS are valid. For type arguments,
15877    make sure that the type's linkage is ok. For non-type arguments,
15878    make sure they are constants if they are integral or enumerations.
15879    Emit an error under control of COMPLAIN, and return TRUE on error.  */
15880
15881 static bool
15882 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
15883 {
15884   if (dependent_template_arg_p (t))
15885     return false;
15886   if (ARGUMENT_PACK_P (t))
15887     {
15888       tree vec = ARGUMENT_PACK_ARGS (t);
15889       int len = TREE_VEC_LENGTH (vec);
15890       bool result = false;
15891       int i;
15892
15893       for (i = 0; i < len; ++i)
15894         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
15895           result = true;
15896       return result;
15897     }
15898   else if (TYPE_P (t))
15899     {
15900       /* [basic.link]: A name with no linkage (notably, the name
15901          of a class or enumeration declared in a local scope)
15902          shall not be used to declare an entity with linkage.
15903          This implies that names with no linkage cannot be used as
15904          template arguments
15905
15906          DR 757 relaxes this restriction for C++0x.  */
15907       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
15908                  : no_linkage_check (t, /*relaxed_p=*/false));
15909
15910       if (nt)
15911         {
15912           /* DR 488 makes use of a type with no linkage cause
15913              type deduction to fail.  */
15914           if (complain & tf_error)
15915             {
15916               if (TYPE_ANONYMOUS_P (nt))
15917                 error ("%qT is/uses anonymous type", t);
15918               else
15919                 error ("template argument for %qD uses local type %qT",
15920                        tmpl, t);
15921             }
15922           return true;
15923         }
15924       /* In order to avoid all sorts of complications, we do not
15925          allow variably-modified types as template arguments.  */
15926       else if (variably_modified_type_p (t, NULL_TREE))
15927         {
15928           if (complain & tf_error)
15929             error ("%qT is a variably modified type", t);
15930           return true;
15931         }
15932     }
15933   /* Class template and alias template arguments should be OK.  */
15934   else if (DECL_TYPE_TEMPLATE_P (t))
15935     ;
15936   /* A non-type argument of integral or enumerated type must be a
15937      constant.  */
15938   else if (TREE_TYPE (t)
15939            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
15940            && !REFERENCE_REF_P (t)
15941            && !TREE_CONSTANT (t))
15942     {
15943       if (complain & tf_error)
15944         error ("integral expression %qE is not constant", t);
15945       return true;
15946     }
15947   return false;
15948 }
15949
15950 static bool
15951 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
15952 {
15953   int ix, len = DECL_NTPARMS (tmpl);
15954   bool result = false;
15955
15956   for (ix = 0; ix != len; ix++)
15957     {
15958       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
15959         result = true;
15960     }
15961   if (result && (complain & tf_error))
15962     error ("  trying to instantiate %qD", tmpl);
15963   return result;
15964 }
15965
15966 /* We're out of SFINAE context now, so generate diagnostics for the access
15967    errors we saw earlier when instantiating D from TMPL and ARGS.  */
15968
15969 static void
15970 recheck_decl_substitution (tree d, tree tmpl, tree args)
15971 {
15972   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
15973   tree type = TREE_TYPE (pattern);
15974   location_t loc = input_location;
15975
15976   push_access_scope (d);
15977   push_deferring_access_checks (dk_no_deferred);
15978   input_location = DECL_SOURCE_LOCATION (pattern);
15979   tsubst (type, args, tf_warning_or_error, d);
15980   input_location = loc;
15981   pop_deferring_access_checks ();
15982   pop_access_scope (d);
15983 }
15984
15985 /* Instantiate the indicated variable, function, or alias template TMPL with
15986    the template arguments in TARG_PTR.  */
15987
15988 static tree
15989 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
15990 {
15991   tree targ_ptr = orig_args;
15992   tree fndecl;
15993   tree gen_tmpl;
15994   tree spec;
15995   bool access_ok = true;
15996
15997   if (tmpl == error_mark_node)
15998     return error_mark_node;
15999
16000   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
16001
16002   /* If this function is a clone, handle it specially.  */
16003   if (DECL_CLONED_FUNCTION_P (tmpl))
16004     {
16005       tree spec;
16006       tree clone;
16007
16008       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
16009          DECL_CLONED_FUNCTION.  */
16010       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
16011                                    targ_ptr, complain);
16012       if (spec == error_mark_node)
16013         return error_mark_node;
16014
16015       /* Look for the clone.  */
16016       FOR_EACH_CLONE (clone, spec)
16017         if (DECL_NAME (clone) == DECL_NAME (tmpl))
16018           return clone;
16019       /* We should always have found the clone by now.  */
16020       gcc_unreachable ();
16021       return NULL_TREE;
16022     }
16023
16024   if (targ_ptr == error_mark_node)
16025     return error_mark_node;
16026
16027   /* Check to see if we already have this specialization.  */
16028   gen_tmpl = most_general_template (tmpl);
16029   if (tmpl != gen_tmpl)
16030     /* The TMPL is a partial instantiation.  To get a full set of
16031        arguments we must add the arguments used to perform the
16032        partial instantiation.  */
16033     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
16034                                             targ_ptr);
16035
16036   /* It would be nice to avoid hashing here and then again in tsubst_decl,
16037      but it doesn't seem to be on the hot path.  */
16038   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
16039
16040   gcc_assert (tmpl == gen_tmpl
16041               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
16042                   == spec)
16043               || fndecl == NULL_TREE);
16044
16045   if (spec != NULL_TREE)
16046     {
16047       if (FNDECL_HAS_ACCESS_ERRORS (spec))
16048         {
16049           if (complain & tf_error)
16050             recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
16051           return error_mark_node;
16052         }
16053       return spec;
16054     }
16055
16056   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
16057                                complain))
16058     return error_mark_node;
16059
16060   /* We are building a FUNCTION_DECL, during which the access of its
16061      parameters and return types have to be checked.  However this
16062      FUNCTION_DECL which is the desired context for access checking
16063      is not built yet.  We solve this chicken-and-egg problem by
16064      deferring all checks until we have the FUNCTION_DECL.  */
16065   push_deferring_access_checks (dk_deferred);
16066
16067   /* Instantiation of the function happens in the context of the function
16068      template, not the context of the overload resolution we're doing.  */
16069   push_to_top_level ();
16070   /* If there are dependent arguments, e.g. because we're doing partial
16071      ordering, make sure processing_template_decl stays set.  */
16072   if (uses_template_parms (targ_ptr))
16073     ++processing_template_decl;
16074   if (DECL_CLASS_SCOPE_P (gen_tmpl))
16075     {
16076       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
16077                                    complain, gen_tmpl, true);
16078       push_nested_class (ctx);
16079     }
16080
16081   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
16082
16083   if (VAR_P (pattern))
16084     {
16085       /* We need to determine if we're using a partial or explicit
16086          specialization now, because the type of the variable could be
16087          different.  */
16088       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
16089       tree elt = most_specialized_partial_spec (tid, complain);
16090       if (elt == error_mark_node)
16091         pattern = error_mark_node;
16092       else if (elt)
16093         {
16094           tmpl = TREE_VALUE (elt);
16095           pattern = DECL_TEMPLATE_RESULT (tmpl);
16096           targ_ptr = TREE_PURPOSE (elt);
16097         }
16098     }
16099
16100   /* Substitute template parameters to obtain the specialization.  */
16101   fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
16102   if (DECL_CLASS_SCOPE_P (gen_tmpl))
16103     pop_nested_class ();
16104   pop_from_top_level ();
16105
16106   if (fndecl == error_mark_node)
16107     {
16108       pop_deferring_access_checks ();
16109       return error_mark_node;
16110     }
16111
16112   /* The DECL_TI_TEMPLATE should always be the immediate parent
16113      template, not the most general template.  */
16114   DECL_TI_TEMPLATE (fndecl) = tmpl;
16115
16116   /* Now we know the specialization, compute access previously
16117      deferred.  */
16118   push_access_scope (fndecl);
16119   if (!perform_deferred_access_checks (complain))
16120     access_ok = false;
16121   pop_access_scope (fndecl);
16122   pop_deferring_access_checks ();
16123
16124   /* If we've just instantiated the main entry point for a function,
16125      instantiate all the alternate entry points as well.  We do this
16126      by cloning the instantiation of the main entry point, not by
16127      instantiating the template clones.  */
16128   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
16129     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
16130
16131   if (!access_ok)
16132     {
16133       if (!(complain & tf_error))
16134         {
16135           /* Remember to reinstantiate when we're out of SFINAE so the user
16136              can see the errors.  */
16137           FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
16138         }
16139       return error_mark_node;
16140     }
16141   return fndecl;
16142 }
16143
16144 /* Wrapper for instantiate_template_1.  */
16145
16146 tree
16147 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
16148 {
16149   tree ret;
16150   timevar_push (TV_TEMPLATE_INST);
16151   ret = instantiate_template_1 (tmpl, orig_args,  complain);
16152   timevar_pop (TV_TEMPLATE_INST);
16153   return ret;
16154 }
16155
16156 /* Instantiate the alias template TMPL with ARGS.  Also push a template
16157    instantiation level, which instantiate_template doesn't do because
16158    functions and variables have sufficient context established by the
16159    callers.  */
16160
16161 static tree
16162 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
16163 {
16164   struct pending_template *old_last_pend = last_pending_template;
16165   struct tinst_level *old_error_tinst = last_error_tinst_level;
16166   if (tmpl == error_mark_node || args == error_mark_node)
16167     return error_mark_node;
16168   tree tinst = build_tree_list (tmpl, args);
16169   if (!push_tinst_level (tinst))
16170     {
16171       ggc_free (tinst);
16172       return error_mark_node;
16173     }
16174
16175   args =
16176     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
16177                                      args, tmpl, complain,
16178                                      /*require_all_args=*/true,
16179                                      /*use_default_args=*/true);
16180
16181   tree r = instantiate_template (tmpl, args, complain);
16182   pop_tinst_level ();
16183   /* We can't free this if a pending_template entry or last_error_tinst_level
16184      is pointing at it.  */
16185   if (last_pending_template == old_last_pend
16186       && last_error_tinst_level == old_error_tinst)
16187     ggc_free (tinst);
16188
16189   return r;
16190 }
16191
16192 /* PARM is a template parameter pack for FN.  Returns true iff
16193    PARM is used in a deducible way in the argument list of FN.  */
16194
16195 static bool
16196 pack_deducible_p (tree parm, tree fn)
16197 {
16198   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
16199   for (; t; t = TREE_CHAIN (t))
16200     {
16201       tree type = TREE_VALUE (t);
16202       tree packs;
16203       if (!PACK_EXPANSION_P (type))
16204         continue;
16205       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
16206            packs; packs = TREE_CHAIN (packs))
16207         if (template_args_equal (TREE_VALUE (packs), parm))
16208           {
16209             /* The template parameter pack is used in a function parameter
16210                pack.  If this is the end of the parameter list, the
16211                template parameter pack is deducible.  */
16212             if (TREE_CHAIN (t) == void_list_node)
16213               return true;
16214             else
16215               /* Otherwise, not.  Well, it could be deduced from
16216                  a non-pack parameter, but doing so would end up with
16217                  a deduction mismatch, so don't bother.  */
16218               return false;
16219           }
16220     }
16221   /* The template parameter pack isn't used in any function parameter
16222      packs, but it might be used deeper, e.g. tuple<Args...>.  */
16223   return true;
16224 }
16225
16226 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
16227    NARGS elements of the arguments that are being used when calling
16228    it.  TARGS is a vector into which the deduced template arguments
16229    are placed.
16230
16231    Returns either a FUNCTION_DECL for the matching specialization of FN or
16232    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
16233    true, diagnostics will be printed to explain why it failed.
16234
16235    If FN is a conversion operator, or we are trying to produce a specific
16236    specialization, RETURN_TYPE is the return type desired.
16237
16238    The EXPLICIT_TARGS are explicit template arguments provided via a
16239    template-id.
16240
16241    The parameter STRICT is one of:
16242
16243    DEDUCE_CALL:
16244      We are deducing arguments for a function call, as in
16245      [temp.deduct.call].
16246
16247    DEDUCE_CONV:
16248      We are deducing arguments for a conversion function, as in
16249      [temp.deduct.conv].
16250
16251    DEDUCE_EXACT:
16252      We are deducing arguments when doing an explicit instantiation
16253      as in [temp.explicit], when determining an explicit specialization
16254      as in [temp.expl.spec], or when taking the address of a function
16255      template, as in [temp.deduct.funcaddr].  */
16256
16257 tree
16258 fn_type_unification (tree fn,
16259                      tree explicit_targs,
16260                      tree targs,
16261                      const tree *args,
16262                      unsigned int nargs,
16263                      tree return_type,
16264                      unification_kind_t strict,
16265                      int flags,
16266                      bool explain_p,
16267                      bool decltype_p)
16268 {
16269   tree parms;
16270   tree fntype;
16271   tree decl = NULL_TREE;
16272   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
16273   bool ok;
16274   static int deduction_depth;
16275   struct pending_template *old_last_pend = last_pending_template;
16276   struct tinst_level *old_error_tinst = last_error_tinst_level;
16277   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
16278   tree tinst;
16279   tree r = error_mark_node;
16280
16281   if (decltype_p)
16282     complain |= tf_decltype;
16283
16284   /* In C++0x, it's possible to have a function template whose type depends
16285      on itself recursively.  This is most obvious with decltype, but can also
16286      occur with enumeration scope (c++/48969).  So we need to catch infinite
16287      recursion and reject the substitution at deduction time; this function
16288      will return error_mark_node for any repeated substitution.
16289
16290      This also catches excessive recursion such as when f<N> depends on
16291      f<N-1> across all integers, and returns error_mark_node for all the
16292      substitutions back up to the initial one.
16293
16294      This is, of course, not reentrant.  */
16295   if (excessive_deduction_depth)
16296     return error_mark_node;
16297   tinst = build_tree_list (fn, NULL_TREE);
16298   ++deduction_depth;
16299
16300   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
16301
16302   fntype = TREE_TYPE (fn);
16303   if (explicit_targs)
16304     {
16305       /* [temp.deduct]
16306
16307          The specified template arguments must match the template
16308          parameters in kind (i.e., type, nontype, template), and there
16309          must not be more arguments than there are parameters;
16310          otherwise type deduction fails.
16311
16312          Nontype arguments must match the types of the corresponding
16313          nontype template parameters, or must be convertible to the
16314          types of the corresponding nontype parameters as specified in
16315          _temp.arg.nontype_, otherwise type deduction fails.
16316
16317          All references in the function type of the function template
16318          to the corresponding template parameters are replaced by the
16319          specified template argument values.  If a substitution in a
16320          template parameter or in the function type of the function
16321          template results in an invalid type, type deduction fails.  */
16322       int i, len = TREE_VEC_LENGTH (tparms);
16323       location_t loc = input_location;
16324       bool incomplete = false;
16325
16326       /* Adjust any explicit template arguments before entering the
16327          substitution context.  */
16328       explicit_targs
16329         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
16330                                   complain,
16331                                   /*require_all_args=*/false,
16332                                   /*use_default_args=*/false));
16333       if (explicit_targs == error_mark_node)
16334         goto fail;
16335
16336       /* Substitute the explicit args into the function type.  This is
16337          necessary so that, for instance, explicitly declared function
16338          arguments can match null pointed constants.  If we were given
16339          an incomplete set of explicit args, we must not do semantic
16340          processing during substitution as we could create partial
16341          instantiations.  */
16342       for (i = 0; i < len; i++)
16343         {
16344           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
16345           bool parameter_pack = false;
16346           tree targ = TREE_VEC_ELT (explicit_targs, i);
16347
16348           /* Dig out the actual parm.  */
16349           if (TREE_CODE (parm) == TYPE_DECL
16350               || TREE_CODE (parm) == TEMPLATE_DECL)
16351             {
16352               parm = TREE_TYPE (parm);
16353               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
16354             }
16355           else if (TREE_CODE (parm) == PARM_DECL)
16356             {
16357               parm = DECL_INITIAL (parm);
16358               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
16359             }
16360
16361           if (!parameter_pack && targ == NULL_TREE)
16362             /* No explicit argument for this template parameter.  */
16363             incomplete = true;
16364
16365           if (parameter_pack && pack_deducible_p (parm, fn))
16366             {
16367               /* Mark the argument pack as "incomplete". We could
16368                  still deduce more arguments during unification.
16369                  We remove this mark in type_unification_real.  */
16370               if (targ)
16371                 {
16372                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
16373                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
16374                     = ARGUMENT_PACK_ARGS (targ);
16375                 }
16376
16377               /* We have some incomplete argument packs.  */
16378               incomplete = true;
16379             }
16380         }
16381
16382       TREE_VALUE (tinst) = explicit_targs;
16383       if (!push_tinst_level (tinst))
16384         {
16385           excessive_deduction_depth = true;
16386           goto fail;
16387         }
16388       processing_template_decl += incomplete;
16389       input_location = DECL_SOURCE_LOCATION (fn);
16390       /* Ignore any access checks; we'll see them again in
16391          instantiate_template and they might have the wrong
16392          access path at this point.  */
16393       push_deferring_access_checks (dk_deferred);
16394       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
16395                        complain | tf_partial, NULL_TREE);
16396       pop_deferring_access_checks ();
16397       input_location = loc;
16398       processing_template_decl -= incomplete;
16399       pop_tinst_level ();
16400
16401       if (fntype == error_mark_node)
16402         goto fail;
16403
16404       /* Place the explicitly specified arguments in TARGS.  */
16405       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
16406         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
16407     }
16408
16409   /* Never do unification on the 'this' parameter.  */
16410   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
16411
16412   if (return_type)
16413     {
16414       tree *new_args;
16415
16416       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
16417       new_args = XALLOCAVEC (tree, nargs + 1);
16418       new_args[0] = return_type;
16419       memcpy (new_args + 1, args, nargs * sizeof (tree));
16420       args = new_args;
16421       ++nargs;
16422     }
16423
16424   /* We allow incomplete unification without an error message here
16425      because the standard doesn't seem to explicitly prohibit it.  Our
16426      callers must be ready to deal with unification failures in any
16427      event.  */
16428
16429   TREE_VALUE (tinst) = targs;
16430   /* If we aren't explaining yet, push tinst context so we can see where
16431      any errors (e.g. from class instantiations triggered by instantiation
16432      of default template arguments) come from.  If we are explaining, this
16433      context is redundant.  */
16434   if (!explain_p && !push_tinst_level (tinst))
16435     {
16436       excessive_deduction_depth = true;
16437       goto fail;
16438     }
16439
16440   /* type_unification_real will pass back any access checks from default
16441      template argument substitution.  */
16442   vec<deferred_access_check, va_gc> *checks;
16443   checks = NULL;
16444
16445   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
16446                                targs, parms, args, nargs, /*subr=*/0,
16447                                strict, flags, &checks, explain_p);
16448   if (!explain_p)
16449     pop_tinst_level ();
16450   if (!ok)
16451     goto fail;
16452
16453   /* Now that we have bindings for all of the template arguments,
16454      ensure that the arguments deduced for the template template
16455      parameters have compatible template parameter lists.  We cannot
16456      check this property before we have deduced all template
16457      arguments, because the template parameter types of a template
16458      template parameter might depend on prior template parameters
16459      deduced after the template template parameter.  The following
16460      ill-formed example illustrates this issue:
16461
16462        template<typename T, template<T> class C> void f(C<5>, T);
16463
16464        template<int N> struct X {};
16465
16466        void g() {
16467          f(X<5>(), 5l); // error: template argument deduction fails
16468        }
16469
16470      The template parameter list of 'C' depends on the template type
16471      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
16472      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
16473      time that we deduce 'C'.  */
16474   if (!template_template_parm_bindings_ok_p
16475            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
16476     {
16477       unify_inconsistent_template_template_parameters (explain_p);
16478       goto fail;
16479     }
16480
16481   /* All is well so far.  Now, check:
16482
16483      [temp.deduct]
16484
16485      When all template arguments have been deduced, all uses of
16486      template parameters in nondeduced contexts are replaced with
16487      the corresponding deduced argument values.  If the
16488      substitution results in an invalid type, as described above,
16489      type deduction fails.  */
16490   TREE_VALUE (tinst) = targs;
16491   if (!push_tinst_level (tinst))
16492     {
16493       excessive_deduction_depth = true;
16494       goto fail;
16495     }
16496
16497   /* Also collect access checks from the instantiation.  */
16498   reopen_deferring_access_checks (checks);
16499
16500   decl = instantiate_template (fn, targs, complain);
16501
16502   checks = get_deferred_access_checks ();
16503   pop_deferring_access_checks ();
16504
16505   pop_tinst_level ();
16506
16507   if (decl == error_mark_node)
16508     goto fail;
16509
16510   /* Now perform any access checks encountered during substitution.  */
16511   push_access_scope (decl);
16512   ok = perform_access_checks (checks, complain);
16513   pop_access_scope (decl);
16514   if (!ok)
16515     goto fail;
16516
16517   /* If we're looking for an exact match, check that what we got
16518      is indeed an exact match.  It might not be if some template
16519      parameters are used in non-deduced contexts.  But don't check
16520      for an exact match if we have dependent template arguments;
16521      in that case we're doing partial ordering, and we already know
16522      that we have two candidates that will provide the actual type.  */
16523   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
16524     {
16525       tree substed = TREE_TYPE (decl);
16526       unsigned int i;
16527
16528       tree sarg
16529         = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
16530       if (return_type)
16531         sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
16532       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
16533         if (!same_type_p (args[i], TREE_VALUE (sarg)))
16534           {
16535             unify_type_mismatch (explain_p, args[i],
16536                                  TREE_VALUE (sarg));
16537             goto fail;
16538           }
16539     }
16540
16541   r = decl;
16542
16543  fail:
16544   --deduction_depth;
16545   if (excessive_deduction_depth)
16546     {
16547       if (deduction_depth == 0)
16548         /* Reset once we're all the way out.  */
16549         excessive_deduction_depth = false;
16550     }
16551
16552   /* We can't free this if a pending_template entry or last_error_tinst_level
16553      is pointing at it.  */
16554   if (last_pending_template == old_last_pend
16555       && last_error_tinst_level == old_error_tinst)
16556     ggc_free (tinst);
16557
16558   return r;
16559 }
16560
16561 /* Adjust types before performing type deduction, as described in
16562    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
16563    sections are symmetric.  PARM is the type of a function parameter
16564    or the return type of the conversion function.  ARG is the type of
16565    the argument passed to the call, or the type of the value
16566    initialized with the result of the conversion function.
16567    ARG_EXPR is the original argument expression, which may be null.  */
16568
16569 static int
16570 maybe_adjust_types_for_deduction (unification_kind_t strict,
16571                                   tree* parm,
16572                                   tree* arg,
16573                                   tree arg_expr)
16574 {
16575   int result = 0;
16576
16577   switch (strict)
16578     {
16579     case DEDUCE_CALL:
16580       break;
16581
16582     case DEDUCE_CONV:
16583       {
16584         /* Swap PARM and ARG throughout the remainder of this
16585            function; the handling is precisely symmetric since PARM
16586            will initialize ARG rather than vice versa.  */
16587         tree* temp = parm;
16588         parm = arg;
16589         arg = temp;
16590         break;
16591       }
16592
16593     case DEDUCE_EXACT:
16594       /* Core issue #873: Do the DR606 thing (see below) for these cases,
16595          too, but here handle it by stripping the reference from PARM
16596          rather than by adding it to ARG.  */
16597       if (TREE_CODE (*parm) == REFERENCE_TYPE
16598           && TYPE_REF_IS_RVALUE (*parm)
16599           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
16600           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
16601           && TREE_CODE (*arg) == REFERENCE_TYPE
16602           && !TYPE_REF_IS_RVALUE (*arg))
16603         *parm = TREE_TYPE (*parm);
16604       /* Nothing else to do in this case.  */
16605       return 0;
16606
16607     default:
16608       gcc_unreachable ();
16609     }
16610
16611   if (TREE_CODE (*parm) != REFERENCE_TYPE)
16612     {
16613       /* [temp.deduct.call]
16614
16615          If P is not a reference type:
16616
16617          --If A is an array type, the pointer type produced by the
16618          array-to-pointer standard conversion (_conv.array_) is
16619          used in place of A for type deduction; otherwise,
16620
16621          --If A is a function type, the pointer type produced by
16622          the function-to-pointer standard conversion
16623          (_conv.func_) is used in place of A for type deduction;
16624          otherwise,
16625
16626          --If A is a cv-qualified type, the top level
16627          cv-qualifiers of A's type are ignored for type
16628          deduction.  */
16629       if (TREE_CODE (*arg) == ARRAY_TYPE)
16630         *arg = build_pointer_type (TREE_TYPE (*arg));
16631       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
16632         *arg = build_pointer_type (*arg);
16633       else
16634         *arg = TYPE_MAIN_VARIANT (*arg);
16635     }
16636
16637   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
16638      of the form T&&, where T is a template parameter, and the argument
16639      is an lvalue, T is deduced as A& */
16640   if (TREE_CODE (*parm) == REFERENCE_TYPE
16641       && TYPE_REF_IS_RVALUE (*parm)
16642       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
16643       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
16644       && (arg_expr ? real_lvalue_p (arg_expr)
16645           /* try_one_overload doesn't provide an arg_expr, but
16646              functions are always lvalues.  */
16647           : TREE_CODE (*arg) == FUNCTION_TYPE))
16648     *arg = build_reference_type (*arg);
16649
16650   /* [temp.deduct.call]
16651
16652      If P is a cv-qualified type, the top level cv-qualifiers
16653      of P's type are ignored for type deduction.  If P is a
16654      reference type, the type referred to by P is used for
16655      type deduction.  */
16656   *parm = TYPE_MAIN_VARIANT (*parm);
16657   if (TREE_CODE (*parm) == REFERENCE_TYPE)
16658     {
16659       *parm = TREE_TYPE (*parm);
16660       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
16661     }
16662
16663   /* DR 322. For conversion deduction, remove a reference type on parm
16664      too (which has been swapped into ARG).  */
16665   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
16666     *arg = TREE_TYPE (*arg);
16667
16668   return result;
16669 }
16670
16671 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
16672    template which does contain any deducible template parameters; check if
16673    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
16674    unify_one_argument.  */
16675
16676 static int
16677 check_non_deducible_conversion (tree parm, tree arg, int strict,
16678                                 int flags, bool explain_p)
16679 {
16680   tree type;
16681
16682   if (!TYPE_P (arg))
16683     type = TREE_TYPE (arg);
16684   else
16685     type = arg;
16686
16687   if (same_type_p (parm, type))
16688     return unify_success (explain_p);
16689
16690   if (strict == DEDUCE_CONV)
16691     {
16692       if (can_convert_arg (type, parm, NULL_TREE, flags,
16693                            explain_p ? tf_warning_or_error : tf_none))
16694         return unify_success (explain_p);
16695     }
16696   else if (strict != DEDUCE_EXACT)
16697     {
16698       if (can_convert_arg (parm, type,
16699                            TYPE_P (arg) ? NULL_TREE : arg,
16700                            flags, explain_p ? tf_warning_or_error : tf_none))
16701         return unify_success (explain_p);
16702     }
16703
16704   if (strict == DEDUCE_EXACT)
16705     return unify_type_mismatch (explain_p, parm, arg);
16706   else
16707     return unify_arg_conversion (explain_p, parm, type, arg);
16708 }
16709
16710 static bool uses_deducible_template_parms (tree type);
16711
16712 /* Returns true iff the expression EXPR is one from which a template
16713    argument can be deduced.  In other words, if it's an undecorated
16714    use of a template non-type parameter.  */
16715
16716 static bool
16717 deducible_expression (tree expr)
16718 {
16719   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
16720 }
16721
16722 /* Returns true iff the array domain DOMAIN uses a template parameter in a
16723    deducible way; that is, if it has a max value of <PARM> - 1.  */
16724
16725 static bool
16726 deducible_array_bound (tree domain)
16727 {
16728   if (domain == NULL_TREE)
16729     return false;
16730
16731   tree max = TYPE_MAX_VALUE (domain);
16732   if (TREE_CODE (max) != MINUS_EXPR)
16733     return false;
16734
16735   return deducible_expression (TREE_OPERAND (max, 0));
16736 }
16737
16738 /* Returns true iff the template arguments ARGS use a template parameter
16739    in a deducible way.  */
16740
16741 static bool
16742 deducible_template_args (tree args)
16743 {
16744   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
16745     {
16746       bool deducible;
16747       tree elt = TREE_VEC_ELT (args, i);
16748       if (ARGUMENT_PACK_P (elt))
16749         deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
16750       else
16751         {
16752           if (PACK_EXPANSION_P (elt))
16753             elt = PACK_EXPANSION_PATTERN (elt);
16754           if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
16755             deducible = true;
16756           else if (TYPE_P (elt))
16757             deducible = uses_deducible_template_parms (elt);
16758           else
16759             deducible = deducible_expression (elt);
16760         }
16761       if (deducible)
16762         return true;
16763     }
16764   return false;
16765 }
16766
16767 /* Returns true iff TYPE contains any deducible references to template
16768    parameters, as per 14.8.2.5.  */
16769
16770 static bool
16771 uses_deducible_template_parms (tree type)
16772 {
16773   if (PACK_EXPANSION_P (type))
16774     type = PACK_EXPANSION_PATTERN (type);
16775
16776   /* T
16777      cv-list T
16778      TT<T>
16779      TT<i>
16780      TT<> */
16781   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16782       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16783     return true;
16784
16785   /* T*
16786      T&
16787      T&&  */
16788   if (POINTER_TYPE_P (type))
16789     return uses_deducible_template_parms (TREE_TYPE (type));
16790
16791   /* T[integer-constant ]
16792      type [i]  */
16793   if (TREE_CODE (type) == ARRAY_TYPE)
16794     return (uses_deducible_template_parms (TREE_TYPE (type))
16795             || deducible_array_bound (TYPE_DOMAIN (type)));
16796
16797   /* T type ::*
16798      type T::*
16799      T T::*
16800      T (type ::*)()
16801      type (T::*)()
16802      type (type ::*)(T)
16803      type (T::*)(T)
16804      T (type ::*)(T)
16805      T (T::*)()
16806      T (T::*)(T) */
16807   if (TYPE_PTRMEM_P (type))
16808     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
16809             || (uses_deducible_template_parms
16810                 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
16811
16812   /* template-name <T> (where template-name refers to a class template)
16813      template-name <i> (where template-name refers to a class template) */
16814   if (CLASS_TYPE_P (type)
16815       && CLASSTYPE_TEMPLATE_INFO (type)
16816       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
16817     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
16818                                     (CLASSTYPE_TI_ARGS (type)));
16819
16820   /* type (T)
16821      T()
16822      T(T)  */
16823   if (TREE_CODE (type) == FUNCTION_TYPE
16824       || TREE_CODE (type) == METHOD_TYPE)
16825     {
16826       if (uses_deducible_template_parms (TREE_TYPE (type)))
16827         return true;
16828       tree parm = TYPE_ARG_TYPES (type);
16829       if (TREE_CODE (type) == METHOD_TYPE)
16830         parm = TREE_CHAIN (parm);
16831       for (; parm; parm = TREE_CHAIN (parm))
16832         if (uses_deducible_template_parms (TREE_VALUE (parm)))
16833           return true;
16834     }
16835
16836   return false;
16837 }
16838
16839 /* Subroutine of type_unification_real and unify_pack_expansion to
16840    handle unification of a single P/A pair.  Parameters are as
16841    for those functions.  */
16842
16843 static int
16844 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
16845                     int subr, unification_kind_t strict, int flags,
16846                     bool explain_p)
16847 {
16848   tree arg_expr = NULL_TREE;
16849   int arg_strict;
16850
16851   if (arg == error_mark_node || parm == error_mark_node)
16852     return unify_invalid (explain_p);
16853   if (arg == unknown_type_node)
16854     /* We can't deduce anything from this, but we might get all the
16855        template args from other function args.  */
16856     return unify_success (explain_p);
16857
16858   /* Implicit conversions (Clause 4) will be performed on a function
16859      argument to convert it to the type of the corresponding function
16860      parameter if the parameter type contains no template-parameters that
16861      participate in template argument deduction.  */
16862   if (TYPE_P (parm) && !uses_template_parms (parm))
16863     /* For function parameters that contain no template-parameters at all,
16864        we have historically checked for convertibility in order to shortcut
16865        consideration of this candidate.  */
16866     return check_non_deducible_conversion (parm, arg, strict, flags,
16867                                            explain_p);
16868   else if (strict == DEDUCE_CALL
16869            && TYPE_P (parm) && !uses_deducible_template_parms (parm))
16870     /* For function parameters with only non-deducible template parameters,
16871        just return.  */
16872     return unify_success (explain_p);
16873
16874   switch (strict)
16875     {
16876     case DEDUCE_CALL:
16877       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
16878                     | UNIFY_ALLOW_MORE_CV_QUAL
16879                     | UNIFY_ALLOW_DERIVED);
16880       break;
16881
16882     case DEDUCE_CONV:
16883       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
16884       break;
16885
16886     case DEDUCE_EXACT:
16887       arg_strict = UNIFY_ALLOW_NONE;
16888       break;
16889
16890     default:
16891       gcc_unreachable ();
16892     }
16893
16894   /* We only do these transformations if this is the top-level
16895      parameter_type_list in a call or declaration matching; in other
16896      situations (nested function declarators, template argument lists) we
16897      won't be comparing a type to an expression, and we don't do any type
16898      adjustments.  */
16899   if (!subr)
16900     {
16901       if (!TYPE_P (arg))
16902         {
16903           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
16904           if (type_unknown_p (arg))
16905             {
16906               /* [temp.deduct.type] A template-argument can be
16907                  deduced from a pointer to function or pointer
16908                  to member function argument if the set of
16909                  overloaded functions does not contain function
16910                  templates and at most one of a set of
16911                  overloaded functions provides a unique
16912                  match.  */
16913
16914               if (resolve_overloaded_unification
16915                   (tparms, targs, parm, arg, strict,
16916                    arg_strict, explain_p))
16917                 return unify_success (explain_p);
16918               return unify_overload_resolution_failure (explain_p, arg);
16919             }
16920
16921           arg_expr = arg;
16922           arg = unlowered_expr_type (arg);
16923           if (arg == error_mark_node)
16924             return unify_invalid (explain_p);
16925         }
16926
16927       arg_strict |=
16928         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
16929     }
16930   else
16931     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
16932         != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
16933       return unify_template_argument_mismatch (explain_p, parm, arg);
16934
16935   /* For deduction from an init-list we need the actual list.  */
16936   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
16937     arg = arg_expr;
16938   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
16939 }
16940
16941 /* Most parms like fn_type_unification.
16942
16943    If SUBR is 1, we're being called recursively (to unify the
16944    arguments of a function or method parameter of a function
16945    template).
16946
16947    CHECKS is a pointer to a vector of access checks encountered while
16948    substituting default template arguments.  */
16949
16950 static int
16951 type_unification_real (tree tparms,
16952                        tree targs,
16953                        tree xparms,
16954                        const tree *xargs,
16955                        unsigned int xnargs,
16956                        int subr,
16957                        unification_kind_t strict,
16958                        int flags,
16959                        vec<deferred_access_check, va_gc> **checks,
16960                        bool explain_p)
16961 {
16962   tree parm, arg;
16963   int i;
16964   int ntparms = TREE_VEC_LENGTH (tparms);
16965   int saw_undeduced = 0;
16966   tree parms;
16967   const tree *args;
16968   unsigned int nargs;
16969   unsigned int ia;
16970
16971   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
16972   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
16973   gcc_assert (ntparms > 0);
16974
16975   /* Reset the number of non-defaulted template arguments contained
16976      in TARGS.  */
16977   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
16978
16979  again:
16980   parms = xparms;
16981   args = xargs;
16982   nargs = xnargs;
16983
16984   ia = 0;
16985   while (parms && parms != void_list_node
16986          && ia < nargs)
16987     {
16988       parm = TREE_VALUE (parms);
16989
16990       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
16991           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
16992         /* For a function parameter pack that occurs at the end of the
16993            parameter-declaration-list, the type A of each remaining
16994            argument of the call is compared with the type P of the
16995            declarator-id of the function parameter pack.  */
16996         break;
16997
16998       parms = TREE_CHAIN (parms);
16999
17000       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
17001         /* For a function parameter pack that does not occur at the
17002            end of the parameter-declaration-list, the type of the
17003            parameter pack is a non-deduced context.  */
17004         continue;
17005
17006       arg = args[ia];
17007       ++ia;
17008
17009       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
17010                               flags, explain_p))
17011         return 1;
17012     }
17013
17014   if (parms 
17015       && parms != void_list_node
17016       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
17017     {
17018       /* Unify the remaining arguments with the pack expansion type.  */
17019       tree argvec;
17020       tree parmvec = make_tree_vec (1);
17021
17022       /* Allocate a TREE_VEC and copy in all of the arguments */ 
17023       argvec = make_tree_vec (nargs - ia);
17024       for (i = 0; ia < nargs; ++ia, ++i)
17025         TREE_VEC_ELT (argvec, i) = args[ia];
17026
17027       /* Copy the parameter into parmvec.  */
17028       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
17029       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
17030                                 /*subr=*/subr, explain_p))
17031         return 1;
17032
17033       /* Advance to the end of the list of parameters.  */
17034       parms = TREE_CHAIN (parms);
17035     }
17036
17037   /* Fail if we've reached the end of the parm list, and more args
17038      are present, and the parm list isn't variadic.  */
17039   if (ia < nargs && parms == void_list_node)
17040     return unify_too_many_arguments (explain_p, nargs, ia);
17041   /* Fail if parms are left and they don't have default values and
17042      they aren't all deduced as empty packs (c++/57397).  This is
17043      consistent with sufficient_parms_p.  */
17044   if (parms && parms != void_list_node
17045       && TREE_PURPOSE (parms) == NULL_TREE)
17046     {
17047       unsigned int count = nargs;
17048       tree p = parms;
17049       bool type_pack_p;
17050       do
17051         {
17052           type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
17053           if (!type_pack_p)
17054             count++;
17055           p = TREE_CHAIN (p);
17056         }
17057       while (p && p != void_list_node);
17058       if (count != nargs)
17059         return unify_too_few_arguments (explain_p, ia, count,
17060                                         type_pack_p);
17061     }
17062
17063   if (!subr)
17064     {
17065       tsubst_flags_t complain = (explain_p
17066                                  ? tf_warning_or_error
17067                                  : tf_none);
17068
17069       for (i = 0; i < ntparms; i++)
17070         {
17071           tree targ = TREE_VEC_ELT (targs, i);
17072           tree tparm = TREE_VEC_ELT (tparms, i);
17073
17074           /* Clear the "incomplete" flags on all argument packs now so that
17075              substituting them into later default arguments works.  */
17076           if (targ && ARGUMENT_PACK_P (targ))
17077             {
17078               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
17079               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
17080             }
17081
17082           if (targ || tparm == error_mark_node)
17083             continue;
17084           tparm = TREE_VALUE (tparm);
17085
17086           /* If this is an undeduced nontype parameter that depends on
17087              a type parameter, try another pass; its type may have been
17088              deduced from a later argument than the one from which
17089              this parameter can be deduced.  */
17090           if (TREE_CODE (tparm) == PARM_DECL
17091               && uses_template_parms (TREE_TYPE (tparm))
17092               && !saw_undeduced++)
17093             goto again;
17094
17095           /* Core issue #226 (C++0x) [temp.deduct]:
17096
17097              If a template argument has not been deduced, its
17098              default template argument, if any, is used. 
17099
17100              When we are in C++98 mode, TREE_PURPOSE will either
17101              be NULL_TREE or ERROR_MARK_NODE, so we do not need
17102              to explicitly check cxx_dialect here.  */
17103           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
17104             {
17105               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
17106               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
17107               reopen_deferring_access_checks (*checks);
17108               location_t save_loc = input_location;
17109               if (DECL_P (parm))
17110                 input_location = DECL_SOURCE_LOCATION (parm);
17111               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
17112               arg = convert_template_argument (parm, arg, targs, complain,
17113                                                i, NULL_TREE);
17114               input_location = save_loc;
17115               *checks = get_deferred_access_checks ();
17116               pop_deferring_access_checks ();
17117               if (arg == error_mark_node)
17118                 return 1;
17119               else
17120                 {
17121                   TREE_VEC_ELT (targs, i) = arg;
17122                   /* The position of the first default template argument,
17123                      is also the number of non-defaulted arguments in TARGS.
17124                      Record that.  */
17125                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
17126                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
17127                   continue;
17128                 }
17129             }
17130
17131           /* If the type parameter is a parameter pack, then it will
17132              be deduced to an empty parameter pack.  */
17133           if (template_parameter_pack_p (tparm))
17134             {
17135               tree arg;
17136
17137               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
17138                 {
17139                   arg = make_node (NONTYPE_ARGUMENT_PACK);
17140                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
17141                   TREE_CONSTANT (arg) = 1;
17142                 }
17143               else
17144                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
17145
17146               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
17147
17148               TREE_VEC_ELT (targs, i) = arg;
17149               continue;
17150             }
17151
17152           return unify_parameter_deduction_failure (explain_p, tparm);
17153         }
17154     }
17155 #ifdef ENABLE_CHECKING
17156   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
17157     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
17158 #endif
17159
17160   return unify_success (explain_p);
17161 }
17162
17163 /* Subroutine of type_unification_real.  Args are like the variables
17164    at the call site.  ARG is an overloaded function (or template-id);
17165    we try deducing template args from each of the overloads, and if
17166    only one succeeds, we go with that.  Modifies TARGS and returns
17167    true on success.  */
17168
17169 static bool
17170 resolve_overloaded_unification (tree tparms,
17171                                 tree targs,
17172                                 tree parm,
17173                                 tree arg,
17174                                 unification_kind_t strict,
17175                                 int sub_strict,
17176                                 bool explain_p)
17177 {
17178   tree tempargs = copy_node (targs);
17179   int good = 0;
17180   tree goodfn = NULL_TREE;
17181   bool addr_p;
17182
17183   if (TREE_CODE (arg) == ADDR_EXPR)
17184     {
17185       arg = TREE_OPERAND (arg, 0);
17186       addr_p = true;
17187     }
17188   else
17189     addr_p = false;
17190
17191   if (TREE_CODE (arg) == COMPONENT_REF)
17192     /* Handle `&x' where `x' is some static or non-static member
17193        function name.  */
17194     arg = TREE_OPERAND (arg, 1);
17195
17196   if (TREE_CODE (arg) == OFFSET_REF)
17197     arg = TREE_OPERAND (arg, 1);
17198
17199   /* Strip baselink information.  */
17200   if (BASELINK_P (arg))
17201     arg = BASELINK_FUNCTIONS (arg);
17202
17203   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
17204     {
17205       /* If we got some explicit template args, we need to plug them into
17206          the affected templates before we try to unify, in case the
17207          explicit args will completely resolve the templates in question.  */
17208
17209       int ok = 0;
17210       tree expl_subargs = TREE_OPERAND (arg, 1);
17211       arg = TREE_OPERAND (arg, 0);
17212
17213       for (; arg; arg = OVL_NEXT (arg))
17214         {
17215           tree fn = OVL_CURRENT (arg);
17216           tree subargs, elem;
17217
17218           if (TREE_CODE (fn) != TEMPLATE_DECL)
17219             continue;
17220
17221           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
17222                                            expl_subargs, NULL_TREE, tf_none,
17223                                            /*require_all_args=*/true,
17224                                            /*use_default_args=*/true);
17225           if (subargs != error_mark_node
17226               && !any_dependent_template_arguments_p (subargs))
17227             {
17228               elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
17229               if (try_one_overload (tparms, targs, tempargs, parm,
17230                                     elem, strict, sub_strict, addr_p, explain_p)
17231                   && (!goodfn || !same_type_p (goodfn, elem)))
17232                 {
17233                   goodfn = elem;
17234                   ++good;
17235                 }
17236             }
17237           else if (subargs)
17238             ++ok;
17239         }
17240       /* If no templates (or more than one) are fully resolved by the
17241          explicit arguments, this template-id is a non-deduced context; it
17242          could still be OK if we deduce all template arguments for the
17243          enclosing call through other arguments.  */
17244       if (good != 1)
17245         good = ok;
17246     }
17247   else if (TREE_CODE (arg) != OVERLOAD
17248            && TREE_CODE (arg) != FUNCTION_DECL)
17249     /* If ARG is, for example, "(0, &f)" then its type will be unknown
17250        -- but the deduction does not succeed because the expression is
17251        not just the function on its own.  */
17252     return false;
17253   else
17254     for (; arg; arg = OVL_NEXT (arg))
17255       if (try_one_overload (tparms, targs, tempargs, parm,
17256                             TREE_TYPE (OVL_CURRENT (arg)),
17257                             strict, sub_strict, addr_p, explain_p)
17258           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
17259         {
17260           goodfn = OVL_CURRENT (arg);
17261           ++good;
17262         }
17263
17264   /* [temp.deduct.type] A template-argument can be deduced from a pointer
17265      to function or pointer to member function argument if the set of
17266      overloaded functions does not contain function templates and at most
17267      one of a set of overloaded functions provides a unique match.
17268
17269      So if we found multiple possibilities, we return success but don't
17270      deduce anything.  */
17271
17272   if (good == 1)
17273     {
17274       int i = TREE_VEC_LENGTH (targs);
17275       for (; i--; )
17276         if (TREE_VEC_ELT (tempargs, i))
17277           {
17278             tree old = TREE_VEC_ELT (targs, i);
17279             tree new_ = TREE_VEC_ELT (tempargs, i);
17280             if (new_ && old && ARGUMENT_PACK_P (old)
17281                 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
17282               /* Don't forget explicit template arguments in a pack.  */
17283               ARGUMENT_PACK_EXPLICIT_ARGS (new_)
17284                 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
17285             TREE_VEC_ELT (targs, i) = new_;
17286           }
17287     }
17288   if (good)
17289     return true;
17290
17291   return false;
17292 }
17293
17294 /* Core DR 115: In contexts where deduction is done and fails, or in
17295    contexts where deduction is not done, if a template argument list is
17296    specified and it, along with any default template arguments, identifies
17297    a single function template specialization, then the template-id is an
17298    lvalue for the function template specialization.  */
17299
17300 tree
17301 resolve_nondeduced_context (tree orig_expr)
17302 {
17303   tree expr, offset, baselink;
17304   bool addr;
17305
17306   if (!type_unknown_p (orig_expr))
17307     return orig_expr;
17308
17309   expr = orig_expr;
17310   addr = false;
17311   offset = NULL_TREE;
17312   baselink = NULL_TREE;
17313
17314   if (TREE_CODE (expr) == ADDR_EXPR)
17315     {
17316       expr = TREE_OPERAND (expr, 0);
17317       addr = true;
17318     }
17319   if (TREE_CODE (expr) == OFFSET_REF)
17320     {
17321       offset = expr;
17322       expr = TREE_OPERAND (expr, 1);
17323     }
17324   if (BASELINK_P (expr))
17325     {
17326       baselink = expr;
17327       expr = BASELINK_FUNCTIONS (expr);
17328     }
17329
17330   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
17331     {
17332       int good = 0;
17333       tree goodfn = NULL_TREE;
17334
17335       /* If we got some explicit template args, we need to plug them into
17336          the affected templates before we try to unify, in case the
17337          explicit args will completely resolve the templates in question.  */
17338
17339       tree expl_subargs = TREE_OPERAND (expr, 1);
17340       tree arg = TREE_OPERAND (expr, 0);
17341       tree badfn = NULL_TREE;
17342       tree badargs = NULL_TREE;
17343
17344       for (; arg; arg = OVL_NEXT (arg))
17345         {
17346           tree fn = OVL_CURRENT (arg);
17347           tree subargs, elem;
17348
17349           if (TREE_CODE (fn) != TEMPLATE_DECL)
17350             continue;
17351
17352           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
17353                                            expl_subargs, NULL_TREE, tf_none,
17354                                            /*require_all_args=*/true,
17355                                            /*use_default_args=*/true);
17356           if (subargs != error_mark_node
17357               && !any_dependent_template_arguments_p (subargs))
17358             {
17359               elem = instantiate_template (fn, subargs, tf_none);
17360               if (elem == error_mark_node)
17361                 {
17362                   badfn = fn;
17363                   badargs = subargs;
17364                 }
17365               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
17366                 {
17367                   goodfn = elem;
17368                   ++good;
17369                 }
17370             }
17371         }
17372       if (good == 1)
17373         {
17374           mark_used (goodfn);
17375           expr = goodfn;
17376           if (baselink)
17377             expr = build_baselink (BASELINK_BINFO (baselink),
17378                                    BASELINK_ACCESS_BINFO (baselink),
17379                                    expr, BASELINK_OPTYPE (baselink));
17380           if (offset)
17381             {
17382               tree base
17383                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
17384               expr = build_offset_ref (base, expr, addr, tf_warning_or_error);
17385             }
17386           if (addr)
17387             expr = cp_build_addr_expr (expr, tf_warning_or_error);
17388           return expr;
17389         }
17390       else if (good == 0 && badargs)
17391         /* There were no good options and at least one bad one, so let the
17392            user know what the problem is.  */
17393         instantiate_template (badfn, badargs, tf_warning_or_error);
17394     }
17395   return orig_expr;
17396 }
17397
17398 /* Subroutine of resolve_overloaded_unification; does deduction for a single
17399    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
17400    different overloads deduce different arguments for a given parm.
17401    ADDR_P is true if the expression for which deduction is being
17402    performed was of the form "& fn" rather than simply "fn".
17403
17404    Returns 1 on success.  */
17405
17406 static int
17407 try_one_overload (tree tparms,
17408                   tree orig_targs,
17409                   tree targs,
17410                   tree parm,
17411                   tree arg,
17412                   unification_kind_t strict,
17413                   int sub_strict,
17414                   bool addr_p,
17415                   bool explain_p)
17416 {
17417   int nargs;
17418   tree tempargs;
17419   int i;
17420
17421   if (arg == error_mark_node)
17422     return 0;
17423
17424   /* [temp.deduct.type] A template-argument can be deduced from a pointer
17425      to function or pointer to member function argument if the set of
17426      overloaded functions does not contain function templates and at most
17427      one of a set of overloaded functions provides a unique match.
17428
17429      So if this is a template, just return success.  */
17430
17431   if (uses_template_parms (arg))
17432     return 1;
17433
17434   if (TREE_CODE (arg) == METHOD_TYPE)
17435     arg = build_ptrmemfunc_type (build_pointer_type (arg));
17436   else if (addr_p)
17437     arg = build_pointer_type (arg);
17438
17439   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
17440
17441   /* We don't copy orig_targs for this because if we have already deduced
17442      some template args from previous args, unify would complain when we
17443      try to deduce a template parameter for the same argument, even though
17444      there isn't really a conflict.  */
17445   nargs = TREE_VEC_LENGTH (targs);
17446   tempargs = make_tree_vec (nargs);
17447
17448   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
17449     return 0;
17450
17451   /* First make sure we didn't deduce anything that conflicts with
17452      explicitly specified args.  */
17453   for (i = nargs; i--; )
17454     {
17455       tree elt = TREE_VEC_ELT (tempargs, i);
17456       tree oldelt = TREE_VEC_ELT (orig_targs, i);
17457
17458       if (!elt)
17459         /*NOP*/;
17460       else if (uses_template_parms (elt))
17461         /* Since we're unifying against ourselves, we will fill in
17462            template args used in the function parm list with our own
17463            template parms.  Discard them.  */
17464         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
17465       else if (oldelt && !template_args_equal (oldelt, elt))
17466         return 0;
17467     }
17468
17469   for (i = nargs; i--; )
17470     {
17471       tree elt = TREE_VEC_ELT (tempargs, i);
17472
17473       if (elt)
17474         TREE_VEC_ELT (targs, i) = elt;
17475     }
17476
17477   return 1;
17478 }
17479
17480 /* PARM is a template class (perhaps with unbound template
17481    parameters).  ARG is a fully instantiated type.  If ARG can be
17482    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
17483    TARGS are as for unify.  */
17484
17485 static tree
17486 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
17487                        bool explain_p)
17488 {
17489   tree copy_of_targs;
17490
17491   if (!CLASSTYPE_TEMPLATE_INFO (arg)
17492       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
17493           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
17494     return NULL_TREE;
17495
17496   /* We need to make a new template argument vector for the call to
17497      unify.  If we used TARGS, we'd clutter it up with the result of
17498      the attempted unification, even if this class didn't work out.
17499      We also don't want to commit ourselves to all the unifications
17500      we've already done, since unification is supposed to be done on
17501      an argument-by-argument basis.  In other words, consider the
17502      following pathological case:
17503
17504        template <int I, int J, int K>
17505        struct S {};
17506
17507        template <int I, int J>
17508        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
17509
17510        template <int I, int J, int K>
17511        void f(S<I, J, K>, S<I, I, I>);
17512
17513        void g() {
17514          S<0, 0, 0> s0;
17515          S<0, 1, 2> s2;
17516
17517          f(s0, s2);
17518        }
17519
17520      Now, by the time we consider the unification involving `s2', we
17521      already know that we must have `f<0, 0, 0>'.  But, even though
17522      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
17523      because there are two ways to unify base classes of S<0, 1, 2>
17524      with S<I, I, I>.  If we kept the already deduced knowledge, we
17525      would reject the possibility I=1.  */
17526   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
17527
17528   /* If unification failed, we're done.  */
17529   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
17530              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
17531     return NULL_TREE;
17532
17533   return arg;
17534 }
17535
17536 /* Given a template type PARM and a class type ARG, find the unique
17537    base type in ARG that is an instance of PARM.  We do not examine
17538    ARG itself; only its base-classes.  If there is not exactly one
17539    appropriate base class, return NULL_TREE.  PARM may be the type of
17540    a partial specialization, as well as a plain template type.  Used
17541    by unify.  */
17542
17543 static enum template_base_result
17544 get_template_base (tree tparms, tree targs, tree parm, tree arg,
17545                    bool explain_p, tree *result)
17546 {
17547   tree rval = NULL_TREE;
17548   tree binfo;
17549
17550   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
17551
17552   binfo = TYPE_BINFO (complete_type (arg));
17553   if (!binfo)
17554     {
17555       /* The type could not be completed.  */
17556       *result = NULL_TREE;
17557       return tbr_incomplete_type;
17558     }
17559
17560   /* Walk in inheritance graph order.  The search order is not
17561      important, and this avoids multiple walks of virtual bases.  */
17562   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
17563     {
17564       tree r = try_class_unification (tparms, targs, parm,
17565                                       BINFO_TYPE (binfo), explain_p);
17566
17567       if (r)
17568         {
17569           /* If there is more than one satisfactory baseclass, then:
17570
17571                [temp.deduct.call]
17572
17573               If they yield more than one possible deduced A, the type
17574               deduction fails.
17575
17576              applies.  */
17577           if (rval && !same_type_p (r, rval))
17578             {
17579               *result = NULL_TREE;
17580               return tbr_ambiguous_baseclass;
17581             }
17582
17583           rval = r;
17584         }
17585     }
17586
17587   *result = rval;
17588   return tbr_success;
17589 }
17590
17591 /* Returns the level of DECL, which declares a template parameter.  */
17592
17593 static int
17594 template_decl_level (tree decl)
17595 {
17596   switch (TREE_CODE (decl))
17597     {
17598     case TYPE_DECL:
17599     case TEMPLATE_DECL:
17600       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
17601
17602     case PARM_DECL:
17603       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
17604
17605     default:
17606       gcc_unreachable ();
17607     }
17608   return 0;
17609 }
17610
17611 /* Decide whether ARG can be unified with PARM, considering only the
17612    cv-qualifiers of each type, given STRICT as documented for unify.
17613    Returns nonzero iff the unification is OK on that basis.  */
17614
17615 static int
17616 check_cv_quals_for_unify (int strict, tree arg, tree parm)
17617 {
17618   int arg_quals = cp_type_quals (arg);
17619   int parm_quals = cp_type_quals (parm);
17620
17621   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
17622       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
17623     {
17624       /*  Although a CVR qualifier is ignored when being applied to a
17625           substituted template parameter ([8.3.2]/1 for example), that
17626           does not allow us to unify "const T" with "int&" because both
17627           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
17628           It is ok when we're allowing additional CV qualifiers
17629           at the outer level [14.8.2.1]/3,1st bullet.  */
17630       if ((TREE_CODE (arg) == REFERENCE_TYPE
17631            || TREE_CODE (arg) == FUNCTION_TYPE
17632            || TREE_CODE (arg) == METHOD_TYPE)
17633           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
17634         return 0;
17635
17636       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
17637           && (parm_quals & TYPE_QUAL_RESTRICT))
17638         return 0;
17639     }
17640
17641   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
17642       && (arg_quals & parm_quals) != parm_quals)
17643     return 0;
17644
17645   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
17646       && (parm_quals & arg_quals) != arg_quals)
17647     return 0;
17648
17649   return 1;
17650 }
17651
17652 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
17653 void 
17654 template_parm_level_and_index (tree parm, int* level, int* index)
17655 {
17656   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
17657       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
17658       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
17659     {
17660       *index = TEMPLATE_TYPE_IDX (parm);
17661       *level = TEMPLATE_TYPE_LEVEL (parm);
17662     }
17663   else
17664     {
17665       *index = TEMPLATE_PARM_IDX (parm);
17666       *level = TEMPLATE_PARM_LEVEL (parm);
17667     }
17668 }
17669
17670 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
17671   do {                                                                  \
17672     if (unify (TP, TA, P, A, S, EP))                                    \
17673       return 1;                                                         \
17674   } while (0);
17675
17676 /* Unifies the remaining arguments in PACKED_ARGS with the pack
17677    expansion at the end of PACKED_PARMS. Returns 0 if the type
17678    deduction succeeds, 1 otherwise. STRICT is the same as in
17679    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
17680    call argument list. We'll need to adjust the arguments to make them
17681    types. SUBR tells us if this is from a recursive call to
17682    type_unification_real, or for comparing two template argument
17683    lists. */
17684
17685 static int
17686 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
17687                       tree packed_args, unification_kind_t strict,
17688                       bool subr, bool explain_p)
17689 {
17690   tree parm 
17691     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
17692   tree pattern = PACK_EXPANSION_PATTERN (parm);
17693   tree pack, packs = NULL_TREE;
17694   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
17695
17696   packed_args = expand_template_argument_pack (packed_args);
17697
17698   int len = TREE_VEC_LENGTH (packed_args);
17699
17700   /* Determine the parameter packs we will be deducing from the
17701      pattern, and record their current deductions.  */
17702   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
17703        pack; pack = TREE_CHAIN (pack))
17704     {
17705       tree parm_pack = TREE_VALUE (pack);
17706       int idx, level;
17707
17708       /* Determine the index and level of this parameter pack.  */
17709       template_parm_level_and_index (parm_pack, &level, &idx);
17710
17711       /* Keep track of the parameter packs and their corresponding
17712          argument packs.  */
17713       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
17714       TREE_TYPE (packs) = make_tree_vec (len - start);
17715     }
17716   
17717   /* Loop through all of the arguments that have not yet been
17718      unified and unify each with the pattern.  */
17719   for (i = start; i < len; i++)
17720     {
17721       tree parm;
17722       bool any_explicit = false;
17723       tree arg = TREE_VEC_ELT (packed_args, i);
17724
17725       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
17726          or the element of its argument pack at the current index if
17727          this argument was explicitly specified.  */
17728       for (pack = packs; pack; pack = TREE_CHAIN (pack))
17729         {
17730           int idx, level;
17731           tree arg, pargs;
17732           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
17733
17734           arg = NULL_TREE;
17735           if (TREE_VALUE (pack)
17736               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
17737               && (i - start < TREE_VEC_LENGTH (pargs)))
17738             {
17739               any_explicit = true;
17740               arg = TREE_VEC_ELT (pargs, i - start);
17741             }
17742           TMPL_ARG (targs, level, idx) = arg;
17743         }
17744
17745       /* If we had explicit template arguments, substitute them into the
17746          pattern before deduction.  */
17747       if (any_explicit)
17748         {
17749           /* Some arguments might still be unspecified or dependent.  */
17750           bool dependent;
17751           ++processing_template_decl;
17752           dependent = any_dependent_template_arguments_p (targs);
17753           if (!dependent)
17754             --processing_template_decl;
17755           parm = tsubst (pattern, targs,
17756                          explain_p ? tf_warning_or_error : tf_none,
17757                          NULL_TREE);
17758           if (dependent)
17759             --processing_template_decl;
17760           if (parm == error_mark_node)
17761             return 1;
17762         }
17763       else
17764         parm = pattern;
17765
17766       /* Unify the pattern with the current argument.  */
17767       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
17768                               LOOKUP_IMPLICIT, explain_p))
17769         return 1;
17770
17771       /* For each parameter pack, collect the deduced value.  */
17772       for (pack = packs; pack; pack = TREE_CHAIN (pack))
17773         {
17774           int idx, level;
17775           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
17776
17777           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
17778             TMPL_ARG (targs, level, idx);
17779         }
17780     }
17781
17782   /* Verify that the results of unification with the parameter packs
17783      produce results consistent with what we've seen before, and make
17784      the deduced argument packs available.  */
17785   for (pack = packs; pack; pack = TREE_CHAIN (pack))
17786     {
17787       tree old_pack = TREE_VALUE (pack);
17788       tree new_args = TREE_TYPE (pack);
17789       int i, len = TREE_VEC_LENGTH (new_args);
17790       int idx, level;
17791       bool nondeduced_p = false;
17792
17793       /* By default keep the original deduced argument pack.
17794          If necessary, more specific code is going to update the
17795          resulting deduced argument later down in this function.  */
17796       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
17797       TMPL_ARG (targs, level, idx) = old_pack;
17798
17799       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
17800          actually deduce anything.  */
17801       for (i = 0; i < len && !nondeduced_p; ++i)
17802         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
17803           nondeduced_p = true;
17804       if (nondeduced_p)
17805         continue;
17806
17807       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
17808         {
17809           /* If we had fewer function args than explicit template args,
17810              just use the explicits.  */
17811           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
17812           int explicit_len = TREE_VEC_LENGTH (explicit_args);
17813           if (len < explicit_len)
17814             new_args = explicit_args;
17815         }
17816
17817       if (!old_pack)
17818         {
17819           tree result;
17820           /* Build the deduced *_ARGUMENT_PACK.  */
17821           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
17822             {
17823               result = make_node (NONTYPE_ARGUMENT_PACK);
17824               TREE_TYPE (result) = 
17825                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
17826               TREE_CONSTANT (result) = 1;
17827             }
17828           else
17829             result = cxx_make_type (TYPE_ARGUMENT_PACK);
17830
17831           SET_ARGUMENT_PACK_ARGS (result, new_args);
17832
17833           /* Note the deduced argument packs for this parameter
17834              pack.  */
17835           TMPL_ARG (targs, level, idx) = result;
17836         }
17837       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
17838                && (ARGUMENT_PACK_ARGS (old_pack) 
17839                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
17840         {
17841           /* We only had the explicitly-provided arguments before, but
17842              now we have a complete set of arguments.  */
17843           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
17844
17845           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
17846           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
17847           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
17848         }
17849       else
17850         {
17851           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
17852           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
17853
17854           if (!comp_template_args_with_info (old_args, new_args,
17855                                              &bad_old_arg, &bad_new_arg))
17856             /* Inconsistent unification of this parameter pack.  */
17857             return unify_parameter_pack_inconsistent (explain_p,
17858                                                       bad_old_arg,
17859                                                       bad_new_arg);
17860         }
17861     }
17862
17863   return unify_success (explain_p);
17864 }
17865
17866 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
17867    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
17868    parameters and return value are as for unify.  */
17869
17870 static int
17871 unify_array_domain (tree tparms, tree targs,
17872                     tree parm_dom, tree arg_dom,
17873                     bool explain_p)
17874 {
17875   tree parm_max;
17876   tree arg_max;
17877   bool parm_cst;
17878   bool arg_cst;
17879
17880   /* Our representation of array types uses "N - 1" as the
17881      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
17882      not an integer constant.  We cannot unify arbitrarily
17883      complex expressions, so we eliminate the MINUS_EXPRs
17884      here.  */
17885   parm_max = TYPE_MAX_VALUE (parm_dom);
17886   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
17887   if (!parm_cst)
17888     {
17889       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
17890       parm_max = TREE_OPERAND (parm_max, 0);
17891     }
17892   arg_max = TYPE_MAX_VALUE (arg_dom);
17893   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
17894   if (!arg_cst)
17895     {
17896       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
17897          trying to unify the type of a variable with the type
17898          of a template parameter.  For example:
17899
17900            template <unsigned int N>
17901            void f (char (&) [N]);
17902            int g();
17903            void h(int i) {
17904              char a[g(i)];
17905              f(a);
17906            }
17907
17908          Here, the type of the ARG will be "int [g(i)]", and
17909          may be a SAVE_EXPR, etc.  */
17910       if (TREE_CODE (arg_max) != MINUS_EXPR)
17911         return unify_vla_arg (explain_p, arg_dom);
17912       arg_max = TREE_OPERAND (arg_max, 0);
17913     }
17914
17915   /* If only one of the bounds used a MINUS_EXPR, compensate
17916      by adding one to the other bound.  */
17917   if (parm_cst && !arg_cst)
17918     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
17919                                 integer_type_node,
17920                                 parm_max,
17921                                 integer_one_node);
17922   else if (arg_cst && !parm_cst)
17923     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
17924                                integer_type_node,
17925                                arg_max,
17926                                integer_one_node);
17927
17928   return unify (tparms, targs, parm_max, arg_max,
17929                 UNIFY_ALLOW_INTEGER, explain_p);
17930 }
17931
17932 /* Deduce the value of template parameters.  TPARMS is the (innermost)
17933    set of template parameters to a template.  TARGS is the bindings
17934    for those template parameters, as determined thus far; TARGS may
17935    include template arguments for outer levels of template parameters
17936    as well.  PARM is a parameter to a template function, or a
17937    subcomponent of that parameter; ARG is the corresponding argument.
17938    This function attempts to match PARM with ARG in a manner
17939    consistent with the existing assignments in TARGS.  If more values
17940    are deduced, then TARGS is updated.
17941
17942    Returns 0 if the type deduction succeeds, 1 otherwise.  The
17943    parameter STRICT is a bitwise or of the following flags:
17944
17945      UNIFY_ALLOW_NONE:
17946        Require an exact match between PARM and ARG.
17947      UNIFY_ALLOW_MORE_CV_QUAL:
17948        Allow the deduced ARG to be more cv-qualified (by qualification
17949        conversion) than ARG.
17950      UNIFY_ALLOW_LESS_CV_QUAL:
17951        Allow the deduced ARG to be less cv-qualified than ARG.
17952      UNIFY_ALLOW_DERIVED:
17953        Allow the deduced ARG to be a template base class of ARG,
17954        or a pointer to a template base class of the type pointed to by
17955        ARG.
17956      UNIFY_ALLOW_INTEGER:
17957        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
17958        case for more information.
17959      UNIFY_ALLOW_OUTER_LEVEL:
17960        This is the outermost level of a deduction. Used to determine validity
17961        of qualification conversions. A valid qualification conversion must
17962        have const qualified pointers leading up to the inner type which
17963        requires additional CV quals, except at the outer level, where const
17964        is not required [conv.qual]. It would be normal to set this flag in
17965        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
17966      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
17967        This is the outermost level of a deduction, and PARM can be more CV
17968        qualified at this point.
17969      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
17970        This is the outermost level of a deduction, and PARM can be less CV
17971        qualified at this point.  */
17972
17973 static int
17974 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
17975        bool explain_p)
17976 {
17977   int idx;
17978   tree targ;
17979   tree tparm;
17980   int strict_in = strict;
17981
17982   /* I don't think this will do the right thing with respect to types.
17983      But the only case I've seen it in so far has been array bounds, where
17984      signedness is the only information lost, and I think that will be
17985      okay.  */
17986   while (TREE_CODE (parm) == NOP_EXPR)
17987     parm = TREE_OPERAND (parm, 0);
17988
17989   if (arg == error_mark_node)
17990     return unify_invalid (explain_p);
17991   if (arg == unknown_type_node
17992       || arg == init_list_type_node)
17993     /* We can't deduce anything from this, but we might get all the
17994        template args from other function args.  */
17995     return unify_success (explain_p);
17996
17997   /* If PARM uses template parameters, then we can't bail out here,
17998      even if ARG == PARM, since we won't record unifications for the
17999      template parameters.  We might need them if we're trying to
18000      figure out which of two things is more specialized.  */
18001   if (arg == parm && !uses_template_parms (parm))
18002     return unify_success (explain_p);
18003
18004   /* Handle init lists early, so the rest of the function can assume
18005      we're dealing with a type. */
18006   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
18007     {
18008       tree elt, elttype;
18009       unsigned i;
18010       tree orig_parm = parm;
18011
18012       /* Replace T with std::initializer_list<T> for deduction.  */
18013       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
18014           && flag_deduce_init_list)
18015         parm = listify (parm);
18016
18017       if (!is_std_init_list (parm)
18018           && TREE_CODE (parm) != ARRAY_TYPE)
18019         /* We can only deduce from an initializer list argument if the
18020            parameter is std::initializer_list or an array; otherwise this
18021            is a non-deduced context. */
18022         return unify_success (explain_p);
18023
18024       if (TREE_CODE (parm) == ARRAY_TYPE)
18025         elttype = TREE_TYPE (parm);
18026       else
18027         {
18028           elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
18029           /* Deduction is defined in terms of a single type, so just punt
18030              on the (bizarre) std::initializer_list<T...>.  */
18031           if (PACK_EXPANSION_P (elttype))
18032             return unify_success (explain_p);
18033         }
18034
18035       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
18036         {
18037           int elt_strict = strict;
18038
18039           if (elt == error_mark_node)
18040             return unify_invalid (explain_p);
18041
18042           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
18043             {
18044               tree type = TREE_TYPE (elt);
18045               if (type == error_mark_node)
18046                 return unify_invalid (explain_p);
18047               /* It should only be possible to get here for a call.  */
18048               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
18049               elt_strict |= maybe_adjust_types_for_deduction
18050                 (DEDUCE_CALL, &elttype, &type, elt);
18051               elt = type;
18052             }
18053
18054           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
18055                                    explain_p);
18056         }
18057
18058       if (TREE_CODE (parm) == ARRAY_TYPE
18059           && deducible_array_bound (TYPE_DOMAIN (parm)))
18060         {
18061           /* Also deduce from the length of the initializer list.  */
18062           tree max = size_int (CONSTRUCTOR_NELTS (arg));
18063           tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
18064           if (idx == error_mark_node)
18065             return unify_invalid (explain_p);
18066           return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
18067                                      idx, explain_p);
18068         }
18069
18070       /* If the std::initializer_list<T> deduction worked, replace the
18071          deduced A with std::initializer_list<A>.  */
18072       if (orig_parm != parm)
18073         {
18074           idx = TEMPLATE_TYPE_IDX (orig_parm);
18075           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
18076           targ = listify (targ);
18077           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
18078         }
18079       return unify_success (explain_p);
18080     }
18081
18082   /* Immediately reject some pairs that won't unify because of
18083      cv-qualification mismatches.  */
18084   if (TREE_CODE (arg) == TREE_CODE (parm)
18085       && TYPE_P (arg)
18086       /* It is the elements of the array which hold the cv quals of an array
18087          type, and the elements might be template type parms. We'll check
18088          when we recurse.  */
18089       && TREE_CODE (arg) != ARRAY_TYPE
18090       /* We check the cv-qualifiers when unifying with template type
18091          parameters below.  We want to allow ARG `const T' to unify with
18092          PARM `T' for example, when computing which of two templates
18093          is more specialized, for example.  */
18094       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
18095       && !check_cv_quals_for_unify (strict_in, arg, parm))
18096     return unify_cv_qual_mismatch (explain_p, parm, arg);
18097
18098   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
18099       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
18100     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
18101   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
18102   strict &= ~UNIFY_ALLOW_DERIVED;
18103   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
18104   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
18105
18106   switch (TREE_CODE (parm))
18107     {
18108     case TYPENAME_TYPE:
18109     case SCOPE_REF:
18110     case UNBOUND_CLASS_TEMPLATE:
18111       /* In a type which contains a nested-name-specifier, template
18112          argument values cannot be deduced for template parameters used
18113          within the nested-name-specifier.  */
18114       return unify_success (explain_p);
18115
18116     case TEMPLATE_TYPE_PARM:
18117     case TEMPLATE_TEMPLATE_PARM:
18118     case BOUND_TEMPLATE_TEMPLATE_PARM:
18119       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
18120       if (error_operand_p (tparm))
18121         return unify_invalid (explain_p);
18122
18123       if (TEMPLATE_TYPE_LEVEL (parm)
18124           != template_decl_level (tparm))
18125         /* The PARM is not one we're trying to unify.  Just check
18126            to see if it matches ARG.  */
18127         {
18128           if (TREE_CODE (arg) == TREE_CODE (parm)
18129               && (is_auto (parm) ? is_auto (arg)
18130                   : same_type_p (parm, arg)))
18131             return unify_success (explain_p);
18132           else
18133             return unify_type_mismatch (explain_p, parm, arg);
18134         }
18135       idx = TEMPLATE_TYPE_IDX (parm);
18136       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
18137       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
18138       if (error_operand_p (tparm))
18139         return unify_invalid (explain_p);
18140
18141       /* Check for mixed types and values.  */
18142       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
18143            && TREE_CODE (tparm) != TYPE_DECL)
18144           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
18145               && TREE_CODE (tparm) != TEMPLATE_DECL))
18146         gcc_unreachable ();
18147
18148       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
18149         {
18150           /* ARG must be constructed from a template class or a template
18151              template parameter.  */
18152           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
18153               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
18154             return unify_template_deduction_failure (explain_p, parm, arg);
18155           {
18156             tree parmvec = TYPE_TI_ARGS (parm);
18157             /* An alias template name is never deduced.  */
18158             if (TYPE_ALIAS_P (arg))
18159               arg = strip_typedefs (arg);
18160             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
18161             tree full_argvec = add_to_template_args (targs, argvec);
18162             tree parm_parms 
18163               = DECL_INNERMOST_TEMPLATE_PARMS
18164                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
18165             int i, len;
18166             int parm_variadic_p = 0;
18167
18168             /* The resolution to DR150 makes clear that default
18169                arguments for an N-argument may not be used to bind T
18170                to a template template parameter with fewer than N
18171                parameters.  It is not safe to permit the binding of
18172                default arguments as an extension, as that may change
18173                the meaning of a conforming program.  Consider:
18174
18175                   struct Dense { static const unsigned int dim = 1; };
18176
18177                   template <template <typename> class View,
18178                             typename Block>
18179                   void operator+(float, View<Block> const&);
18180
18181                   template <typename Block,
18182                             unsigned int Dim = Block::dim>
18183                   struct Lvalue_proxy { operator float() const; };
18184
18185                   void
18186                   test_1d (void) {
18187                     Lvalue_proxy<Dense> p;
18188                     float b;
18189                     b + p;
18190                   }
18191
18192               Here, if Lvalue_proxy is permitted to bind to View, then
18193               the global operator+ will be used; if they are not, the
18194               Lvalue_proxy will be converted to float.  */
18195             if (coerce_template_parms (parm_parms,
18196                                        full_argvec,
18197                                        TYPE_TI_TEMPLATE (parm),
18198                                        (explain_p
18199                                         ? tf_warning_or_error
18200                                         : tf_none),
18201                                        /*require_all_args=*/true,
18202                                        /*use_default_args=*/false)
18203                 == error_mark_node)
18204               return 1;
18205
18206             /* Deduce arguments T, i from TT<T> or TT<i>.
18207                We check each element of PARMVEC and ARGVEC individually
18208                rather than the whole TREE_VEC since they can have
18209                different number of elements.  */
18210
18211             parmvec = expand_template_argument_pack (parmvec);
18212             argvec = expand_template_argument_pack (argvec);
18213
18214             len = TREE_VEC_LENGTH (parmvec);
18215
18216             /* Check if the parameters end in a pack, making them
18217                variadic.  */
18218             if (len > 0
18219                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
18220               parm_variadic_p = 1;
18221             
18222              for (i = 0; i < len - parm_variadic_p; ++i)
18223                /* If the template argument list of P contains a pack
18224                   expansion that is not the last template argument, the
18225                   entire template argument list is a non-deduced
18226                   context.  */
18227                if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
18228                  return unify_success (explain_p);
18229
18230             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
18231               return unify_too_few_arguments (explain_p,
18232                                               TREE_VEC_LENGTH (argvec), len);
18233
18234              for (i = 0; i < len - parm_variadic_p; ++i)
18235               {
18236                 RECUR_AND_CHECK_FAILURE (tparms, targs,
18237                                          TREE_VEC_ELT (parmvec, i),
18238                                          TREE_VEC_ELT (argvec, i),
18239                                          UNIFY_ALLOW_NONE, explain_p);
18240               }
18241
18242             if (parm_variadic_p
18243                 && unify_pack_expansion (tparms, targs,
18244                                          parmvec, argvec,
18245                                          DEDUCE_EXACT,
18246                                          /*subr=*/true, explain_p))
18247               return 1;
18248           }
18249           arg = TYPE_TI_TEMPLATE (arg);
18250
18251           /* Fall through to deduce template name.  */
18252         }
18253
18254       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
18255           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
18256         {
18257           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
18258
18259           /* Simple cases: Value already set, does match or doesn't.  */
18260           if (targ != NULL_TREE && template_args_equal (targ, arg))
18261             return unify_success (explain_p);
18262           else if (targ)
18263             return unify_inconsistency (explain_p, parm, targ, arg);
18264         }
18265       else
18266         {
18267           /* If PARM is `const T' and ARG is only `int', we don't have
18268              a match unless we are allowing additional qualification.
18269              If ARG is `const int' and PARM is just `T' that's OK;
18270              that binds `const int' to `T'.  */
18271           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
18272                                          arg, parm))
18273             return unify_cv_qual_mismatch (explain_p, parm, arg);
18274
18275           /* Consider the case where ARG is `const volatile int' and
18276              PARM is `const T'.  Then, T should be `volatile int'.  */
18277           arg = cp_build_qualified_type_real
18278             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
18279           if (arg == error_mark_node)
18280             return unify_invalid (explain_p);
18281
18282           /* Simple cases: Value already set, does match or doesn't.  */
18283           if (targ != NULL_TREE && same_type_p (targ, arg))
18284             return unify_success (explain_p);
18285           else if (targ)
18286             return unify_inconsistency (explain_p, parm, targ, arg);
18287
18288           /* Make sure that ARG is not a variable-sized array.  (Note
18289              that were talking about variable-sized arrays (like
18290              `int[n]'), rather than arrays of unknown size (like
18291              `int[]').)  We'll get very confused by such a type since
18292              the bound of the array is not constant, and therefore
18293              not mangleable.  Besides, such types are not allowed in
18294              ISO C++, so we can do as we please here.  We do allow
18295              them for 'auto' deduction, since that isn't ABI-exposed.  */
18296           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
18297             return unify_vla_arg (explain_p, arg);
18298
18299           /* Strip typedefs as in convert_template_argument.  */
18300           arg = canonicalize_type_argument (arg, tf_none);
18301         }
18302
18303       /* If ARG is a parameter pack or an expansion, we cannot unify
18304          against it unless PARM is also a parameter pack.  */
18305       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
18306           && !template_parameter_pack_p (parm))
18307         return unify_parameter_pack_mismatch (explain_p, parm, arg);
18308
18309       /* If the argument deduction results is a METHOD_TYPE,
18310          then there is a problem.
18311          METHOD_TYPE doesn't map to any real C++ type the result of
18312          the deduction can not be of that type.  */
18313       if (TREE_CODE (arg) == METHOD_TYPE)
18314         return unify_method_type_error (explain_p, arg);
18315
18316       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
18317       return unify_success (explain_p);
18318
18319     case TEMPLATE_PARM_INDEX:
18320       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
18321       if (error_operand_p (tparm))
18322         return unify_invalid (explain_p);
18323
18324       if (TEMPLATE_PARM_LEVEL (parm)
18325           != template_decl_level (tparm))
18326         {
18327           /* The PARM is not one we're trying to unify.  Just check
18328              to see if it matches ARG.  */
18329           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
18330                          && cp_tree_equal (parm, arg));
18331           if (result)
18332             unify_expression_unequal (explain_p, parm, arg);
18333           return result;
18334         }
18335
18336       idx = TEMPLATE_PARM_IDX (parm);
18337       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
18338
18339       if (targ)
18340         {
18341           int x = !cp_tree_equal (targ, arg);
18342           if (x)
18343             unify_inconsistency (explain_p, parm, targ, arg);
18344           return x;
18345         }
18346
18347       /* [temp.deduct.type] If, in the declaration of a function template
18348          with a non-type template-parameter, the non-type
18349          template-parameter is used in an expression in the function
18350          parameter-list and, if the corresponding template-argument is
18351          deduced, the template-argument type shall match the type of the
18352          template-parameter exactly, except that a template-argument
18353          deduced from an array bound may be of any integral type.
18354          The non-type parameter might use already deduced type parameters.  */
18355       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
18356       if (!TREE_TYPE (arg))
18357         /* Template-parameter dependent expression.  Just accept it for now.
18358            It will later be processed in convert_template_argument.  */
18359         ;
18360       else if (same_type_p (TREE_TYPE (arg), tparm))
18361         /* OK */;
18362       else if ((strict & UNIFY_ALLOW_INTEGER)
18363                && CP_INTEGRAL_TYPE_P (tparm))
18364         /* Convert the ARG to the type of PARM; the deduced non-type
18365            template argument must exactly match the types of the
18366            corresponding parameter.  */
18367         arg = fold (build_nop (tparm, arg));
18368       else if (uses_template_parms (tparm))
18369         /* We haven't deduced the type of this parameter yet.  Try again
18370            later.  */
18371         return unify_success (explain_p);
18372       else
18373         return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
18374
18375       /* If ARG is a parameter pack or an expansion, we cannot unify
18376          against it unless PARM is also a parameter pack.  */
18377       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
18378           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
18379         return unify_parameter_pack_mismatch (explain_p, parm, arg);
18380
18381       arg = strip_typedefs_expr (arg);
18382       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
18383       return unify_success (explain_p);
18384
18385     case PTRMEM_CST:
18386      {
18387         /* A pointer-to-member constant can be unified only with
18388          another constant.  */
18389       if (TREE_CODE (arg) != PTRMEM_CST)
18390         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
18391
18392       /* Just unify the class member. It would be useless (and possibly
18393          wrong, depending on the strict flags) to unify also
18394          PTRMEM_CST_CLASS, because we want to be sure that both parm and
18395          arg refer to the same variable, even if through different
18396          classes. For instance:
18397
18398          struct A { int x; };
18399          struct B : A { };
18400
18401          Unification of &A::x and &B::x must succeed.  */
18402       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
18403                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
18404      }
18405
18406     case POINTER_TYPE:
18407       {
18408         if (!TYPE_PTR_P (arg))
18409           return unify_type_mismatch (explain_p, parm, arg);
18410
18411         /* [temp.deduct.call]
18412
18413            A can be another pointer or pointer to member type that can
18414            be converted to the deduced A via a qualification
18415            conversion (_conv.qual_).
18416
18417            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
18418            This will allow for additional cv-qualification of the
18419            pointed-to types if appropriate.  */
18420
18421         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
18422           /* The derived-to-base conversion only persists through one
18423              level of pointers.  */
18424           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
18425
18426         return unify (tparms, targs, TREE_TYPE (parm),
18427                       TREE_TYPE (arg), strict, explain_p);
18428       }
18429
18430     case REFERENCE_TYPE:
18431       if (TREE_CODE (arg) != REFERENCE_TYPE)
18432         return unify_type_mismatch (explain_p, parm, arg);
18433       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
18434                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
18435
18436     case ARRAY_TYPE:
18437       if (TREE_CODE (arg) != ARRAY_TYPE)
18438         return unify_type_mismatch (explain_p, parm, arg);
18439       if ((TYPE_DOMAIN (parm) == NULL_TREE)
18440           != (TYPE_DOMAIN (arg) == NULL_TREE))
18441         return unify_type_mismatch (explain_p, parm, arg);
18442       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
18443                                strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
18444       if (TYPE_DOMAIN (parm) != NULL_TREE)
18445         return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
18446                                    TYPE_DOMAIN (arg), explain_p);
18447       return unify_success (explain_p);
18448
18449     case REAL_TYPE:
18450     case COMPLEX_TYPE:
18451     case VECTOR_TYPE:
18452     case INTEGER_TYPE:
18453     case BOOLEAN_TYPE:
18454     case ENUMERAL_TYPE:
18455     case VOID_TYPE:
18456     case NULLPTR_TYPE:
18457       if (TREE_CODE (arg) != TREE_CODE (parm))
18458         return unify_type_mismatch (explain_p, parm, arg);
18459
18460       /* We have already checked cv-qualification at the top of the
18461          function.  */
18462       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
18463         return unify_type_mismatch (explain_p, parm, arg);
18464
18465       /* As far as unification is concerned, this wins.  Later checks
18466          will invalidate it if necessary.  */
18467       return unify_success (explain_p);
18468
18469       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
18470       /* Type INTEGER_CST can come from ordinary constant template args.  */
18471     case INTEGER_CST:
18472       while (TREE_CODE (arg) == NOP_EXPR)
18473         arg = TREE_OPERAND (arg, 0);
18474
18475       if (TREE_CODE (arg) != INTEGER_CST)
18476         return unify_template_argument_mismatch (explain_p, parm, arg);
18477       return (tree_int_cst_equal (parm, arg)
18478               ? unify_success (explain_p)
18479               : unify_template_argument_mismatch (explain_p, parm, arg));
18480
18481     case TREE_VEC:
18482       {
18483         int i, len, argslen;
18484         int parm_variadic_p = 0;
18485
18486         if (TREE_CODE (arg) != TREE_VEC)
18487           return unify_template_argument_mismatch (explain_p, parm, arg);
18488
18489         len = TREE_VEC_LENGTH (parm);
18490         argslen = TREE_VEC_LENGTH (arg);
18491
18492         /* Check for pack expansions in the parameters.  */
18493         for (i = 0; i < len; ++i)
18494           {
18495             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
18496               {
18497                 if (i == len - 1)
18498                   /* We can unify against something with a trailing
18499                      parameter pack.  */
18500                   parm_variadic_p = 1;
18501                 else
18502                   /* [temp.deduct.type]/9: If the template argument list of
18503                      P contains a pack expansion that is not the last
18504                      template argument, the entire template argument list
18505                      is a non-deduced context.  */
18506                   return unify_success (explain_p);
18507               }
18508           }
18509
18510         /* If we don't have enough arguments to satisfy the parameters
18511            (not counting the pack expression at the end), or we have
18512            too many arguments for a parameter list that doesn't end in
18513            a pack expression, we can't unify.  */
18514         if (parm_variadic_p
18515             ? argslen < len - parm_variadic_p
18516             : argslen != len)
18517           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
18518
18519         /* Unify all of the parameters that precede the (optional)
18520            pack expression.  */
18521         for (i = 0; i < len - parm_variadic_p; ++i)
18522           {
18523             RECUR_AND_CHECK_FAILURE (tparms, targs,
18524                                      TREE_VEC_ELT (parm, i),
18525                                      TREE_VEC_ELT (arg, i),
18526                                      UNIFY_ALLOW_NONE, explain_p);
18527           }
18528         if (parm_variadic_p)
18529           return unify_pack_expansion (tparms, targs, parm, arg,
18530                                        DEDUCE_EXACT,
18531                                        /*subr=*/true, explain_p);
18532         return unify_success (explain_p);
18533       }
18534
18535     case RECORD_TYPE:
18536     case UNION_TYPE:
18537       if (TREE_CODE (arg) != TREE_CODE (parm))
18538         return unify_type_mismatch (explain_p, parm, arg);
18539
18540       if (TYPE_PTRMEMFUNC_P (parm))
18541         {
18542           if (!TYPE_PTRMEMFUNC_P (arg))
18543             return unify_type_mismatch (explain_p, parm, arg);
18544
18545           return unify (tparms, targs,
18546                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
18547                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
18548                         strict, explain_p);
18549         }
18550       else if (TYPE_PTRMEMFUNC_P (arg))
18551         return unify_type_mismatch (explain_p, parm, arg);
18552
18553       if (CLASSTYPE_TEMPLATE_INFO (parm))
18554         {
18555           tree t = NULL_TREE;
18556
18557           if (strict_in & UNIFY_ALLOW_DERIVED)
18558             {
18559               /* First, we try to unify the PARM and ARG directly.  */
18560               t = try_class_unification (tparms, targs,
18561                                          parm, arg, explain_p);
18562
18563               if (!t)
18564                 {
18565                   /* Fallback to the special case allowed in
18566                      [temp.deduct.call]:
18567
18568                        If P is a class, and P has the form
18569                        template-id, then A can be a derived class of
18570                        the deduced A.  Likewise, if P is a pointer to
18571                        a class of the form template-id, A can be a
18572                        pointer to a derived class pointed to by the
18573                        deduced A.  */
18574                   enum template_base_result r;
18575                   r = get_template_base (tparms, targs, parm, arg,
18576                                          explain_p, &t);
18577
18578                   if (!t)
18579                     return unify_no_common_base (explain_p, r, parm, arg);
18580                 }
18581             }
18582           else if (CLASSTYPE_TEMPLATE_INFO (arg)
18583                    && (CLASSTYPE_TI_TEMPLATE (parm)
18584                        == CLASSTYPE_TI_TEMPLATE (arg)))
18585             /* Perhaps PARM is something like S<U> and ARG is S<int>.
18586                Then, we should unify `int' and `U'.  */
18587             t = arg;
18588           else
18589             /* There's no chance of unification succeeding.  */
18590             return unify_type_mismatch (explain_p, parm, arg);
18591
18592           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
18593                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
18594         }
18595       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
18596         return unify_type_mismatch (explain_p, parm, arg);
18597       return unify_success (explain_p);
18598
18599     case METHOD_TYPE:
18600     case FUNCTION_TYPE:
18601       {
18602         unsigned int nargs;
18603         tree *args;
18604         tree a;
18605         unsigned int i;
18606
18607         if (TREE_CODE (arg) != TREE_CODE (parm))
18608           return unify_type_mismatch (explain_p, parm, arg);
18609
18610         /* CV qualifications for methods can never be deduced, they must
18611            match exactly.  We need to check them explicitly here,
18612            because type_unification_real treats them as any other
18613            cv-qualified parameter.  */
18614         if (TREE_CODE (parm) == METHOD_TYPE
18615             && (!check_cv_quals_for_unify
18616                 (UNIFY_ALLOW_NONE,
18617                  class_of_this_parm (arg),
18618                  class_of_this_parm (parm))))
18619           return unify_cv_qual_mismatch (explain_p, parm, arg);
18620
18621         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
18622                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
18623
18624         nargs = list_length (TYPE_ARG_TYPES (arg));
18625         args = XALLOCAVEC (tree, nargs);
18626         for (a = TYPE_ARG_TYPES (arg), i = 0;
18627              a != NULL_TREE && a != void_list_node;
18628              a = TREE_CHAIN (a), ++i)
18629           args[i] = TREE_VALUE (a);
18630         nargs = i;
18631
18632         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
18633                                       args, nargs, 1, DEDUCE_EXACT,
18634                                       LOOKUP_NORMAL, NULL, explain_p);
18635       }
18636
18637     case OFFSET_TYPE:
18638       /* Unify a pointer to member with a pointer to member function, which
18639          deduces the type of the member as a function type. */
18640       if (TYPE_PTRMEMFUNC_P (arg))
18641         {
18642           /* Check top-level cv qualifiers */
18643           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
18644             return unify_cv_qual_mismatch (explain_p, parm, arg);
18645
18646           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
18647                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
18648                                    UNIFY_ALLOW_NONE, explain_p);
18649
18650           /* Determine the type of the function we are unifying against. */
18651           tree fntype = static_fn_type (arg);
18652
18653           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
18654         }
18655
18656       if (TREE_CODE (arg) != OFFSET_TYPE)
18657         return unify_type_mismatch (explain_p, parm, arg);
18658       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
18659                                TYPE_OFFSET_BASETYPE (arg),
18660                                UNIFY_ALLOW_NONE, explain_p);
18661       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
18662                     strict, explain_p);
18663
18664     case CONST_DECL:
18665       if (DECL_TEMPLATE_PARM_P (parm))
18666         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
18667       if (arg != scalar_constant_value (parm))
18668         return unify_template_argument_mismatch (explain_p, parm, arg);
18669       return unify_success (explain_p);
18670
18671     case FIELD_DECL:
18672     case TEMPLATE_DECL:
18673       /* Matched cases are handled by the ARG == PARM test above.  */
18674       return unify_template_argument_mismatch (explain_p, parm, arg);
18675
18676     case VAR_DECL:
18677       /* A non-type template parameter that is a variable should be a
18678          an integral constant, in which case, it whould have been
18679          folded into its (constant) value. So we should not be getting
18680          a variable here.  */
18681       gcc_unreachable ();
18682
18683     case TYPE_ARGUMENT_PACK:
18684     case NONTYPE_ARGUMENT_PACK:
18685       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
18686                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
18687
18688     case TYPEOF_TYPE:
18689     case DECLTYPE_TYPE:
18690     case UNDERLYING_TYPE:
18691       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
18692          or UNDERLYING_TYPE nodes.  */
18693       return unify_success (explain_p);
18694
18695     case ERROR_MARK:
18696       /* Unification fails if we hit an error node.  */
18697       return unify_invalid (explain_p);
18698
18699     case INDIRECT_REF:
18700       if (REFERENCE_REF_P (parm))
18701         {
18702           if (REFERENCE_REF_P (arg))
18703             arg = TREE_OPERAND (arg, 0);
18704           return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
18705                         strict, explain_p);
18706         }
18707       /* FALLTHRU */
18708
18709     default:
18710       /* An unresolved overload is a nondeduced context.  */
18711       if (is_overloaded_fn (parm) || type_unknown_p (parm))
18712         return unify_success (explain_p);
18713       gcc_assert (EXPR_P (parm));
18714
18715       /* We must be looking at an expression.  This can happen with
18716          something like:
18717
18718            template <int I>
18719            void foo(S<I>, S<I + 2>);
18720
18721          This is a "nondeduced context":
18722
18723            [deduct.type]
18724
18725            The nondeduced contexts are:
18726
18727            --A type that is a template-id in which one or more of
18728              the template-arguments is an expression that references
18729              a template-parameter.
18730
18731          In these cases, we assume deduction succeeded, but don't
18732          actually infer any unifications.  */
18733
18734       if (!uses_template_parms (parm)
18735           && !template_args_equal (parm, arg))
18736         return unify_expression_unequal (explain_p, parm, arg);
18737       else
18738         return unify_success (explain_p);
18739     }
18740 }
18741 #undef RECUR_AND_CHECK_FAILURE
18742 \f
18743 /* Note that DECL can be defined in this translation unit, if
18744    required.  */
18745
18746 static void
18747 mark_definable (tree decl)
18748 {
18749   tree clone;
18750   DECL_NOT_REALLY_EXTERN (decl) = 1;
18751   FOR_EACH_CLONE (clone, decl)
18752     DECL_NOT_REALLY_EXTERN (clone) = 1;
18753 }
18754
18755 /* Called if RESULT is explicitly instantiated, or is a member of an
18756    explicitly instantiated class.  */
18757
18758 void
18759 mark_decl_instantiated (tree result, int extern_p)
18760 {
18761   SET_DECL_EXPLICIT_INSTANTIATION (result);
18762
18763   /* If this entity has already been written out, it's too late to
18764      make any modifications.  */
18765   if (TREE_ASM_WRITTEN (result))
18766     return;
18767
18768   /* For anonymous namespace we don't need to do anything.  */
18769   if (decl_anon_ns_mem_p (result))
18770     {
18771       gcc_assert (!TREE_PUBLIC (result));
18772       return;
18773     }
18774
18775   if (TREE_CODE (result) != FUNCTION_DECL)
18776     /* The TREE_PUBLIC flag for function declarations will have been
18777        set correctly by tsubst.  */
18778     TREE_PUBLIC (result) = 1;
18779
18780   /* This might have been set by an earlier implicit instantiation.  */
18781   DECL_COMDAT (result) = 0;
18782
18783   if (extern_p)
18784     DECL_NOT_REALLY_EXTERN (result) = 0;
18785   else
18786     {
18787       mark_definable (result);
18788       mark_needed (result);
18789       /* Always make artificials weak.  */
18790       if (DECL_ARTIFICIAL (result) && flag_weak)
18791         comdat_linkage (result);
18792       /* For WIN32 we also want to put explicit instantiations in
18793          linkonce sections.  */
18794       else if (TREE_PUBLIC (result))
18795         maybe_make_one_only (result);
18796     }
18797
18798   /* If EXTERN_P, then this function will not be emitted -- unless
18799      followed by an explicit instantiation, at which point its linkage
18800      will be adjusted.  If !EXTERN_P, then this function will be
18801      emitted here.  In neither circumstance do we want
18802      import_export_decl to adjust the linkage.  */
18803   DECL_INTERFACE_KNOWN (result) = 1;
18804 }
18805
18806 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
18807    important template arguments.  If any are missing, we check whether
18808    they're important by using error_mark_node for substituting into any
18809    args that were used for partial ordering (the ones between ARGS and END)
18810    and seeing if it bubbles up.  */
18811
18812 static bool
18813 check_undeduced_parms (tree targs, tree args, tree end)
18814 {
18815   bool found = false;
18816   int i;
18817   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
18818     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
18819       {
18820         found = true;
18821         TREE_VEC_ELT (targs, i) = error_mark_node;
18822       }
18823   if (found)
18824     {
18825       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
18826       if (substed == error_mark_node)
18827         return true;
18828     }
18829   return false;
18830 }
18831
18832 /* Given two function templates PAT1 and PAT2, return:
18833
18834    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
18835    -1 if PAT2 is more specialized than PAT1.
18836    0 if neither is more specialized.
18837
18838    LEN indicates the number of parameters we should consider
18839    (defaulted parameters should not be considered).
18840
18841    The 1998 std underspecified function template partial ordering, and
18842    DR214 addresses the issue.  We take pairs of arguments, one from
18843    each of the templates, and deduce them against each other.  One of
18844    the templates will be more specialized if all the *other*
18845    template's arguments deduce against its arguments and at least one
18846    of its arguments *does* *not* deduce against the other template's
18847    corresponding argument.  Deduction is done as for class templates.
18848    The arguments used in deduction have reference and top level cv
18849    qualifiers removed.  Iff both arguments were originally reference
18850    types *and* deduction succeeds in both directions, an lvalue reference
18851    wins against an rvalue reference and otherwise the template
18852    with the more cv-qualified argument wins for that pairing (if
18853    neither is more cv-qualified, they both are equal).  Unlike regular
18854    deduction, after all the arguments have been deduced in this way,
18855    we do *not* verify the deduced template argument values can be
18856    substituted into non-deduced contexts.
18857
18858    The logic can be a bit confusing here, because we look at deduce1 and
18859    targs1 to see if pat2 is at least as specialized, and vice versa; if we
18860    can find template arguments for pat1 to make arg1 look like arg2, that
18861    means that arg2 is at least as specialized as arg1.  */
18862
18863 int
18864 more_specialized_fn (tree pat1, tree pat2, int len)
18865 {
18866   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
18867   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
18868   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
18869   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
18870   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
18871   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
18872   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
18873   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
18874   tree origs1, origs2;
18875   bool lose1 = false;
18876   bool lose2 = false;
18877
18878   /* Remove the this parameter from non-static member functions.  If
18879      one is a non-static member function and the other is not a static
18880      member function, remove the first parameter from that function
18881      also.  This situation occurs for operator functions where we
18882      locate both a member function (with this pointer) and non-member
18883      operator (with explicit first operand).  */
18884   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
18885     {
18886       len--; /* LEN is the number of significant arguments for DECL1 */
18887       args1 = TREE_CHAIN (args1);
18888       if (!DECL_STATIC_FUNCTION_P (decl2))
18889         args2 = TREE_CHAIN (args2);
18890     }
18891   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
18892     {
18893       args2 = TREE_CHAIN (args2);
18894       if (!DECL_STATIC_FUNCTION_P (decl1))
18895         {
18896           len--;
18897           args1 = TREE_CHAIN (args1);
18898         }
18899     }
18900
18901   /* If only one is a conversion operator, they are unordered.  */
18902   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
18903     return 0;
18904
18905   /* Consider the return type for a conversion function */
18906   if (DECL_CONV_FN_P (decl1))
18907     {
18908       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
18909       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
18910       len++;
18911     }
18912
18913   processing_template_decl++;
18914
18915   origs1 = args1;
18916   origs2 = args2;
18917
18918   while (len--
18919          /* Stop when an ellipsis is seen.  */
18920          && args1 != NULL_TREE && args2 != NULL_TREE)
18921     {
18922       tree arg1 = TREE_VALUE (args1);
18923       tree arg2 = TREE_VALUE (args2);
18924       int deduce1, deduce2;
18925       int quals1 = -1;
18926       int quals2 = -1;
18927       int ref1 = 0;
18928       int ref2 = 0;
18929
18930       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
18931           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
18932         {
18933           /* When both arguments are pack expansions, we need only
18934              unify the patterns themselves.  */
18935           arg1 = PACK_EXPANSION_PATTERN (arg1);
18936           arg2 = PACK_EXPANSION_PATTERN (arg2);
18937
18938           /* This is the last comparison we need to do.  */
18939           len = 0;
18940         }
18941
18942       if (TREE_CODE (arg1) == REFERENCE_TYPE)
18943         {
18944           ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
18945           arg1 = TREE_TYPE (arg1);
18946           quals1 = cp_type_quals (arg1);
18947         }
18948
18949       if (TREE_CODE (arg2) == REFERENCE_TYPE)
18950         {
18951           ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
18952           arg2 = TREE_TYPE (arg2);
18953           quals2 = cp_type_quals (arg2);
18954         }
18955
18956       arg1 = TYPE_MAIN_VARIANT (arg1);
18957       arg2 = TYPE_MAIN_VARIANT (arg2);
18958
18959       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
18960         {
18961           int i, len2 = list_length (args2);
18962           tree parmvec = make_tree_vec (1);
18963           tree argvec = make_tree_vec (len2);
18964           tree ta = args2;
18965
18966           /* Setup the parameter vector, which contains only ARG1.  */
18967           TREE_VEC_ELT (parmvec, 0) = arg1;
18968
18969           /* Setup the argument vector, which contains the remaining
18970              arguments.  */
18971           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
18972             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
18973
18974           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
18975                                            argvec, DEDUCE_EXACT,
18976                                            /*subr=*/true, /*explain_p=*/false)
18977                      == 0);
18978
18979           /* We cannot deduce in the other direction, because ARG1 is
18980              a pack expansion but ARG2 is not.  */
18981           deduce2 = 0;
18982         }
18983       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
18984         {
18985           int i, len1 = list_length (args1);
18986           tree parmvec = make_tree_vec (1);
18987           tree argvec = make_tree_vec (len1);
18988           tree ta = args1;
18989
18990           /* Setup the parameter vector, which contains only ARG1.  */
18991           TREE_VEC_ELT (parmvec, 0) = arg2;
18992
18993           /* Setup the argument vector, which contains the remaining
18994              arguments.  */
18995           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
18996             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
18997
18998           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
18999                                            argvec, DEDUCE_EXACT,
19000                                            /*subr=*/true, /*explain_p=*/false)
19001                      == 0);
19002
19003           /* We cannot deduce in the other direction, because ARG2 is
19004              a pack expansion but ARG1 is not.*/
19005           deduce1 = 0;
19006         }
19007
19008       else
19009         {
19010           /* The normal case, where neither argument is a pack
19011              expansion.  */
19012           deduce1 = (unify (tparms1, targs1, arg1, arg2,
19013                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
19014                      == 0);
19015           deduce2 = (unify (tparms2, targs2, arg2, arg1,
19016                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
19017                      == 0);
19018         }
19019
19020       /* If we couldn't deduce arguments for tparms1 to make arg1 match
19021          arg2, then arg2 is not as specialized as arg1.  */
19022       if (!deduce1)
19023         lose2 = true;
19024       if (!deduce2)
19025         lose1 = true;
19026
19027       /* "If, for a given type, deduction succeeds in both directions
19028          (i.e., the types are identical after the transformations above)
19029          and both P and A were reference types (before being replaced with
19030          the type referred to above):
19031          - if the type from the argument template was an lvalue reference and
19032          the type from the parameter template was not, the argument type is
19033          considered to be more specialized than the other; otherwise,
19034          - if the type from the argument template is more cv-qualified
19035          than the type from the parameter template (as described above),
19036          the argument type is considered to be more specialized than the other;
19037          otherwise,
19038          - neither type is more specialized than the other."  */
19039
19040       if (deduce1 && deduce2)
19041         {
19042           if (ref1 && ref2 && ref1 != ref2)
19043             {
19044               if (ref1 > ref2)
19045                 lose1 = true;
19046               else
19047                 lose2 = true;
19048             }
19049           else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
19050             {
19051               if ((quals1 & quals2) == quals2)
19052                 lose2 = true;
19053               if ((quals1 & quals2) == quals1)
19054                 lose1 = true;
19055             }
19056         }
19057
19058       if (lose1 && lose2)
19059         /* We've failed to deduce something in either direction.
19060            These must be unordered.  */
19061         break;
19062
19063       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
19064           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
19065         /* We have already processed all of the arguments in our
19066            handing of the pack expansion type.  */
19067         len = 0;
19068
19069       args1 = TREE_CHAIN (args1);
19070       args2 = TREE_CHAIN (args2);
19071     }
19072
19073   /* "In most cases, all template parameters must have values in order for
19074      deduction to succeed, but for partial ordering purposes a template
19075      parameter may remain without a value provided it is not used in the
19076      types being used for partial ordering."
19077
19078      Thus, if we are missing any of the targs1 we need to substitute into
19079      origs1, then pat2 is not as specialized as pat1.  This can happen when
19080      there is a nondeduced context.  */
19081   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
19082     lose2 = true;
19083   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
19084     lose1 = true;
19085
19086   processing_template_decl--;
19087
19088   /* All things being equal, if the next argument is a pack expansion
19089      for one function but not for the other, prefer the
19090      non-variadic function.  FIXME this is bogus; see c++/41958.  */
19091   if (lose1 == lose2
19092       && args1 && TREE_VALUE (args1)
19093       && args2 && TREE_VALUE (args2))
19094     {
19095       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
19096       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
19097     }
19098
19099   if (lose1 == lose2)
19100     return 0;
19101   else if (!lose1)
19102     return 1;
19103   else
19104     return -1;
19105 }
19106
19107 /* Determine which of two partial specializations of TMPL is more
19108    specialized.
19109
19110    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
19111    to the first partial specialization.  The TREE_PURPOSE is the
19112    innermost set of template parameters for the partial
19113    specialization.  PAT2 is similar, but for the second template.
19114
19115    Return 1 if the first partial specialization is more specialized;
19116    -1 if the second is more specialized; 0 if neither is more
19117    specialized.
19118
19119    See [temp.class.order] for information about determining which of
19120    two templates is more specialized.  */
19121
19122 static int
19123 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
19124 {
19125   tree targs;
19126   int winner = 0;
19127   bool any_deductions = false;
19128
19129   tree tmpl1 = TREE_VALUE (pat1);
19130   tree tmpl2 = TREE_VALUE (pat2);
19131   tree parms1 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl1);
19132   tree parms2 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl2);
19133   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
19134   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
19135
19136   /* Just like what happens for functions, if we are ordering between
19137      different template specializations, we may encounter dependent
19138      types in the arguments, and we need our dependency check functions
19139      to behave correctly.  */
19140   ++processing_template_decl;
19141   targs = get_partial_spec_bindings (tmpl, parms1, specargs1, specargs2);
19142   if (targs)
19143     {
19144       --winner;
19145       any_deductions = true;
19146     }
19147
19148   targs = get_partial_spec_bindings (tmpl, parms2, specargs2, specargs1);
19149   if (targs)
19150     {
19151       ++winner;
19152       any_deductions = true;
19153     }
19154   --processing_template_decl;
19155
19156   /* In the case of a tie where at least one of the templates
19157      has a parameter pack at the end, the template with the most
19158      non-packed parameters wins.  */
19159   if (winner == 0
19160       && any_deductions
19161       && (template_args_variadic_p (TREE_PURPOSE (pat1))
19162           || template_args_variadic_p (TREE_PURPOSE (pat2))))
19163     {
19164       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
19165       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
19166       int len1 = TREE_VEC_LENGTH (args1);
19167       int len2 = TREE_VEC_LENGTH (args2);
19168
19169       /* We don't count the pack expansion at the end.  */
19170       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
19171         --len1;
19172       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
19173         --len2;
19174
19175       if (len1 > len2)
19176         return 1;
19177       else if (len1 < len2)
19178         return -1;
19179     }
19180
19181   return winner;
19182 }
19183
19184 /* Return the template arguments that will produce the function signature
19185    DECL from the function template FN, with the explicit template
19186    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
19187    also match.  Return NULL_TREE if no satisfactory arguments could be
19188    found.  */
19189
19190 static tree
19191 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
19192 {
19193   int ntparms = DECL_NTPARMS (fn);
19194   tree targs = make_tree_vec (ntparms);
19195   tree decl_type = TREE_TYPE (decl);
19196   tree decl_arg_types;
19197   tree *args;
19198   unsigned int nargs, ix;
19199   tree arg;
19200
19201   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
19202
19203   /* Never do unification on the 'this' parameter.  */
19204   decl_arg_types = skip_artificial_parms_for (decl, 
19205                                               TYPE_ARG_TYPES (decl_type));
19206
19207   nargs = list_length (decl_arg_types);
19208   args = XALLOCAVEC (tree, nargs);
19209   for (arg = decl_arg_types, ix = 0;
19210        arg != NULL_TREE && arg != void_list_node;
19211        arg = TREE_CHAIN (arg), ++ix)
19212     args[ix] = TREE_VALUE (arg);
19213
19214   if (fn_type_unification (fn, explicit_args, targs,
19215                            args, ix,
19216                            (check_rettype || DECL_CONV_FN_P (fn)
19217                             ? TREE_TYPE (decl_type) : NULL_TREE),
19218                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
19219                            /*decltype*/false)
19220       == error_mark_node)
19221     return NULL_TREE;
19222
19223   return targs;
19224 }
19225
19226 /* Return the innermost template arguments that, when applied to a partial
19227    specialization of TMPL whose innermost template parameters are
19228    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
19229    ARGS.
19230
19231    For example, suppose we have:
19232
19233      template <class T, class U> struct S {};
19234      template <class T> struct S<T*, int> {};
19235
19236    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
19237    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
19238    int}.  The resulting vector will be {double}, indicating that `T'
19239    is bound to `double'.  */
19240
19241 static tree
19242 get_partial_spec_bindings (tree tmpl, tree tparms, tree spec_args, tree args)
19243 {
19244   int i, ntparms = TREE_VEC_LENGTH (tparms);
19245   tree deduced_args;
19246   tree innermost_deduced_args;
19247
19248   innermost_deduced_args = make_tree_vec (ntparms);
19249   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
19250     {
19251       deduced_args = copy_node (args);
19252       SET_TMPL_ARGS_LEVEL (deduced_args,
19253                            TMPL_ARGS_DEPTH (deduced_args),
19254                            innermost_deduced_args);
19255     }
19256   else
19257     deduced_args = innermost_deduced_args;
19258
19259   if (unify (tparms, deduced_args,
19260              INNERMOST_TEMPLATE_ARGS (spec_args),
19261              INNERMOST_TEMPLATE_ARGS (args),
19262              UNIFY_ALLOW_NONE, /*explain_p=*/false))
19263     return NULL_TREE;
19264
19265   for (i =  0; i < ntparms; ++i)
19266     if (! TREE_VEC_ELT (innermost_deduced_args, i))
19267       return NULL_TREE;
19268
19269   /* Verify that nondeduced template arguments agree with the type
19270      obtained from argument deduction.
19271
19272      For example:
19273
19274        struct A { typedef int X; };
19275        template <class T, class U> struct C {};
19276        template <class T> struct C<T, typename T::X> {};
19277
19278      Then with the instantiation `C<A, int>', we can deduce that
19279      `T' is `A' but unify () does not check whether `typename T::X'
19280      is `int'.  */
19281   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
19282   spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
19283                                      spec_args, tmpl,
19284                                      tf_none, false, false);
19285   if (spec_args == error_mark_node
19286       /* We only need to check the innermost arguments; the other
19287          arguments will always agree.  */
19288       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
19289                               INNERMOST_TEMPLATE_ARGS (args)))
19290     return NULL_TREE;
19291
19292   /* Now that we have bindings for all of the template arguments,
19293      ensure that the arguments deduced for the template template
19294      parameters have compatible template parameter lists.  See the use
19295      of template_template_parm_bindings_ok_p in fn_type_unification
19296      for more information.  */
19297   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
19298     return NULL_TREE;
19299
19300   return deduced_args;
19301 }
19302
19303 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
19304    Return the TREE_LIST node with the most specialized template, if
19305    any.  If there is no most specialized template, the error_mark_node
19306    is returned.
19307
19308    Note that this function does not look at, or modify, the
19309    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
19310    returned is one of the elements of INSTANTIATIONS, callers may
19311    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
19312    and retrieve it from the value returned.  */
19313
19314 tree
19315 most_specialized_instantiation (tree templates)
19316 {
19317   tree fn, champ;
19318
19319   ++processing_template_decl;
19320
19321   champ = templates;
19322   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
19323     {
19324       int fate = 0;
19325
19326       if (get_bindings (TREE_VALUE (champ),
19327                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
19328                         NULL_TREE, /*check_ret=*/true))
19329         fate--;
19330
19331       if (get_bindings (TREE_VALUE (fn),
19332                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
19333                         NULL_TREE, /*check_ret=*/true))
19334         fate++;
19335
19336       if (fate == -1)
19337         champ = fn;
19338       else if (!fate)
19339         {
19340           /* Equally specialized, move to next function.  If there
19341              is no next function, nothing's most specialized.  */
19342           fn = TREE_CHAIN (fn);
19343           champ = fn;
19344           if (!fn)
19345             break;
19346         }
19347     }
19348
19349   if (champ)
19350     /* Now verify that champ is better than everything earlier in the
19351        instantiation list.  */
19352     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
19353       if (get_bindings (TREE_VALUE (champ),
19354                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
19355                         NULL_TREE, /*check_ret=*/true)
19356           || !get_bindings (TREE_VALUE (fn),
19357                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
19358                             NULL_TREE, /*check_ret=*/true))
19359         {
19360           champ = NULL_TREE;
19361           break;
19362         }
19363
19364   processing_template_decl--;
19365
19366   if (!champ)
19367     return error_mark_node;
19368
19369   return champ;
19370 }
19371
19372 /* If DECL is a specialization of some template, return the most
19373    general such template.  Otherwise, returns NULL_TREE.
19374
19375    For example, given:
19376
19377      template <class T> struct S { template <class U> void f(U); };
19378
19379    if TMPL is `template <class U> void S<int>::f(U)' this will return
19380    the full template.  This function will not trace past partial
19381    specializations, however.  For example, given in addition:
19382
19383      template <class T> struct S<T*> { template <class U> void f(U); };
19384
19385    if TMPL is `template <class U> void S<int*>::f(U)' this will return
19386    `template <class T> template <class U> S<T*>::f(U)'.  */
19387
19388 tree
19389 most_general_template (tree decl)
19390 {
19391   if (TREE_CODE (decl) != TEMPLATE_DECL)
19392     {
19393       if (tree tinfo = get_template_info (decl))
19394         decl = TI_TEMPLATE (tinfo);
19395       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
19396          template friend, or a FIELD_DECL for a capture pack.  */
19397       if (TREE_CODE (decl) != TEMPLATE_DECL)
19398         return NULL_TREE;
19399     }
19400
19401   /* Look for more and more general templates.  */
19402   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
19403     {
19404       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
19405          (See cp-tree.h for details.)  */
19406       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
19407         break;
19408
19409       if (CLASS_TYPE_P (TREE_TYPE (decl))
19410           && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
19411           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
19412         break;
19413
19414       /* Stop if we run into an explicitly specialized class template.  */
19415       if (!DECL_NAMESPACE_SCOPE_P (decl)
19416           && DECL_CONTEXT (decl)
19417           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
19418         break;
19419
19420       decl = DECL_TI_TEMPLATE (decl);
19421     }
19422
19423   return decl;
19424 }
19425
19426 /* Return the most specialized of the template partial specializations
19427    which can produce TARGET, a specialization of some class or variable
19428    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
19429    a TEMPLATE_DECL node corresponding to the partial specialization, while
19430    the TREE_PURPOSE is the set of template arguments that must be
19431    substituted into the template pattern in order to generate TARGET.
19432
19433    If the choice of partial specialization is ambiguous, a diagnostic
19434    is issued, and the error_mark_node is returned.  If there are no
19435    partial specializations matching TARGET, then NULL_TREE is
19436    returned, indicating that the primary template should be used.  */
19437
19438 static tree
19439 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
19440 {
19441   tree list = NULL_TREE;
19442   tree t;
19443   tree champ;
19444   int fate;
19445   bool ambiguous_p;
19446   tree outer_args = NULL_TREE;
19447   tree tmpl, args;
19448
19449   if (TYPE_P (target))
19450     {
19451       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
19452       tmpl = TI_TEMPLATE (tinfo);
19453       args = TI_ARGS (tinfo);
19454     }
19455   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
19456     {
19457       tmpl = TREE_OPERAND (target, 0);
19458       args = TREE_OPERAND (target, 1);
19459     }
19460   else if (VAR_P (target))
19461     {
19462       tree tinfo = DECL_TEMPLATE_INFO (target);
19463       tmpl = TI_TEMPLATE (tinfo);
19464       args = TI_ARGS (tinfo);
19465     }
19466   else
19467     gcc_unreachable ();
19468
19469   tree main_tmpl = most_general_template (tmpl);
19470
19471   /* For determining which partial specialization to use, only the
19472      innermost args are interesting.  */
19473   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
19474     {
19475       outer_args = strip_innermost_template_args (args, 1);
19476       args = INNERMOST_TEMPLATE_ARGS (args);
19477     }
19478
19479   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
19480     {
19481       tree partial_spec_args;
19482       tree spec_args;
19483       tree spec_tmpl = TREE_VALUE (t);
19484
19485       partial_spec_args = TREE_PURPOSE (t);
19486
19487       ++processing_template_decl;
19488
19489       if (outer_args)
19490         {
19491           /* Discard the outer levels of args, and then substitute in the
19492              template args from the enclosing class.  */
19493           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
19494           partial_spec_args = tsubst_template_args
19495             (partial_spec_args, outer_args, tf_none, NULL_TREE);
19496
19497           /* And the same for the partial specialization TEMPLATE_DECL.  */
19498           spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
19499         }
19500
19501       partial_spec_args =
19502           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
19503                                  partial_spec_args,
19504                                  tmpl, tf_none,
19505                                  /*require_all_args=*/true,
19506                                  /*use_default_args=*/true);
19507
19508       --processing_template_decl;
19509
19510       if (partial_spec_args == error_mark_node)
19511         return error_mark_node;
19512       if (spec_tmpl == error_mark_node)
19513         return error_mark_node;
19514
19515       tree parms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
19516       spec_args = get_partial_spec_bindings (tmpl, parms,
19517                                       partial_spec_args,
19518                                       args);
19519       if (spec_args)
19520         {
19521           if (outer_args)
19522             spec_args = add_to_template_args (outer_args, spec_args);
19523           list = tree_cons (spec_args, TREE_VALUE (t), list);
19524           TREE_TYPE (list) = TREE_TYPE (t);
19525         }
19526     }
19527
19528   if (! list)
19529     return NULL_TREE;
19530
19531   ambiguous_p = false;
19532   t = list;
19533   champ = t;
19534   t = TREE_CHAIN (t);
19535   for (; t; t = TREE_CHAIN (t))
19536     {
19537       fate = more_specialized_partial_spec (tmpl, champ, t);
19538       if (fate == 1)
19539         ;
19540       else
19541         {
19542           if (fate == 0)
19543             {
19544               t = TREE_CHAIN (t);
19545               if (! t)
19546                 {
19547                   ambiguous_p = true;
19548                   break;
19549                 }
19550             }
19551           champ = t;
19552         }
19553     }
19554
19555   if (!ambiguous_p)
19556     for (t = list; t && t != champ; t = TREE_CHAIN (t))
19557       {
19558         fate = more_specialized_partial_spec (tmpl, champ, t);
19559         if (fate != 1)
19560           {
19561             ambiguous_p = true;
19562             break;
19563           }
19564       }
19565
19566   if (ambiguous_p)
19567     {
19568       const char *str;
19569       char *spaces = NULL;
19570       if (!(complain & tf_error))
19571         return error_mark_node;
19572       if (TYPE_P (target))
19573         error ("ambiguous template instantiation for %q#T", target);
19574       else
19575         error ("ambiguous template instantiation for %q#D", target);
19576       str = ngettext ("candidate is:", "candidates are:", list_length (list));
19577       for (t = list; t; t = TREE_CHAIN (t))
19578         {
19579           tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
19580           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
19581                   "%s %#S", spaces ? spaces : str, subst);
19582           spaces = spaces ? spaces : get_spaces (str);
19583         }
19584       free (spaces);
19585       return error_mark_node;
19586     }
19587
19588   return champ;
19589 }
19590
19591 /* Explicitly instantiate DECL.  */
19592
19593 void
19594 do_decl_instantiation (tree decl, tree storage)
19595 {
19596   tree result = NULL_TREE;
19597   int extern_p = 0;
19598
19599   if (!decl || decl == error_mark_node)
19600     /* An error occurred, for which grokdeclarator has already issued
19601        an appropriate message.  */
19602     return;
19603   else if (! DECL_LANG_SPECIFIC (decl))
19604     {
19605       error ("explicit instantiation of non-template %q#D", decl);
19606       return;
19607     }
19608
19609   bool var_templ = (DECL_TEMPLATE_INFO (decl)
19610                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
19611
19612   if (VAR_P (decl) && !var_templ)
19613     {
19614       /* There is an asymmetry here in the way VAR_DECLs and
19615          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
19616          the latter, the DECL we get back will be marked as a
19617          template instantiation, and the appropriate
19618          DECL_TEMPLATE_INFO will be set up.  This does not happen for
19619          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
19620          should handle VAR_DECLs as it currently handles
19621          FUNCTION_DECLs.  */
19622       if (!DECL_CLASS_SCOPE_P (decl))
19623         {
19624           error ("%qD is not a static data member of a class template", decl);
19625           return;
19626         }
19627       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
19628       if (!result || !VAR_P (result))
19629         {
19630           error ("no matching template for %qD found", decl);
19631           return;
19632         }
19633       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
19634         {
19635           error ("type %qT for explicit instantiation %qD does not match "
19636                  "declared type %qT", TREE_TYPE (result), decl,
19637                  TREE_TYPE (decl));
19638           return;
19639         }
19640     }
19641   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
19642     {
19643       error ("explicit instantiation of %q#D", decl);
19644       return;
19645     }
19646   else
19647     result = decl;
19648
19649   /* Check for various error cases.  Note that if the explicit
19650      instantiation is valid the RESULT will currently be marked as an
19651      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
19652      until we get here.  */
19653
19654   if (DECL_TEMPLATE_SPECIALIZATION (result))
19655     {
19656       /* DR 259 [temp.spec].
19657
19658          Both an explicit instantiation and a declaration of an explicit
19659          specialization shall not appear in a program unless the explicit
19660          instantiation follows a declaration of the explicit specialization.
19661
19662          For a given set of template parameters, if an explicit
19663          instantiation of a template appears after a declaration of an
19664          explicit specialization for that template, the explicit
19665          instantiation has no effect.  */
19666       return;
19667     }
19668   else if (DECL_EXPLICIT_INSTANTIATION (result))
19669     {
19670       /* [temp.spec]
19671
19672          No program shall explicitly instantiate any template more
19673          than once.
19674
19675          We check DECL_NOT_REALLY_EXTERN so as not to complain when
19676          the first instantiation was `extern' and the second is not,
19677          and EXTERN_P for the opposite case.  */
19678       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
19679         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
19680       /* If an "extern" explicit instantiation follows an ordinary
19681          explicit instantiation, the template is instantiated.  */
19682       if (extern_p)
19683         return;
19684     }
19685   else if (!DECL_IMPLICIT_INSTANTIATION (result))
19686     {
19687       error ("no matching template for %qD found", result);
19688       return;
19689     }
19690   else if (!DECL_TEMPLATE_INFO (result))
19691     {
19692       permerror (input_location, "explicit instantiation of non-template %q#D", result);
19693       return;
19694     }
19695
19696   if (storage == NULL_TREE)
19697     ;
19698   else if (storage == ridpointers[(int) RID_EXTERN])
19699     {
19700       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
19701         pedwarn (input_location, OPT_Wpedantic, 
19702                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
19703                  "instantiations");
19704       extern_p = 1;
19705     }
19706   else
19707     error ("storage class %qD applied to template instantiation", storage);
19708
19709   check_explicit_instantiation_namespace (result);
19710   mark_decl_instantiated (result, extern_p);
19711   if (! extern_p)
19712     instantiate_decl (result, /*defer_ok=*/1,
19713                       /*expl_inst_class_mem_p=*/false);
19714 }
19715
19716 static void
19717 mark_class_instantiated (tree t, int extern_p)
19718 {
19719   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
19720   SET_CLASSTYPE_INTERFACE_KNOWN (t);
19721   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
19722   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
19723   if (! extern_p)
19724     {
19725       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
19726       rest_of_type_compilation (t, 1);
19727     }
19728 }
19729
19730 /* Called from do_type_instantiation through binding_table_foreach to
19731    do recursive instantiation for the type bound in ENTRY.  */
19732 static void
19733 bt_instantiate_type_proc (binding_entry entry, void *data)
19734 {
19735   tree storage = *(tree *) data;
19736
19737   if (MAYBE_CLASS_TYPE_P (entry->type)
19738       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
19739     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
19740 }
19741
19742 /* Called from do_type_instantiation to instantiate a member
19743    (a member function or a static member variable) of an
19744    explicitly instantiated class template.  */
19745 static void
19746 instantiate_class_member (tree decl, int extern_p)
19747 {
19748   mark_decl_instantiated (decl, extern_p);
19749   if (! extern_p)
19750     instantiate_decl (decl, /*defer_ok=*/1,
19751                       /*expl_inst_class_mem_p=*/true);
19752 }
19753
19754 /* Perform an explicit instantiation of template class T.  STORAGE, if
19755    non-null, is the RID for extern, inline or static.  COMPLAIN is
19756    nonzero if this is called from the parser, zero if called recursively,
19757    since the standard is unclear (as detailed below).  */
19758
19759 void
19760 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
19761 {
19762   int extern_p = 0;
19763   int nomem_p = 0;
19764   int static_p = 0;
19765   int previous_instantiation_extern_p = 0;
19766
19767   if (TREE_CODE (t) == TYPE_DECL)
19768     t = TREE_TYPE (t);
19769
19770   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
19771     {
19772       tree tmpl =
19773         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
19774       if (tmpl)
19775         error ("explicit instantiation of non-class template %qD", tmpl);
19776       else
19777         error ("explicit instantiation of non-template type %qT", t);
19778       return;
19779     }
19780
19781   complete_type (t);
19782
19783   if (!COMPLETE_TYPE_P (t))
19784     {
19785       if (complain & tf_error)
19786         error ("explicit instantiation of %q#T before definition of template",
19787                t);
19788       return;
19789     }
19790
19791   if (storage != NULL_TREE)
19792     {
19793       if (!in_system_header_at (input_location))
19794         {
19795           if (storage == ridpointers[(int) RID_EXTERN])
19796             {
19797               if (cxx_dialect == cxx98)
19798                 pedwarn (input_location, OPT_Wpedantic, 
19799                          "ISO C++ 1998 forbids the use of %<extern%> on "
19800                          "explicit instantiations");
19801             }
19802           else
19803             pedwarn (input_location, OPT_Wpedantic, 
19804                      "ISO C++ forbids the use of %qE"
19805                      " on explicit instantiations", storage);
19806         }
19807
19808       if (storage == ridpointers[(int) RID_INLINE])
19809         nomem_p = 1;
19810       else if (storage == ridpointers[(int) RID_EXTERN])
19811         extern_p = 1;
19812       else if (storage == ridpointers[(int) RID_STATIC])
19813         static_p = 1;
19814       else
19815         {
19816           error ("storage class %qD applied to template instantiation",
19817                  storage);
19818           extern_p = 0;
19819         }
19820     }
19821
19822   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
19823     {
19824       /* DR 259 [temp.spec].
19825
19826          Both an explicit instantiation and a declaration of an explicit
19827          specialization shall not appear in a program unless the explicit
19828          instantiation follows a declaration of the explicit specialization.
19829
19830          For a given set of template parameters, if an explicit
19831          instantiation of a template appears after a declaration of an
19832          explicit specialization for that template, the explicit
19833          instantiation has no effect.  */
19834       return;
19835     }
19836   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
19837     {
19838       /* [temp.spec]
19839
19840          No program shall explicitly instantiate any template more
19841          than once.
19842
19843          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
19844          instantiation was `extern'.  If EXTERN_P then the second is.
19845          These cases are OK.  */
19846       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
19847
19848       if (!previous_instantiation_extern_p && !extern_p
19849           && (complain & tf_error))
19850         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
19851
19852       /* If we've already instantiated the template, just return now.  */
19853       if (!CLASSTYPE_INTERFACE_ONLY (t))
19854         return;
19855     }
19856
19857   check_explicit_instantiation_namespace (TYPE_NAME (t));
19858   mark_class_instantiated (t, extern_p);
19859
19860   if (nomem_p)
19861     return;
19862
19863   {
19864     tree tmp;
19865
19866     /* In contrast to implicit instantiation, where only the
19867        declarations, and not the definitions, of members are
19868        instantiated, we have here:
19869
19870          [temp.explicit]
19871
19872          The explicit instantiation of a class template specialization
19873          implies the instantiation of all of its members not
19874          previously explicitly specialized in the translation unit
19875          containing the explicit instantiation.
19876
19877        Of course, we can't instantiate member template classes, since
19878        we don't have any arguments for them.  Note that the standard
19879        is unclear on whether the instantiation of the members are
19880        *explicit* instantiations or not.  However, the most natural
19881        interpretation is that it should be an explicit instantiation.  */
19882
19883     if (! static_p)
19884       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
19885         if (TREE_CODE (tmp) == FUNCTION_DECL
19886             && DECL_TEMPLATE_INSTANTIATION (tmp))
19887           instantiate_class_member (tmp, extern_p);
19888
19889     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
19890       if (VAR_P (tmp) && DECL_TEMPLATE_INSTANTIATION (tmp))
19891         instantiate_class_member (tmp, extern_p);
19892
19893     if (CLASSTYPE_NESTED_UTDS (t))
19894       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
19895                              bt_instantiate_type_proc, &storage);
19896   }
19897 }
19898
19899 /* Given a function DECL, which is a specialization of TMPL, modify
19900    DECL to be a re-instantiation of TMPL with the same template
19901    arguments.  TMPL should be the template into which tsubst'ing
19902    should occur for DECL, not the most general template.
19903
19904    One reason for doing this is a scenario like this:
19905
19906      template <class T>
19907      void f(const T&, int i);
19908
19909      void g() { f(3, 7); }
19910
19911      template <class T>
19912      void f(const T& t, const int i) { }
19913
19914    Note that when the template is first instantiated, with
19915    instantiate_template, the resulting DECL will have no name for the
19916    first parameter, and the wrong type for the second.  So, when we go
19917    to instantiate the DECL, we regenerate it.  */
19918
19919 static void
19920 regenerate_decl_from_template (tree decl, tree tmpl)
19921 {
19922   /* The arguments used to instantiate DECL, from the most general
19923      template.  */
19924   tree args;
19925   tree code_pattern;
19926
19927   args = DECL_TI_ARGS (decl);
19928   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
19929
19930   /* Make sure that we can see identifiers, and compute access
19931      correctly.  */
19932   push_access_scope (decl);
19933
19934   if (TREE_CODE (decl) == FUNCTION_DECL)
19935     {
19936       tree decl_parm;
19937       tree pattern_parm;
19938       tree specs;
19939       int args_depth;
19940       int parms_depth;
19941
19942       args_depth = TMPL_ARGS_DEPTH (args);
19943       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
19944       if (args_depth > parms_depth)
19945         args = get_innermost_template_args (args, parms_depth);
19946
19947       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
19948                                               args, tf_error, NULL_TREE,
19949                                               /*defer_ok*/false);
19950       if (specs && specs != error_mark_node)
19951         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
19952                                                     specs);
19953
19954       /* Merge parameter declarations.  */
19955       decl_parm = skip_artificial_parms_for (decl,
19956                                              DECL_ARGUMENTS (decl));
19957       pattern_parm
19958         = skip_artificial_parms_for (code_pattern,
19959                                      DECL_ARGUMENTS (code_pattern));
19960       while (decl_parm && !DECL_PACK_P (pattern_parm))
19961         {
19962           tree parm_type;
19963           tree attributes;
19964           
19965           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
19966             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
19967           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
19968                               NULL_TREE);
19969           parm_type = type_decays_to (parm_type);
19970           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
19971             TREE_TYPE (decl_parm) = parm_type;
19972           attributes = DECL_ATTRIBUTES (pattern_parm);
19973           if (DECL_ATTRIBUTES (decl_parm) != attributes)
19974             {
19975               DECL_ATTRIBUTES (decl_parm) = attributes;
19976               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
19977             }
19978           decl_parm = DECL_CHAIN (decl_parm);
19979           pattern_parm = DECL_CHAIN (pattern_parm);
19980         }
19981       /* Merge any parameters that match with the function parameter
19982          pack.  */
19983       if (pattern_parm && DECL_PACK_P (pattern_parm))
19984         {
19985           int i, len;
19986           tree expanded_types;
19987           /* Expand the TYPE_PACK_EXPANSION that provides the types for
19988              the parameters in this function parameter pack.  */
19989           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
19990                                                  args, tf_error, NULL_TREE);
19991           len = TREE_VEC_LENGTH (expanded_types);
19992           for (i = 0; i < len; i++)
19993             {
19994               tree parm_type;
19995               tree attributes;
19996           
19997               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
19998                 /* Rename the parameter to include the index.  */
19999                 DECL_NAME (decl_parm) = 
20000                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
20001               parm_type = TREE_VEC_ELT (expanded_types, i);
20002               parm_type = type_decays_to (parm_type);
20003               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
20004                 TREE_TYPE (decl_parm) = parm_type;
20005               attributes = DECL_ATTRIBUTES (pattern_parm);
20006               if (DECL_ATTRIBUTES (decl_parm) != attributes)
20007                 {
20008                   DECL_ATTRIBUTES (decl_parm) = attributes;
20009                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
20010                 }
20011               decl_parm = DECL_CHAIN (decl_parm);
20012             }
20013         }
20014       /* Merge additional specifiers from the CODE_PATTERN.  */
20015       if (DECL_DECLARED_INLINE_P (code_pattern)
20016           && !DECL_DECLARED_INLINE_P (decl))
20017         DECL_DECLARED_INLINE_P (decl) = 1;
20018     }
20019   else if (VAR_P (decl))
20020     {
20021       DECL_INITIAL (decl) =
20022         tsubst_expr (DECL_INITIAL (code_pattern), args,
20023                      tf_error, DECL_TI_TEMPLATE (decl),
20024                      /*integral_constant_expression_p=*/false);
20025       if (VAR_HAD_UNKNOWN_BOUND (decl))
20026         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
20027                                    tf_error, DECL_TI_TEMPLATE (decl));
20028     }
20029   else
20030     gcc_unreachable ();
20031
20032   pop_access_scope (decl);
20033 }
20034
20035 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
20036    substituted to get DECL.  */
20037
20038 tree
20039 template_for_substitution (tree decl)
20040 {
20041   tree tmpl = DECL_TI_TEMPLATE (decl);
20042
20043   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
20044      for the instantiation.  This is not always the most general
20045      template.  Consider, for example:
20046
20047         template <class T>
20048         struct S { template <class U> void f();
20049                    template <> void f<int>(); };
20050
20051      and an instantiation of S<double>::f<int>.  We want TD to be the
20052      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
20053   while (/* An instantiation cannot have a definition, so we need a
20054             more general template.  */
20055          DECL_TEMPLATE_INSTANTIATION (tmpl)
20056            /* We must also deal with friend templates.  Given:
20057
20058                 template <class T> struct S {
20059                   template <class U> friend void f() {};
20060                 };
20061
20062               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
20063               so far as the language is concerned, but that's still
20064               where we get the pattern for the instantiation from.  On
20065               other hand, if the definition comes outside the class, say:
20066
20067                 template <class T> struct S {
20068                   template <class U> friend void f();
20069                 };
20070                 template <class U> friend void f() {}
20071
20072               we don't need to look any further.  That's what the check for
20073               DECL_INITIAL is for.  */
20074           || (TREE_CODE (decl) == FUNCTION_DECL
20075               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
20076               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
20077     {
20078       /* The present template, TD, should not be a definition.  If it
20079          were a definition, we should be using it!  Note that we
20080          cannot restructure the loop to just keep going until we find
20081          a template with a definition, since that might go too far if
20082          a specialization was declared, but not defined.  */
20083
20084       /* Fetch the more general template.  */
20085       tmpl = DECL_TI_TEMPLATE (tmpl);
20086     }
20087
20088   return tmpl;
20089 }
20090
20091 /* Returns true if we need to instantiate this template instance even if we
20092    know we aren't going to emit it..  */
20093
20094 bool
20095 always_instantiate_p (tree decl)
20096 {
20097   /* We always instantiate inline functions so that we can inline them.  An
20098      explicit instantiation declaration prohibits implicit instantiation of
20099      non-inline functions.  With high levels of optimization, we would
20100      normally inline non-inline functions -- but we're not allowed to do
20101      that for "extern template" functions.  Therefore, we check
20102      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
20103   return ((TREE_CODE (decl) == FUNCTION_DECL
20104            && (DECL_DECLARED_INLINE_P (decl)
20105                || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
20106           /* And we need to instantiate static data members so that
20107              their initializers are available in integral constant
20108              expressions.  */
20109           || (VAR_P (decl)
20110               && decl_maybe_constant_var_p (decl)));
20111 }
20112
20113 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
20114    instantiate it now, modifying TREE_TYPE (fn).  */
20115
20116 void
20117 maybe_instantiate_noexcept (tree fn)
20118 {
20119   tree fntype, spec, noex, clone;
20120
20121   /* Don't instantiate a noexcept-specification from template context.  */
20122   if (processing_template_decl)
20123     return;
20124
20125   if (DECL_CLONED_FUNCTION_P (fn))
20126     fn = DECL_CLONED_FUNCTION (fn);
20127   fntype = TREE_TYPE (fn);
20128   spec = TYPE_RAISES_EXCEPTIONS (fntype);
20129
20130   if (!spec || !TREE_PURPOSE (spec))
20131     return;
20132
20133   noex = TREE_PURPOSE (spec);
20134
20135   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
20136     {
20137       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
20138         spec = get_defaulted_eh_spec (fn);
20139       else if (push_tinst_level (fn))
20140         {
20141           push_access_scope (fn);
20142           push_deferring_access_checks (dk_no_deferred);
20143           input_location = DECL_SOURCE_LOCATION (fn);
20144           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
20145                                         DEFERRED_NOEXCEPT_ARGS (noex),
20146                                         tf_warning_or_error, fn,
20147                                         /*function_p=*/false,
20148                                         /*integral_constant_expression_p=*/true);
20149           pop_deferring_access_checks ();
20150           pop_access_scope (fn);
20151           pop_tinst_level ();
20152           spec = build_noexcept_spec (noex, tf_warning_or_error);
20153           if (spec == error_mark_node)
20154             spec = noexcept_false_spec;
20155         }
20156       else
20157         spec = noexcept_false_spec;
20158
20159       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
20160     }
20161
20162   FOR_EACH_CLONE (clone, fn)
20163     {
20164       if (TREE_TYPE (clone) == fntype)
20165         TREE_TYPE (clone) = TREE_TYPE (fn);
20166       else
20167         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
20168     }
20169 }
20170
20171 /* Produce the definition of D, a _DECL generated from a template.  If
20172    DEFER_OK is nonzero, then we don't have to actually do the
20173    instantiation now; we just have to do it sometime.  Normally it is
20174    an error if this is an explicit instantiation but D is undefined.
20175    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
20176    explicitly instantiated class template.  */
20177
20178 tree
20179 instantiate_decl (tree d, int defer_ok,
20180                   bool expl_inst_class_mem_p)
20181 {
20182   tree tmpl = DECL_TI_TEMPLATE (d);
20183   tree gen_args;
20184   tree args;
20185   tree td;
20186   tree code_pattern;
20187   tree spec;
20188   tree gen_tmpl;
20189   bool pattern_defined;
20190   location_t saved_loc = input_location;
20191   int saved_unevaluated_operand = cp_unevaluated_operand;
20192   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
20193   bool external_p;
20194   bool deleted_p;
20195   tree fn_context;
20196   bool nested;
20197
20198   /* This function should only be used to instantiate templates for
20199      functions and static member variables.  */
20200   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
20201
20202   /* Variables are never deferred; if instantiation is required, they
20203      are instantiated right away.  That allows for better code in the
20204      case that an expression refers to the value of the variable --
20205      if the variable has a constant value the referring expression can
20206      take advantage of that fact.  */
20207   if (VAR_P (d)
20208       || DECL_DECLARED_CONSTEXPR_P (d))
20209     defer_ok = 0;
20210
20211   /* Don't instantiate cloned functions.  Instead, instantiate the
20212      functions they cloned.  */
20213   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
20214     d = DECL_CLONED_FUNCTION (d);
20215
20216   if (DECL_TEMPLATE_INSTANTIATED (d)
20217       || (TREE_CODE (d) == FUNCTION_DECL
20218           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
20219       || DECL_TEMPLATE_SPECIALIZATION (d))
20220     /* D has already been instantiated or explicitly specialized, so
20221        there's nothing for us to do here.
20222
20223        It might seem reasonable to check whether or not D is an explicit
20224        instantiation, and, if so, stop here.  But when an explicit
20225        instantiation is deferred until the end of the compilation,
20226        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
20227        the instantiation.  */
20228     return d;
20229
20230   /* Check to see whether we know that this template will be
20231      instantiated in some other file, as with "extern template"
20232      extension.  */
20233   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
20234
20235   /* In general, we do not instantiate such templates.  */
20236   if (external_p && !always_instantiate_p (d))
20237     return d;
20238
20239   gen_tmpl = most_general_template (tmpl);
20240   gen_args = DECL_TI_ARGS (d);
20241
20242   if (tmpl != gen_tmpl)
20243     /* We should already have the extra args.  */
20244     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
20245                 == TMPL_ARGS_DEPTH (gen_args));
20246   /* And what's in the hash table should match D.  */
20247   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
20248               || spec == NULL_TREE);
20249
20250   /* This needs to happen before any tsubsting.  */
20251   if (! push_tinst_level (d))
20252     return d;
20253
20254   timevar_push (TV_TEMPLATE_INST);
20255
20256   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
20257      for the instantiation.  */
20258   td = template_for_substitution (d);
20259   code_pattern = DECL_TEMPLATE_RESULT (td);
20260
20261   /* We should never be trying to instantiate a member of a class
20262      template or partial specialization.  */
20263   gcc_assert (d != code_pattern);
20264
20265   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
20266       || DECL_TEMPLATE_SPECIALIZATION (td))
20267     /* In the case of a friend template whose definition is provided
20268        outside the class, we may have too many arguments.  Drop the
20269        ones we don't need.  The same is true for specializations.  */
20270     args = get_innermost_template_args
20271       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
20272   else
20273     args = gen_args;
20274
20275   if (TREE_CODE (d) == FUNCTION_DECL)
20276     {
20277       deleted_p = DECL_DELETED_FN (code_pattern);
20278       pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
20279                          || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
20280                          || deleted_p);
20281     }
20282   else
20283     {
20284       deleted_p = false;
20285       pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
20286     }
20287
20288   /* We may be in the middle of deferred access check.  Disable it now.  */
20289   push_deferring_access_checks (dk_no_deferred);
20290
20291   /* Unless an explicit instantiation directive has already determined
20292      the linkage of D, remember that a definition is available for
20293      this entity.  */
20294   if (pattern_defined
20295       && !DECL_INTERFACE_KNOWN (d)
20296       && !DECL_NOT_REALLY_EXTERN (d))
20297     mark_definable (d);
20298
20299   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
20300   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
20301   input_location = DECL_SOURCE_LOCATION (d);
20302
20303   /* If D is a member of an explicitly instantiated class template,
20304      and no definition is available, treat it like an implicit
20305      instantiation.  */
20306   if (!pattern_defined && expl_inst_class_mem_p
20307       && DECL_EXPLICIT_INSTANTIATION (d))
20308     {
20309       /* Leave linkage flags alone on instantiations with anonymous
20310          visibility.  */
20311       if (TREE_PUBLIC (d))
20312         {
20313           DECL_NOT_REALLY_EXTERN (d) = 0;
20314           DECL_INTERFACE_KNOWN (d) = 0;
20315         }
20316       SET_DECL_IMPLICIT_INSTANTIATION (d);
20317     }
20318
20319   /* Defer all other templates, unless we have been explicitly
20320      forbidden from doing so.  */
20321   if (/* If there is no definition, we cannot instantiate the
20322          template.  */
20323       ! pattern_defined
20324       /* If it's OK to postpone instantiation, do so.  */
20325       || defer_ok
20326       /* If this is a static data member that will be defined
20327          elsewhere, we don't want to instantiate the entire data
20328          member, but we do want to instantiate the initializer so that
20329          we can substitute that elsewhere.  */
20330       || (external_p && VAR_P (d))
20331       /* Handle here a deleted function too, avoid generating
20332          its body (c++/61080).  */
20333       || deleted_p)
20334     {
20335       /* The definition of the static data member is now required so
20336          we must substitute the initializer.  */
20337       if (VAR_P (d)
20338           && !DECL_INITIAL (d)
20339           && DECL_INITIAL (code_pattern))
20340         {
20341           tree ns;
20342           tree init;
20343           bool const_init = false;
20344           bool enter_context = DECL_CLASS_SCOPE_P (d);
20345
20346           ns = decl_namespace_context (d);
20347           push_nested_namespace (ns);
20348           if (enter_context)
20349             push_nested_class (DECL_CONTEXT (d));
20350           init = tsubst_expr (DECL_INITIAL (code_pattern),
20351                               args,
20352                               tf_warning_or_error, NULL_TREE,
20353                               /*integral_constant_expression_p=*/false);
20354           /* If instantiating the initializer involved instantiating this
20355              again, don't call cp_finish_decl twice.  */
20356           if (!DECL_INITIAL (d))
20357             {
20358               /* Make sure the initializer is still constant, in case of
20359                  circular dependency (template/instantiate6.C). */
20360               const_init
20361                 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
20362               cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
20363                               /*asmspec_tree=*/NULL_TREE,
20364                               LOOKUP_ONLYCONVERTING);
20365             }
20366           if (enter_context)
20367             pop_nested_class ();
20368           pop_nested_namespace (ns);
20369         }
20370
20371       /* We restore the source position here because it's used by
20372          add_pending_template.  */
20373       input_location = saved_loc;
20374
20375       if (at_eof && !pattern_defined
20376           && DECL_EXPLICIT_INSTANTIATION (d)
20377           && DECL_NOT_REALLY_EXTERN (d))
20378         /* [temp.explicit]
20379
20380            The definition of a non-exported function template, a
20381            non-exported member function template, or a non-exported
20382            member function or static data member of a class template
20383            shall be present in every translation unit in which it is
20384            explicitly instantiated.  */
20385         permerror (input_location,  "explicit instantiation of %qD "
20386                    "but no definition available", d);
20387
20388       /* If we're in unevaluated context, we just wanted to get the
20389          constant value; this isn't an odr use, so don't queue
20390          a full instantiation.  */
20391       if (cp_unevaluated_operand != 0)
20392         goto out;
20393       /* ??? Historically, we have instantiated inline functions, even
20394          when marked as "extern template".  */
20395       if (!(external_p && VAR_P (d)))
20396         add_pending_template (d);
20397       goto out;
20398     }
20399   /* Tell the repository that D is available in this translation unit
20400      -- and see if it is supposed to be instantiated here.  */
20401   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
20402     {
20403       /* In a PCH file, despite the fact that the repository hasn't
20404          requested instantiation in the PCH it is still possible that
20405          an instantiation will be required in a file that includes the
20406          PCH.  */
20407       if (pch_file)
20408         add_pending_template (d);
20409       /* Instantiate inline functions so that the inliner can do its
20410          job, even though we'll not be emitting a copy of this
20411          function.  */
20412       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
20413         goto out;
20414     }
20415
20416   fn_context = decl_function_context (d);
20417   nested = (current_function_decl != NULL_TREE);
20418   if (!fn_context)
20419     push_to_top_level ();
20420   else
20421     {
20422       if (nested)
20423         push_function_context ();
20424       cp_unevaluated_operand = 0;
20425       c_inhibit_evaluation_warnings = 0;
20426     }
20427
20428   /* Mark D as instantiated so that recursive calls to
20429      instantiate_decl do not try to instantiate it again.  */
20430   DECL_TEMPLATE_INSTANTIATED (d) = 1;
20431
20432   /* Regenerate the declaration in case the template has been modified
20433      by a subsequent redeclaration.  */
20434   regenerate_decl_from_template (d, td);
20435
20436   /* We already set the file and line above.  Reset them now in case
20437      they changed as a result of calling regenerate_decl_from_template.  */
20438   input_location = DECL_SOURCE_LOCATION (d);
20439
20440   if (VAR_P (d))
20441     {
20442       tree init;
20443       bool const_init = false;
20444
20445       /* Clear out DECL_RTL; whatever was there before may not be right
20446          since we've reset the type of the declaration.  */
20447       SET_DECL_RTL (d, NULL);
20448       DECL_IN_AGGR_P (d) = 0;
20449
20450       /* The initializer is placed in DECL_INITIAL by
20451          regenerate_decl_from_template so we don't need to
20452          push/pop_access_scope again here.  Pull it out so that
20453          cp_finish_decl can process it.  */
20454       init = DECL_INITIAL (d);
20455       DECL_INITIAL (d) = NULL_TREE;
20456       DECL_INITIALIZED_P (d) = 0;
20457
20458       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
20459          initializer.  That function will defer actual emission until
20460          we have a chance to determine linkage.  */
20461       DECL_EXTERNAL (d) = 0;
20462
20463       /* Enter the scope of D so that access-checking works correctly.  */
20464       bool enter_context = DECL_CLASS_SCOPE_P (d);
20465       if (enter_context)
20466         push_nested_class (DECL_CONTEXT (d));
20467
20468       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
20469       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
20470
20471       if (enter_context)
20472         pop_nested_class ();
20473
20474       if (variable_template_p (td))
20475         note_variable_template_instantiation (d);
20476     }
20477   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
20478     synthesize_method (d);
20479   else if (TREE_CODE (d) == FUNCTION_DECL)
20480     {
20481       hash_map<tree, tree> *saved_local_specializations;
20482       tree subst_decl;
20483       tree tmpl_parm;
20484       tree spec_parm;
20485       tree block = NULL_TREE;
20486
20487       /* Save away the current list, in case we are instantiating one
20488          template from within the body of another.  */
20489       saved_local_specializations = local_specializations;
20490
20491       /* Set up the list of local specializations.  */
20492       local_specializations = new hash_map<tree, tree>;
20493
20494       /* Set up context.  */
20495       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
20496           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
20497         block = push_stmt_list ();
20498       else
20499         start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
20500
20501       /* Some typedefs referenced from within the template code need to be
20502          access checked at template instantiation time, i.e now. These
20503          types were added to the template at parsing time. Let's get those
20504          and perform the access checks then.  */
20505       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (gen_tmpl),
20506                                      gen_args);
20507
20508       /* Create substitution entries for the parameters.  */
20509       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
20510       tmpl_parm = DECL_ARGUMENTS (subst_decl);
20511       spec_parm = DECL_ARGUMENTS (d);
20512       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
20513         {
20514           register_local_specialization (spec_parm, tmpl_parm);
20515           spec_parm = skip_artificial_parms_for (d, spec_parm);
20516           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
20517         }
20518       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
20519         {
20520           if (!DECL_PACK_P (tmpl_parm))
20521             {
20522               register_local_specialization (spec_parm, tmpl_parm);
20523               spec_parm = DECL_CHAIN (spec_parm);
20524             }
20525           else
20526             {
20527               /* Register the (value) argument pack as a specialization of
20528                  TMPL_PARM, then move on.  */
20529               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
20530               register_local_specialization (argpack, tmpl_parm);
20531             }
20532         }
20533       gcc_assert (!spec_parm);
20534
20535       /* Substitute into the body of the function.  */
20536       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
20537         tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
20538                         tf_warning_or_error, tmpl);
20539       else
20540         {
20541           tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
20542                        tf_warning_or_error, tmpl,
20543                        /*integral_constant_expression_p=*/false);
20544
20545           /* Set the current input_location to the end of the function
20546              so that finish_function knows where we are.  */
20547           input_location
20548             = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
20549
20550           /* Remember if we saw an infinite loop in the template.  */
20551           current_function_infinite_loop
20552             = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
20553         }
20554
20555       /* We don't need the local specializations any more.  */
20556       delete local_specializations;
20557       local_specializations = saved_local_specializations;
20558
20559       /* Finish the function.  */
20560       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
20561           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
20562         DECL_SAVED_TREE (d) = pop_stmt_list (block);
20563       else
20564         {
20565           d = finish_function (0);
20566           expand_or_defer_fn (d);
20567         }
20568
20569       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
20570         cp_check_omp_declare_reduction (d);
20571     }
20572
20573   /* We're not deferring instantiation any more.  */
20574   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
20575
20576   if (!fn_context)
20577     pop_from_top_level ();
20578   else if (nested)
20579     pop_function_context ();
20580
20581 out:
20582   input_location = saved_loc;
20583   cp_unevaluated_operand = saved_unevaluated_operand;
20584   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
20585   pop_deferring_access_checks ();
20586   pop_tinst_level ();
20587
20588   timevar_pop (TV_TEMPLATE_INST);
20589
20590   return d;
20591 }
20592
20593 /* Run through the list of templates that we wish we could
20594    instantiate, and instantiate any we can.  RETRIES is the
20595    number of times we retry pending template instantiation.  */
20596
20597 void
20598 instantiate_pending_templates (int retries)
20599 {
20600   int reconsider;
20601   location_t saved_loc = input_location;
20602
20603   /* Instantiating templates may trigger vtable generation.  This in turn
20604      may require further template instantiations.  We place a limit here
20605      to avoid infinite loop.  */
20606   if (pending_templates && retries >= max_tinst_depth)
20607     {
20608       tree decl = pending_templates->tinst->decl;
20609
20610       fatal_error (input_location,
20611                    "template instantiation depth exceeds maximum of %d"
20612                    " instantiating %q+D, possibly from virtual table generation"
20613                    " (use -ftemplate-depth= to increase the maximum)",
20614                    max_tinst_depth, decl);
20615       if (TREE_CODE (decl) == FUNCTION_DECL)
20616         /* Pretend that we defined it.  */
20617         DECL_INITIAL (decl) = error_mark_node;
20618       return;
20619     }
20620
20621   do
20622     {
20623       struct pending_template **t = &pending_templates;
20624       struct pending_template *last = NULL;
20625       reconsider = 0;
20626       while (*t)
20627         {
20628           tree instantiation = reopen_tinst_level ((*t)->tinst);
20629           bool complete = false;
20630
20631           if (TYPE_P (instantiation))
20632             {
20633               tree fn;
20634
20635               if (!COMPLETE_TYPE_P (instantiation))
20636                 {
20637                   instantiate_class_template (instantiation);
20638                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
20639                     for (fn = TYPE_METHODS (instantiation);
20640                          fn;
20641                          fn = TREE_CHAIN (fn))
20642                       if (! DECL_ARTIFICIAL (fn))
20643                         instantiate_decl (fn,
20644                                           /*defer_ok=*/0,
20645                                           /*expl_inst_class_mem_p=*/false);
20646                   if (COMPLETE_TYPE_P (instantiation))
20647                     reconsider = 1;
20648                 }
20649
20650               complete = COMPLETE_TYPE_P (instantiation);
20651             }
20652           else
20653             {
20654               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
20655                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
20656                 {
20657                   instantiation
20658                     = instantiate_decl (instantiation,
20659                                         /*defer_ok=*/0,
20660                                         /*expl_inst_class_mem_p=*/false);
20661                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
20662                     reconsider = 1;
20663                 }
20664
20665               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
20666                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
20667             }
20668
20669           if (complete)
20670             /* If INSTANTIATION has been instantiated, then we don't
20671                need to consider it again in the future.  */
20672             *t = (*t)->next;
20673           else
20674             {
20675               last = *t;
20676               t = &(*t)->next;
20677             }
20678           tinst_depth = 0;
20679           current_tinst_level = NULL;
20680         }
20681       last_pending_template = last;
20682     }
20683   while (reconsider);
20684
20685   input_location = saved_loc;
20686 }
20687
20688 /* Substitute ARGVEC into T, which is a list of initializers for
20689    either base class or a non-static data member.  The TREE_PURPOSEs
20690    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
20691    instantiate_decl.  */
20692
20693 static tree
20694 tsubst_initializer_list (tree t, tree argvec)
20695 {
20696   tree inits = NULL_TREE;
20697
20698   for (; t; t = TREE_CHAIN (t))
20699     {
20700       tree decl;
20701       tree init;
20702       tree expanded_bases = NULL_TREE;
20703       tree expanded_arguments = NULL_TREE;
20704       int i, len = 1;
20705
20706       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
20707         {
20708           tree expr;
20709           tree arg;
20710
20711           /* Expand the base class expansion type into separate base
20712              classes.  */
20713           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
20714                                                  tf_warning_or_error,
20715                                                  NULL_TREE);
20716           if (expanded_bases == error_mark_node)
20717             continue;
20718           
20719           /* We'll be building separate TREE_LISTs of arguments for
20720              each base.  */
20721           len = TREE_VEC_LENGTH (expanded_bases);
20722           expanded_arguments = make_tree_vec (len);
20723           for (i = 0; i < len; i++)
20724             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
20725
20726           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
20727              expand each argument in the TREE_VALUE of t.  */
20728           expr = make_node (EXPR_PACK_EXPANSION);
20729           PACK_EXPANSION_LOCAL_P (expr) = true;
20730           PACK_EXPANSION_PARAMETER_PACKS (expr) =
20731             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
20732
20733           if (TREE_VALUE (t) == void_type_node)
20734             /* VOID_TYPE_NODE is used to indicate
20735                value-initialization.  */
20736             {
20737               for (i = 0; i < len; i++)
20738                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
20739             }
20740           else
20741             {
20742               /* Substitute parameter packs into each argument in the
20743                  TREE_LIST.  */
20744               in_base_initializer = 1;
20745               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
20746                 {
20747                   tree expanded_exprs;
20748
20749                   /* Expand the argument.  */
20750                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
20751                   expanded_exprs 
20752                     = tsubst_pack_expansion (expr, argvec,
20753                                              tf_warning_or_error,
20754                                              NULL_TREE);
20755                   if (expanded_exprs == error_mark_node)
20756                     continue;
20757
20758                   /* Prepend each of the expanded expressions to the
20759                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
20760                   for (i = 0; i < len; i++)
20761                     {
20762                       TREE_VEC_ELT (expanded_arguments, i) = 
20763                         tree_cons (NULL_TREE, 
20764                                    TREE_VEC_ELT (expanded_exprs, i),
20765                                    TREE_VEC_ELT (expanded_arguments, i));
20766                     }
20767                 }
20768               in_base_initializer = 0;
20769
20770               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
20771                  since we built them backwards.  */
20772               for (i = 0; i < len; i++)
20773                 {
20774                   TREE_VEC_ELT (expanded_arguments, i) = 
20775                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
20776                 }
20777             }
20778         }
20779
20780       for (i = 0; i < len; ++i)
20781         {
20782           if (expanded_bases)
20783             {
20784               decl = TREE_VEC_ELT (expanded_bases, i);
20785               decl = expand_member_init (decl);
20786               init = TREE_VEC_ELT (expanded_arguments, i);
20787             }
20788           else
20789             {
20790               tree tmp;
20791               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
20792                                   tf_warning_or_error, NULL_TREE);
20793
20794               decl = expand_member_init (decl);
20795               if (decl && !DECL_P (decl))
20796                 in_base_initializer = 1;
20797
20798               init = TREE_VALUE (t);
20799               tmp = init;
20800               if (init != void_type_node)
20801                 init = tsubst_expr (init, argvec,
20802                                     tf_warning_or_error, NULL_TREE,
20803                                     /*integral_constant_expression_p=*/false);
20804               if (init == NULL_TREE && tmp != NULL_TREE)
20805                 /* If we had an initializer but it instantiated to nothing,
20806                    value-initialize the object.  This will only occur when
20807                    the initializer was a pack expansion where the parameter
20808                    packs used in that expansion were of length zero.  */
20809                 init = void_type_node;
20810               in_base_initializer = 0;
20811             }
20812
20813           if (decl)
20814             {
20815               init = build_tree_list (decl, init);
20816               TREE_CHAIN (init) = inits;
20817               inits = init;
20818             }
20819         }
20820     }
20821   return inits;
20822 }
20823
20824 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
20825
20826 static void
20827 set_current_access_from_decl (tree decl)
20828 {
20829   if (TREE_PRIVATE (decl))
20830     current_access_specifier = access_private_node;
20831   else if (TREE_PROTECTED (decl))
20832     current_access_specifier = access_protected_node;
20833   else
20834     current_access_specifier = access_public_node;
20835 }
20836
20837 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
20838    is the instantiation (which should have been created with
20839    start_enum) and ARGS are the template arguments to use.  */
20840
20841 static void
20842 tsubst_enum (tree tag, tree newtag, tree args)
20843 {
20844   tree e;
20845
20846   if (SCOPED_ENUM_P (newtag))
20847     begin_scope (sk_scoped_enum, newtag);
20848
20849   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
20850     {
20851       tree value;
20852       tree decl;
20853
20854       decl = TREE_VALUE (e);
20855       /* Note that in a template enum, the TREE_VALUE is the
20856          CONST_DECL, not the corresponding INTEGER_CST.  */
20857       value = tsubst_expr (DECL_INITIAL (decl),
20858                            args, tf_warning_or_error, NULL_TREE,
20859                            /*integral_constant_expression_p=*/true);
20860
20861       /* Give this enumeration constant the correct access.  */
20862       set_current_access_from_decl (decl);
20863
20864       /* Actually build the enumerator itself.  */
20865       build_enumerator
20866         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
20867     }
20868
20869   if (SCOPED_ENUM_P (newtag))
20870     finish_scope ();
20871
20872   finish_enum_value_list (newtag);
20873   finish_enum (newtag);
20874
20875   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
20876     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
20877 }
20878
20879 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
20880    its type -- but without substituting the innermost set of template
20881    arguments.  So, innermost set of template parameters will appear in
20882    the type.  */
20883
20884 tree
20885 get_mostly_instantiated_function_type (tree decl)
20886 {
20887   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
20888   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
20889 }
20890
20891 /* Return truthvalue if we're processing a template different from
20892    the last one involved in diagnostics.  */
20893 bool
20894 problematic_instantiation_changed (void)
20895 {
20896   return current_tinst_level != last_error_tinst_level;
20897 }
20898
20899 /* Remember current template involved in diagnostics.  */
20900 void
20901 record_last_problematic_instantiation (void)
20902 {
20903   last_error_tinst_level = current_tinst_level;
20904 }
20905
20906 struct tinst_level *
20907 current_instantiation (void)
20908 {
20909   return current_tinst_level;
20910 }
20911
20912 /* Return TRUE if current_function_decl is being instantiated, false
20913    otherwise.  */
20914
20915 bool
20916 instantiating_current_function_p (void)
20917 {
20918   return (current_instantiation ()
20919           && current_instantiation ()->decl == current_function_decl);
20920 }
20921
20922 /* [temp.param] Check that template non-type parm TYPE is of an allowable
20923    type. Return zero for ok, nonzero for disallowed. Issue error and
20924    warning messages under control of COMPLAIN.  */
20925
20926 static int
20927 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
20928 {
20929   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
20930     return 0;
20931   else if (POINTER_TYPE_P (type))
20932     return 0;
20933   else if (TYPE_PTRMEM_P (type))
20934     return 0;
20935   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
20936     return 0;
20937   else if (TREE_CODE (type) == TYPENAME_TYPE)
20938     return 0;
20939   else if (TREE_CODE (type) == DECLTYPE_TYPE)
20940     return 0;
20941   else if (TREE_CODE (type) == NULLPTR_TYPE)
20942     return 0;
20943
20944   if (complain & tf_error)
20945     {
20946       if (type == error_mark_node)
20947         inform (input_location, "invalid template non-type parameter");
20948       else
20949         error ("%q#T is not a valid type for a template non-type parameter",
20950                type);
20951     }
20952   return 1;
20953 }
20954
20955 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
20956    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
20957
20958 static bool
20959 dependent_type_p_r (tree type)
20960 {
20961   tree scope;
20962
20963   /* [temp.dep.type]
20964
20965      A type is dependent if it is:
20966
20967      -- a template parameter. Template template parameters are types
20968         for us (since TYPE_P holds true for them) so we handle
20969         them here.  */
20970   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20971       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
20972     return true;
20973   /* -- a qualified-id with a nested-name-specifier which contains a
20974         class-name that names a dependent type or whose unqualified-id
20975         names a dependent type.  */
20976   if (TREE_CODE (type) == TYPENAME_TYPE)
20977     return true;
20978
20979   /* An alias template specialization can be dependent even if the
20980      resulting type is not.  */
20981   if (dependent_alias_template_spec_p (type))
20982     return true;
20983
20984   /* -- a cv-qualified type where the cv-unqualified type is
20985         dependent.
20986      No code is necessary for this bullet; the code below handles
20987      cv-qualified types, and we don't want to strip aliases with
20988      TYPE_MAIN_VARIANT because of DR 1558.  */
20989   /* -- a compound type constructed from any dependent type.  */
20990   if (TYPE_PTRMEM_P (type))
20991     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
20992             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
20993                                            (type)));
20994   else if (TYPE_PTR_P (type)
20995            || TREE_CODE (type) == REFERENCE_TYPE)
20996     return dependent_type_p (TREE_TYPE (type));
20997   else if (TREE_CODE (type) == FUNCTION_TYPE
20998            || TREE_CODE (type) == METHOD_TYPE)
20999     {
21000       tree arg_type;
21001
21002       if (dependent_type_p (TREE_TYPE (type)))
21003         return true;
21004       for (arg_type = TYPE_ARG_TYPES (type);
21005            arg_type;
21006            arg_type = TREE_CHAIN (arg_type))
21007         if (dependent_type_p (TREE_VALUE (arg_type)))
21008           return true;
21009       return false;
21010     }
21011   /* -- an array type constructed from any dependent type or whose
21012         size is specified by a constant expression that is
21013         value-dependent.
21014
21015         We checked for type- and value-dependence of the bounds in
21016         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
21017   if (TREE_CODE (type) == ARRAY_TYPE)
21018     {
21019       if (TYPE_DOMAIN (type)
21020           && dependent_type_p (TYPE_DOMAIN (type)))
21021         return true;
21022       return dependent_type_p (TREE_TYPE (type));
21023     }
21024
21025   /* -- a template-id in which either the template name is a template
21026      parameter ...  */
21027   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21028     return true;
21029   /* ... or any of the template arguments is a dependent type or
21030         an expression that is type-dependent or value-dependent.  */
21031   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
21032            && (any_dependent_template_arguments_p
21033                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
21034     return true;
21035
21036   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
21037      dependent; if the argument of the `typeof' expression is not
21038      type-dependent, then it should already been have resolved.  */
21039   if (TREE_CODE (type) == TYPEOF_TYPE
21040       || TREE_CODE (type) == DECLTYPE_TYPE
21041       || TREE_CODE (type) == UNDERLYING_TYPE)
21042     return true;
21043
21044   /* A template argument pack is dependent if any of its packed
21045      arguments are.  */
21046   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
21047     {
21048       tree args = ARGUMENT_PACK_ARGS (type);
21049       int i, len = TREE_VEC_LENGTH (args);
21050       for (i = 0; i < len; ++i)
21051         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
21052           return true;
21053     }
21054
21055   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
21056      be template parameters.  */
21057   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
21058     return true;
21059
21060   /* The standard does not specifically mention types that are local
21061      to template functions or local classes, but they should be
21062      considered dependent too.  For example:
21063
21064        template <int I> void f() {
21065          enum E { a = I };
21066          S<sizeof (E)> s;
21067        }
21068
21069      The size of `E' cannot be known until the value of `I' has been
21070      determined.  Therefore, `E' must be considered dependent.  */
21071   scope = TYPE_CONTEXT (type);
21072   if (scope && TYPE_P (scope))
21073     return dependent_type_p (scope);
21074   /* Don't use type_dependent_expression_p here, as it can lead
21075      to infinite recursion trying to determine whether a lambda
21076      nested in a lambda is dependent (c++/47687).  */
21077   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
21078            && DECL_LANG_SPECIFIC (scope)
21079            && DECL_TEMPLATE_INFO (scope)
21080            && (any_dependent_template_arguments_p
21081                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
21082     return true;
21083
21084   /* Other types are non-dependent.  */
21085   return false;
21086 }
21087
21088 /* Returns TRUE if TYPE is dependent, in the sense of
21089    [temp.dep.type].  Note that a NULL type is considered dependent.  */
21090
21091 bool
21092 dependent_type_p (tree type)
21093 {
21094   /* If there are no template parameters in scope, then there can't be
21095      any dependent types.  */
21096   if (!processing_template_decl)
21097     {
21098       /* If we are not processing a template, then nobody should be
21099          providing us with a dependent type.  */
21100       gcc_assert (type);
21101       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
21102       return false;
21103     }
21104
21105   /* If the type is NULL, we have not computed a type for the entity
21106      in question; in that case, the type is dependent.  */
21107   if (!type)
21108     return true;
21109
21110   /* Erroneous types can be considered non-dependent.  */
21111   if (type == error_mark_node)
21112     return false;
21113
21114   /* If we have not already computed the appropriate value for TYPE,
21115      do so now.  */
21116   if (!TYPE_DEPENDENT_P_VALID (type))
21117     {
21118       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
21119       TYPE_DEPENDENT_P_VALID (type) = 1;
21120     }
21121
21122   return TYPE_DEPENDENT_P (type);
21123 }
21124
21125 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
21126    lookup.  In other words, a dependent type that is not the current
21127    instantiation.  */
21128
21129 bool
21130 dependent_scope_p (tree scope)
21131 {
21132   return (scope && TYPE_P (scope) && dependent_type_p (scope)
21133           && !currently_open_class (scope));
21134 }
21135
21136 /* T is a SCOPE_REF; return whether we need to consider it
21137     instantiation-dependent so that we can check access at instantiation
21138     time even though we know which member it resolves to.  */
21139
21140 static bool
21141 instantiation_dependent_scope_ref_p (tree t)
21142 {
21143   if (DECL_P (TREE_OPERAND (t, 1))
21144       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
21145       && accessible_in_template_p (TREE_OPERAND (t, 0),
21146                                    TREE_OPERAND (t, 1)))
21147     return false;
21148   else
21149     return true;
21150 }
21151
21152 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
21153    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
21154    expression.  */
21155
21156 /* Note that this predicate is not appropriate for general expressions;
21157    only constant expressions (that satisfy potential_constant_expression)
21158    can be tested for value dependence.  */
21159
21160 bool
21161 value_dependent_expression_p (tree expression)
21162 {
21163   if (!processing_template_decl)
21164     return false;
21165
21166   /* A name declared with a dependent type.  */
21167   if (DECL_P (expression) && type_dependent_expression_p (expression))
21168     return true;
21169
21170   switch (TREE_CODE (expression))
21171     {
21172     case IDENTIFIER_NODE:
21173       /* A name that has not been looked up -- must be dependent.  */
21174       return true;
21175
21176     case TEMPLATE_PARM_INDEX:
21177       /* A non-type template parm.  */
21178       return true;
21179
21180     case CONST_DECL:
21181       /* A non-type template parm.  */
21182       if (DECL_TEMPLATE_PARM_P (expression))
21183         return true;
21184       return value_dependent_expression_p (DECL_INITIAL (expression));
21185
21186     case VAR_DECL:
21187        /* A constant with literal type and is initialized
21188           with an expression that is value-dependent.
21189
21190           Note that a non-dependent parenthesized initializer will have
21191           already been replaced with its constant value, so if we see
21192           a TREE_LIST it must be dependent.  */
21193       if (DECL_INITIAL (expression)
21194           && decl_constant_var_p (expression)
21195           && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
21196               /* cp_finish_decl doesn't fold reference initializers.  */
21197               || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE
21198               || value_dependent_expression_p (DECL_INITIAL (expression))))
21199         return true;
21200       return false;
21201
21202     case DYNAMIC_CAST_EXPR:
21203     case STATIC_CAST_EXPR:
21204     case CONST_CAST_EXPR:
21205     case REINTERPRET_CAST_EXPR:
21206     case CAST_EXPR:
21207       /* These expressions are value-dependent if the type to which
21208          the cast occurs is dependent or the expression being casted
21209          is value-dependent.  */
21210       {
21211         tree type = TREE_TYPE (expression);
21212
21213         if (dependent_type_p (type))
21214           return true;
21215
21216         /* A functional cast has a list of operands.  */
21217         expression = TREE_OPERAND (expression, 0);
21218         if (!expression)
21219           {
21220             /* If there are no operands, it must be an expression such
21221                as "int()". This should not happen for aggregate types
21222                because it would form non-constant expressions.  */
21223             gcc_assert (cxx_dialect >= cxx11
21224                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
21225
21226             return false;
21227           }
21228
21229         if (TREE_CODE (expression) == TREE_LIST)
21230           return any_value_dependent_elements_p (expression);
21231
21232         return value_dependent_expression_p (expression);
21233       }
21234
21235     case SIZEOF_EXPR:
21236       if (SIZEOF_EXPR_TYPE_P (expression))
21237         return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
21238       /* FALLTHRU */
21239     case ALIGNOF_EXPR:
21240     case TYPEID_EXPR:
21241       /* A `sizeof' expression is value-dependent if the operand is
21242          type-dependent or is a pack expansion.  */
21243       expression = TREE_OPERAND (expression, 0);
21244       if (PACK_EXPANSION_P (expression))
21245         return true;
21246       else if (TYPE_P (expression))
21247         return dependent_type_p (expression);
21248       return instantiation_dependent_expression_p (expression);
21249
21250     case AT_ENCODE_EXPR:
21251       /* An 'encode' expression is value-dependent if the operand is
21252          type-dependent.  */
21253       expression = TREE_OPERAND (expression, 0);
21254       return dependent_type_p (expression);
21255
21256     case NOEXCEPT_EXPR:
21257       expression = TREE_OPERAND (expression, 0);
21258       return instantiation_dependent_expression_p (expression);
21259
21260     case SCOPE_REF:
21261       /* All instantiation-dependent expressions should also be considered
21262          value-dependent.  */
21263       return instantiation_dependent_scope_ref_p (expression);
21264
21265     case COMPONENT_REF:
21266       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
21267               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
21268
21269     case NONTYPE_ARGUMENT_PACK:
21270       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
21271          is value-dependent.  */
21272       {
21273         tree values = ARGUMENT_PACK_ARGS (expression);
21274         int i, len = TREE_VEC_LENGTH (values);
21275         
21276         for (i = 0; i < len; ++i)
21277           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
21278             return true;
21279         
21280         return false;
21281       }
21282
21283     case TRAIT_EXPR:
21284       {
21285         tree type2 = TRAIT_EXPR_TYPE2 (expression);
21286         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
21287                 || (type2 ? dependent_type_p (type2) : false));
21288       }
21289
21290     case MODOP_EXPR:
21291       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
21292               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
21293
21294     case ARRAY_REF:
21295       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
21296               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
21297
21298     case ADDR_EXPR:
21299       {
21300         tree op = TREE_OPERAND (expression, 0);
21301         return (value_dependent_expression_p (op)
21302                 || has_value_dependent_address (op));
21303       }
21304
21305     case CALL_EXPR:
21306       {
21307         tree fn = get_callee_fndecl (expression);
21308         int i, nargs;
21309         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
21310           return true;
21311         nargs = call_expr_nargs (expression);
21312         for (i = 0; i < nargs; ++i)
21313           {
21314             tree op = CALL_EXPR_ARG (expression, i);
21315             /* In a call to a constexpr member function, look through the
21316                implicit ADDR_EXPR on the object argument so that it doesn't
21317                cause the call to be considered value-dependent.  We also
21318                look through it in potential_constant_expression.  */
21319             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
21320                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21321                 && TREE_CODE (op) == ADDR_EXPR)
21322               op = TREE_OPERAND (op, 0);
21323             if (value_dependent_expression_p (op))
21324               return true;
21325           }
21326         return false;
21327       }
21328
21329     case TEMPLATE_ID_EXPR:
21330       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
21331          type-dependent.  */
21332       return type_dependent_expression_p (expression);
21333
21334     case CONSTRUCTOR:
21335       {
21336         unsigned ix;
21337         tree val;
21338         if (dependent_type_p (TREE_TYPE (expression)))
21339           return true;
21340         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
21341           if (value_dependent_expression_p (val))
21342             return true;
21343         return false;
21344       }
21345
21346     case STMT_EXPR:
21347       /* Treat a GNU statement expression as dependent to avoid crashing
21348          under instantiate_non_dependent_expr; it can't be constant.  */
21349       return true;
21350
21351     default:
21352       /* A constant expression is value-dependent if any subexpression is
21353          value-dependent.  */
21354       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
21355         {
21356         case tcc_reference:
21357         case tcc_unary:
21358         case tcc_comparison:
21359         case tcc_binary:
21360         case tcc_expression:
21361         case tcc_vl_exp:
21362           {
21363             int i, len = cp_tree_operand_length (expression);
21364
21365             for (i = 0; i < len; i++)
21366               {
21367                 tree t = TREE_OPERAND (expression, i);
21368
21369                 /* In some cases, some of the operands may be missing.l
21370                    (For example, in the case of PREDECREMENT_EXPR, the
21371                    amount to increment by may be missing.)  That doesn't
21372                    make the expression dependent.  */
21373                 if (t && value_dependent_expression_p (t))
21374                   return true;
21375               }
21376           }
21377           break;
21378         default:
21379           break;
21380         }
21381       break;
21382     }
21383
21384   /* The expression is not value-dependent.  */
21385   return false;
21386 }
21387
21388 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
21389    [temp.dep.expr].  Note that an expression with no type is
21390    considered dependent.  Other parts of the compiler arrange for an
21391    expression with type-dependent subexpressions to have no type, so
21392    this function doesn't have to be fully recursive.  */
21393
21394 bool
21395 type_dependent_expression_p (tree expression)
21396 {
21397   if (!processing_template_decl)
21398     return false;
21399
21400   if (expression == NULL_TREE || expression == error_mark_node)
21401     return false;
21402
21403   /* An unresolved name is always dependent.  */
21404   if (identifier_p (expression) || TREE_CODE (expression) == USING_DECL)
21405     return true;
21406
21407   /* Some expression forms are never type-dependent.  */
21408   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
21409       || TREE_CODE (expression) == SIZEOF_EXPR
21410       || TREE_CODE (expression) == ALIGNOF_EXPR
21411       || TREE_CODE (expression) == AT_ENCODE_EXPR
21412       || TREE_CODE (expression) == NOEXCEPT_EXPR
21413       || TREE_CODE (expression) == TRAIT_EXPR
21414       || TREE_CODE (expression) == TYPEID_EXPR
21415       || TREE_CODE (expression) == DELETE_EXPR
21416       || TREE_CODE (expression) == VEC_DELETE_EXPR
21417       || TREE_CODE (expression) == THROW_EXPR)
21418     return false;
21419
21420   /* The types of these expressions depends only on the type to which
21421      the cast occurs.  */
21422   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
21423       || TREE_CODE (expression) == STATIC_CAST_EXPR
21424       || TREE_CODE (expression) == CONST_CAST_EXPR
21425       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
21426       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
21427       || TREE_CODE (expression) == CAST_EXPR)
21428     return dependent_type_p (TREE_TYPE (expression));
21429
21430   /* The types of these expressions depends only on the type created
21431      by the expression.  */
21432   if (TREE_CODE (expression) == NEW_EXPR
21433       || TREE_CODE (expression) == VEC_NEW_EXPR)
21434     {
21435       /* For NEW_EXPR tree nodes created inside a template, either
21436          the object type itself or a TREE_LIST may appear as the
21437          operand 1.  */
21438       tree type = TREE_OPERAND (expression, 1);
21439       if (TREE_CODE (type) == TREE_LIST)
21440         /* This is an array type.  We need to check array dimensions
21441            as well.  */
21442         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
21443                || value_dependent_expression_p
21444                     (TREE_OPERAND (TREE_VALUE (type), 1));
21445       else
21446         return dependent_type_p (type);
21447     }
21448
21449   if (TREE_CODE (expression) == SCOPE_REF)
21450     {
21451       tree scope = TREE_OPERAND (expression, 0);
21452       tree name = TREE_OPERAND (expression, 1);
21453
21454       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
21455          contains an identifier associated by name lookup with one or more
21456          declarations declared with a dependent type, or...a
21457          nested-name-specifier or qualified-id that names a member of an
21458          unknown specialization.  */
21459       return (type_dependent_expression_p (name)
21460               || dependent_scope_p (scope));
21461     }
21462
21463   if (TREE_CODE (expression) == FUNCTION_DECL
21464       && DECL_LANG_SPECIFIC (expression)
21465       && DECL_TEMPLATE_INFO (expression)
21466       && (any_dependent_template_arguments_p
21467           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
21468     return true;
21469
21470   if (TREE_CODE (expression) == TEMPLATE_DECL
21471       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
21472     return false;
21473
21474   if (TREE_CODE (expression) == STMT_EXPR)
21475     expression = stmt_expr_value_expr (expression);
21476
21477   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
21478     {
21479       tree elt;
21480       unsigned i;
21481
21482       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
21483         {
21484           if (type_dependent_expression_p (elt))
21485             return true;
21486         }
21487       return false;
21488     }
21489
21490   /* A static data member of the current instantiation with incomplete
21491      array type is type-dependent, as the definition and specializations
21492      can have different bounds.  */
21493   if (VAR_P (expression)
21494       && DECL_CLASS_SCOPE_P (expression)
21495       && dependent_type_p (DECL_CONTEXT (expression))
21496       && VAR_HAD_UNKNOWN_BOUND (expression))
21497     return true;
21498
21499   /* An array of unknown bound depending on a variadic parameter, eg:
21500
21501      template<typename... Args>
21502        void foo (Args... args)
21503        {
21504          int arr[] = { args... };
21505        }
21506
21507      template<int... vals>
21508        void bar ()
21509        {
21510          int arr[] = { vals... };
21511        }
21512
21513      If the array has no length and has an initializer, it must be that
21514      we couldn't determine its length in cp_complete_array_type because
21515      it is dependent.  */
21516   if (VAR_P (expression)
21517       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
21518       && !TYPE_DOMAIN (TREE_TYPE (expression))
21519       && DECL_INITIAL (expression))
21520    return true;
21521
21522   /* A variable template specialization is type-dependent if it has any
21523      dependent template arguments.  */
21524   if (VAR_P (expression)
21525       && DECL_LANG_SPECIFIC (expression)
21526       && DECL_TEMPLATE_INFO (expression)
21527       && variable_template_p (DECL_TI_TEMPLATE (expression)))
21528     return any_dependent_template_arguments_p (DECL_TI_ARGS (expression));
21529
21530   /* Always dependent, on the number of arguments if nothing else.  */
21531   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
21532     return true;
21533
21534   if (TREE_TYPE (expression) == unknown_type_node)
21535     {
21536       if (TREE_CODE (expression) == ADDR_EXPR)
21537         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
21538       if (TREE_CODE (expression) == COMPONENT_REF
21539           || TREE_CODE (expression) == OFFSET_REF)
21540         {
21541           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
21542             return true;
21543           expression = TREE_OPERAND (expression, 1);
21544           if (identifier_p (expression))
21545             return false;
21546         }
21547       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
21548       if (TREE_CODE (expression) == SCOPE_REF)
21549         return false;
21550
21551       if (BASELINK_P (expression))
21552         {
21553           if (BASELINK_OPTYPE (expression)
21554               && dependent_type_p (BASELINK_OPTYPE (expression)))
21555             return true;
21556           expression = BASELINK_FUNCTIONS (expression);
21557         }
21558
21559       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
21560         {
21561           if (any_dependent_template_arguments_p
21562               (TREE_OPERAND (expression, 1)))
21563             return true;
21564           expression = TREE_OPERAND (expression, 0);
21565         }
21566       gcc_assert (TREE_CODE (expression) == OVERLOAD
21567                   || TREE_CODE (expression) == FUNCTION_DECL);
21568
21569       while (expression)
21570         {
21571           if (type_dependent_expression_p (OVL_CURRENT (expression)))
21572             return true;
21573           expression = OVL_NEXT (expression);
21574         }
21575       return false;
21576     }
21577
21578   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
21579
21580   return (dependent_type_p (TREE_TYPE (expression)));
21581 }
21582
21583 /* walk_tree callback function for instantiation_dependent_expression_p,
21584    below.  Returns non-zero if a dependent subexpression is found.  */
21585
21586 static tree
21587 instantiation_dependent_r (tree *tp, int *walk_subtrees,
21588                            void * /*data*/)
21589 {
21590   if (TYPE_P (*tp))
21591     {
21592       /* We don't have to worry about decltype currently because decltype
21593          of an instantiation-dependent expr is a dependent type.  This
21594          might change depending on the resolution of DR 1172.  */
21595       *walk_subtrees = false;
21596       return NULL_TREE;
21597     }
21598   enum tree_code code = TREE_CODE (*tp);
21599   switch (code)
21600     {
21601       /* Don't treat an argument list as dependent just because it has no
21602          TREE_TYPE.  */
21603     case TREE_LIST:
21604     case TREE_VEC:
21605       return NULL_TREE;
21606
21607     case VAR_DECL:
21608     case CONST_DECL:
21609       /* A constant with a dependent initializer is dependent.  */
21610       if (value_dependent_expression_p (*tp))
21611         return *tp;
21612       break;
21613
21614     case TEMPLATE_PARM_INDEX:
21615       return *tp;
21616
21617       /* Handle expressions with type operands.  */
21618     case SIZEOF_EXPR:
21619     case ALIGNOF_EXPR:
21620     case TYPEID_EXPR:
21621     case AT_ENCODE_EXPR:
21622       {
21623         tree op = TREE_OPERAND (*tp, 0);
21624         if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
21625           op = TREE_TYPE (op);
21626         if (TYPE_P (op))
21627           {
21628             if (dependent_type_p (op))
21629               return *tp;
21630             else
21631               {
21632                 *walk_subtrees = false;
21633                 return NULL_TREE;
21634               }
21635           }
21636         break;
21637       }
21638
21639     case TRAIT_EXPR:
21640       if (dependent_type_p (TRAIT_EXPR_TYPE1 (*tp))
21641           || (TRAIT_EXPR_TYPE2 (*tp)
21642               && dependent_type_p (TRAIT_EXPR_TYPE2 (*tp))))
21643         return *tp;
21644       *walk_subtrees = false;
21645       return NULL_TREE;
21646
21647     case COMPONENT_REF:
21648       if (identifier_p (TREE_OPERAND (*tp, 1)))
21649         /* In a template, finish_class_member_access_expr creates a
21650            COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
21651            type-dependent, so that we can check access control at
21652            instantiation time (PR 42277).  See also Core issue 1273.  */
21653         return *tp;
21654       break;
21655
21656     case SCOPE_REF:
21657       if (instantiation_dependent_scope_ref_p (*tp))
21658         return *tp;
21659       else
21660         break;
21661
21662       /* Treat statement-expressions as dependent.  */
21663     case BIND_EXPR:
21664       return *tp;
21665
21666     default:
21667       break;
21668     }
21669
21670   if (type_dependent_expression_p (*tp))
21671     return *tp;
21672   else
21673     return NULL_TREE;
21674 }
21675
21676 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
21677    sense defined by the ABI:
21678
21679    "An expression is instantiation-dependent if it is type-dependent
21680    or value-dependent, or it has a subexpression that is type-dependent
21681    or value-dependent."  */
21682
21683 bool
21684 instantiation_dependent_expression_p (tree expression)
21685 {
21686   tree result;
21687
21688   if (!processing_template_decl)
21689     return false;
21690
21691   if (expression == error_mark_node)
21692     return false;
21693
21694   result = cp_walk_tree_without_duplicates (&expression,
21695                                             instantiation_dependent_r, NULL);
21696   return result != NULL_TREE;
21697 }
21698
21699 /* Like type_dependent_expression_p, but it also works while not processing
21700    a template definition, i.e. during substitution or mangling.  */
21701
21702 bool
21703 type_dependent_expression_p_push (tree expr)
21704 {
21705   bool b;
21706   ++processing_template_decl;
21707   b = type_dependent_expression_p (expr);
21708   --processing_template_decl;
21709   return b;
21710 }
21711
21712 /* Returns TRUE if ARGS contains a type-dependent expression.  */
21713
21714 bool
21715 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
21716 {
21717   unsigned int i;
21718   tree arg;
21719
21720   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
21721     {
21722       if (type_dependent_expression_p (arg))
21723         return true;
21724     }
21725   return false;
21726 }
21727
21728 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
21729    expressions) contains any type-dependent expressions.  */
21730
21731 bool
21732 any_type_dependent_elements_p (const_tree list)
21733 {
21734   for (; list; list = TREE_CHAIN (list))
21735     if (type_dependent_expression_p (TREE_VALUE (list)))
21736       return true;
21737
21738   return false;
21739 }
21740
21741 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
21742    expressions) contains any value-dependent expressions.  */
21743
21744 bool
21745 any_value_dependent_elements_p (const_tree list)
21746 {
21747   for (; list; list = TREE_CHAIN (list))
21748     if (value_dependent_expression_p (TREE_VALUE (list)))
21749       return true;
21750
21751   return false;
21752 }
21753
21754 /* Returns TRUE if the ARG (a template argument) is dependent.  */
21755
21756 bool
21757 dependent_template_arg_p (tree arg)
21758 {
21759   if (!processing_template_decl)
21760     return false;
21761
21762   /* Assume a template argument that was wrongly written by the user
21763      is dependent. This is consistent with what
21764      any_dependent_template_arguments_p [that calls this function]
21765      does.  */
21766   if (!arg || arg == error_mark_node)
21767     return true;
21768
21769   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
21770     arg = ARGUMENT_PACK_SELECT_ARG (arg);
21771
21772   if (TREE_CODE (arg) == TEMPLATE_DECL
21773       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
21774     return dependent_template_p (arg);
21775   else if (ARGUMENT_PACK_P (arg))
21776     {
21777       tree args = ARGUMENT_PACK_ARGS (arg);
21778       int i, len = TREE_VEC_LENGTH (args);
21779       for (i = 0; i < len; ++i)
21780         {
21781           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
21782             return true;
21783         }
21784
21785       return false;
21786     }
21787   else if (TYPE_P (arg))
21788     return dependent_type_p (arg);
21789   else
21790     return (type_dependent_expression_p (arg)
21791             || value_dependent_expression_p (arg));
21792 }
21793
21794 /* Returns true if ARGS (a collection of template arguments) contains
21795    any types that require structural equality testing.  */
21796
21797 bool
21798 any_template_arguments_need_structural_equality_p (tree args)
21799 {
21800   int i;
21801   int j;
21802
21803   if (!args)
21804     return false;
21805   if (args == error_mark_node)
21806     return true;
21807
21808   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
21809     {
21810       tree level = TMPL_ARGS_LEVEL (args, i + 1);
21811       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
21812         {
21813           tree arg = TREE_VEC_ELT (level, j);
21814           tree packed_args = NULL_TREE;
21815           int k, len = 1;
21816
21817           if (ARGUMENT_PACK_P (arg))
21818             {
21819               /* Look inside the argument pack.  */
21820               packed_args = ARGUMENT_PACK_ARGS (arg);
21821               len = TREE_VEC_LENGTH (packed_args);
21822             }
21823
21824           for (k = 0; k < len; ++k)
21825             {
21826               if (packed_args)
21827                 arg = TREE_VEC_ELT (packed_args, k);
21828
21829               if (error_operand_p (arg))
21830                 return true;
21831               else if (TREE_CODE (arg) == TEMPLATE_DECL)
21832                 continue;
21833               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
21834                 return true;
21835               else if (!TYPE_P (arg) && TREE_TYPE (arg)
21836                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
21837                 return true;
21838             }
21839         }
21840     }
21841
21842   return false;
21843 }
21844
21845 /* Returns true if ARGS (a collection of template arguments) contains
21846    any dependent arguments.  */
21847
21848 bool
21849 any_dependent_template_arguments_p (const_tree args)
21850 {
21851   int i;
21852   int j;
21853
21854   if (!args)
21855     return false;
21856   if (args == error_mark_node)
21857     return true;
21858
21859   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
21860     {
21861       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
21862       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
21863         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
21864           return true;
21865     }
21866
21867   return false;
21868 }
21869
21870 /* Returns TRUE if the template TMPL is dependent.  */
21871
21872 bool
21873 dependent_template_p (tree tmpl)
21874 {
21875   if (TREE_CODE (tmpl) == OVERLOAD)
21876     {
21877       while (tmpl)
21878         {
21879           if (dependent_template_p (OVL_CURRENT (tmpl)))
21880             return true;
21881           tmpl = OVL_NEXT (tmpl);
21882         }
21883       return false;
21884     }
21885
21886   /* Template template parameters are dependent.  */
21887   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
21888       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
21889     return true;
21890   /* So are names that have not been looked up.  */
21891   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
21892     return true;
21893   /* So are member templates of dependent classes.  */
21894   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
21895     return dependent_type_p (DECL_CONTEXT (tmpl));
21896   return false;
21897 }
21898
21899 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
21900
21901 bool
21902 dependent_template_id_p (tree tmpl, tree args)
21903 {
21904   return (dependent_template_p (tmpl)
21905           || any_dependent_template_arguments_p (args));
21906 }
21907
21908 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
21909    is dependent.  */
21910
21911 bool
21912 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
21913 {
21914   int i;
21915
21916   if (!processing_template_decl)
21917     return false;
21918
21919   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
21920     {
21921       tree decl = TREE_VEC_ELT (declv, i);
21922       tree init = TREE_VEC_ELT (initv, i);
21923       tree cond = TREE_VEC_ELT (condv, i);
21924       tree incr = TREE_VEC_ELT (incrv, i);
21925
21926       if (type_dependent_expression_p (decl))
21927         return true;
21928
21929       if (init && type_dependent_expression_p (init))
21930         return true;
21931
21932       if (type_dependent_expression_p (cond))
21933         return true;
21934
21935       if (COMPARISON_CLASS_P (cond)
21936           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
21937               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
21938         return true;
21939
21940       if (TREE_CODE (incr) == MODOP_EXPR)
21941         {
21942           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
21943               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
21944             return true;
21945         }
21946       else if (type_dependent_expression_p (incr))
21947         return true;
21948       else if (TREE_CODE (incr) == MODIFY_EXPR)
21949         {
21950           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
21951             return true;
21952           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
21953             {
21954               tree t = TREE_OPERAND (incr, 1);
21955               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
21956                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
21957                 return true;
21958             }
21959         }
21960     }
21961
21962   return false;
21963 }
21964
21965 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
21966    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
21967    no such TYPE can be found.  Note that this function peers inside
21968    uninstantiated templates and therefore should be used only in
21969    extremely limited situations.  ONLY_CURRENT_P restricts this
21970    peering to the currently open classes hierarchy (which is required
21971    when comparing types).  */
21972
21973 tree
21974 resolve_typename_type (tree type, bool only_current_p)
21975 {
21976   tree scope;
21977   tree name;
21978   tree decl;
21979   int quals;
21980   tree pushed_scope;
21981   tree result;
21982
21983   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
21984
21985   scope = TYPE_CONTEXT (type);
21986   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
21987      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
21988      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
21989      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
21990      identifier  of the TYPENAME_TYPE anymore.
21991      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
21992      TYPENAME_TYPE instead, we avoid messing up with a possible
21993      typedef variant case.  */
21994   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
21995
21996   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
21997      it first before we can figure out what NAME refers to.  */
21998   if (TREE_CODE (scope) == TYPENAME_TYPE)
21999     {
22000       if (TYPENAME_IS_RESOLVING_P (scope))
22001         /* Given a class template A with a dependent base with nested type C,
22002            typedef typename A::C::C C will land us here, as trying to resolve
22003            the initial A::C leads to the local C typedef, which leads back to
22004            A::C::C.  So we break the recursion now.  */
22005         return type;
22006       else
22007         scope = resolve_typename_type (scope, only_current_p);
22008     }
22009   /* If we don't know what SCOPE refers to, then we cannot resolve the
22010      TYPENAME_TYPE.  */
22011   if (TREE_CODE (scope) == TYPENAME_TYPE)
22012     return type;
22013   /* If the SCOPE is a template type parameter, we have no way of
22014      resolving the name.  */
22015   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
22016     return type;
22017   /* If the SCOPE is not the current instantiation, there's no reason
22018      to look inside it.  */
22019   if (only_current_p && !currently_open_class (scope))
22020     return type;
22021   /* If this is a typedef, we don't want to look inside (c++/11987).  */
22022   if (typedef_variant_p (type))
22023     return type;
22024   /* If SCOPE isn't the template itself, it will not have a valid
22025      TYPE_FIELDS list.  */
22026   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
22027     /* scope is either the template itself or a compatible instantiation
22028        like X<T>, so look up the name in the original template.  */
22029     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
22030   else
22031     /* scope is a partial instantiation, so we can't do the lookup or we
22032        will lose the template arguments.  */
22033     return type;
22034   /* Enter the SCOPE so that name lookup will be resolved as if we
22035      were in the class definition.  In particular, SCOPE will no
22036      longer be considered a dependent type.  */
22037   pushed_scope = push_scope (scope);
22038   /* Look up the declaration.  */
22039   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
22040                         tf_warning_or_error);
22041
22042   result = NULL_TREE;
22043   
22044   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
22045      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
22046   if (!decl)
22047     /*nop*/;
22048   else if (identifier_p (TYPENAME_TYPE_FULLNAME (type))
22049            && TREE_CODE (decl) == TYPE_DECL)
22050     {
22051       result = TREE_TYPE (decl);
22052       if (result == error_mark_node)
22053         result = NULL_TREE;
22054     }
22055   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
22056            && DECL_CLASS_TEMPLATE_P (decl))
22057     {
22058       tree tmpl;
22059       tree args;
22060       /* Obtain the template and the arguments.  */
22061       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
22062       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
22063       /* Instantiate the template.  */
22064       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
22065                                       /*entering_scope=*/0,
22066                                       tf_error | tf_user);
22067       if (result == error_mark_node)
22068         result = NULL_TREE;
22069     }
22070   
22071   /* Leave the SCOPE.  */
22072   if (pushed_scope)
22073     pop_scope (pushed_scope);
22074
22075   /* If we failed to resolve it, return the original typename.  */
22076   if (!result)
22077     return type;
22078   
22079   /* If lookup found a typename type, resolve that too.  */
22080   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
22081     {
22082       /* Ill-formed programs can cause infinite recursion here, so we
22083          must catch that.  */
22084       TYPENAME_IS_RESOLVING_P (type) = 1;
22085       result = resolve_typename_type (result, only_current_p);
22086       TYPENAME_IS_RESOLVING_P (type) = 0;
22087     }
22088   
22089   /* Qualify the resulting type.  */
22090   quals = cp_type_quals (type);
22091   if (quals)
22092     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
22093
22094   return result;
22095 }
22096
22097 /* EXPR is an expression which is not type-dependent.  Return a proxy
22098    for EXPR that can be used to compute the types of larger
22099    expressions containing EXPR.  */
22100
22101 tree
22102 build_non_dependent_expr (tree expr)
22103 {
22104   tree inner_expr;
22105
22106 #ifdef ENABLE_CHECKING
22107   /* Try to get a constant value for all non-dependent expressions in
22108       order to expose bugs in *_dependent_expression_p and constexpr.  */
22109   if (cxx_dialect >= cxx11)
22110     fold_non_dependent_expr (expr);
22111 #endif
22112
22113   /* Preserve OVERLOADs; the functions must be available to resolve
22114      types.  */
22115   inner_expr = expr;
22116   if (TREE_CODE (inner_expr) == STMT_EXPR)
22117     inner_expr = stmt_expr_value_expr (inner_expr);
22118   if (TREE_CODE (inner_expr) == ADDR_EXPR)
22119     inner_expr = TREE_OPERAND (inner_expr, 0);
22120   if (TREE_CODE (inner_expr) == COMPONENT_REF)
22121     inner_expr = TREE_OPERAND (inner_expr, 1);
22122   if (is_overloaded_fn (inner_expr)
22123       || TREE_CODE (inner_expr) == OFFSET_REF)
22124     return expr;
22125   /* There is no need to return a proxy for a variable.  */
22126   if (VAR_P (expr))
22127     return expr;
22128   /* Preserve string constants; conversions from string constants to
22129      "char *" are allowed, even though normally a "const char *"
22130      cannot be used to initialize a "char *".  */
22131   if (TREE_CODE (expr) == STRING_CST)
22132     return expr;
22133   /* Preserve void and arithmetic constants, as an optimization -- there is no
22134      reason to create a new node.  */
22135   if (TREE_CODE (expr) == VOID_CST
22136       || TREE_CODE (expr) == INTEGER_CST
22137       || TREE_CODE (expr) == REAL_CST)
22138     return expr;
22139   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
22140      There is at least one place where we want to know that a
22141      particular expression is a throw-expression: when checking a ?:
22142      expression, there are special rules if the second or third
22143      argument is a throw-expression.  */
22144   if (TREE_CODE (expr) == THROW_EXPR)
22145     return expr;
22146
22147   /* Don't wrap an initializer list, we need to be able to look inside.  */
22148   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
22149     return expr;
22150
22151   /* Don't wrap a dummy object, we need to be able to test for it.  */
22152   if (is_dummy_object (expr))
22153     return expr;
22154
22155   if (TREE_CODE (expr) == COND_EXPR)
22156     return build3 (COND_EXPR,
22157                    TREE_TYPE (expr),
22158                    TREE_OPERAND (expr, 0),
22159                    (TREE_OPERAND (expr, 1)
22160                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
22161                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
22162                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
22163   if (TREE_CODE (expr) == COMPOUND_EXPR
22164       && !COMPOUND_EXPR_OVERLOADED (expr))
22165     return build2 (COMPOUND_EXPR,
22166                    TREE_TYPE (expr),
22167                    TREE_OPERAND (expr, 0),
22168                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
22169
22170   /* If the type is unknown, it can't really be non-dependent */
22171   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
22172
22173   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
22174   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
22175 }
22176
22177 /* ARGS is a vector of expressions as arguments to a function call.
22178    Replace the arguments with equivalent non-dependent expressions.
22179    This modifies ARGS in place.  */
22180
22181 void
22182 make_args_non_dependent (vec<tree, va_gc> *args)
22183 {
22184   unsigned int ix;
22185   tree arg;
22186
22187   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
22188     {
22189       tree newarg = build_non_dependent_expr (arg);
22190       if (newarg != arg)
22191         (*args)[ix] = newarg;
22192     }
22193 }
22194
22195 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
22196    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
22197    parms.  */
22198
22199 static tree
22200 make_auto_1 (tree name)
22201 {
22202   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
22203   TYPE_NAME (au) = build_decl (input_location,
22204                                TYPE_DECL, name, au);
22205   TYPE_STUB_DECL (au) = TYPE_NAME (au);
22206   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
22207     (0, processing_template_decl + 1, processing_template_decl + 1,
22208      TYPE_NAME (au), NULL_TREE);
22209   TYPE_CANONICAL (au) = canonical_type_parameter (au);
22210   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
22211   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
22212
22213   return au;
22214 }
22215
22216 tree
22217 make_decltype_auto (void)
22218 {
22219   return make_auto_1 (get_identifier ("decltype(auto)"));
22220 }
22221
22222 tree
22223 make_auto (void)
22224 {
22225   return make_auto_1 (get_identifier ("auto"));
22226 }
22227
22228 /* Given type ARG, return std::initializer_list<ARG>.  */
22229
22230 static tree
22231 listify (tree arg)
22232 {
22233   tree std_init_list = namespace_binding
22234     (get_identifier ("initializer_list"), std_node);
22235   tree argvec;
22236   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
22237     {    
22238       error ("deducing from brace-enclosed initializer list requires "
22239              "#include <initializer_list>");
22240       return error_mark_node;
22241     }
22242   argvec = make_tree_vec (1);
22243   TREE_VEC_ELT (argvec, 0) = arg;
22244   return lookup_template_class (std_init_list, argvec, NULL_TREE,
22245                                 NULL_TREE, 0, tf_warning_or_error);
22246 }
22247
22248 /* Replace auto in TYPE with std::initializer_list<auto>.  */
22249
22250 static tree
22251 listify_autos (tree type, tree auto_node)
22252 {
22253   tree init_auto = listify (auto_node);
22254   tree argvec = make_tree_vec (1);
22255   TREE_VEC_ELT (argvec, 0) = init_auto;
22256   if (processing_template_decl)
22257     argvec = add_to_template_args (current_template_args (), argvec);
22258   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
22259 }
22260
22261 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
22262    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
22263
22264 tree
22265 do_auto_deduction (tree type, tree init, tree auto_node)
22266 {
22267   tree targs;
22268
22269   if (init == error_mark_node)
22270     return error_mark_node;
22271
22272   if (type_dependent_expression_p (init))
22273     /* Defining a subset of type-dependent expressions that we can deduce
22274        from ahead of time isn't worth the trouble.  */
22275     return type;
22276
22277   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
22278      with either a new invented type template parameter U or, if the
22279      initializer is a braced-init-list (8.5.4), with
22280      std::initializer_list<U>.  */
22281   if (BRACE_ENCLOSED_INITIALIZER_P (init))
22282     {
22283       if (!DIRECT_LIST_INIT_P (init))
22284         type = listify_autos (type, auto_node);
22285       else if (CONSTRUCTOR_NELTS (init) == 1)
22286         init = CONSTRUCTOR_ELT (init, 0)->value;
22287       else
22288         {
22289           if (permerror (input_location, "direct-list-initialization of "
22290                          "%<auto%> requires exactly one element"))
22291             inform (input_location,
22292                     "for deduction to %<std::initializer_list%>, use copy-"
22293                     "list-initialization (i.e. add %<=%> before the %<{%>)");
22294           type = listify_autos (type, auto_node);
22295         }
22296     }
22297
22298   init = resolve_nondeduced_context (init);
22299
22300   targs = make_tree_vec (1);
22301   if (AUTO_IS_DECLTYPE (auto_node))
22302     {
22303       bool id = (DECL_P (init) || (TREE_CODE (init) == COMPONENT_REF
22304                                    && !REF_PARENTHESIZED_P (init)));
22305       TREE_VEC_ELT (targs, 0)
22306         = finish_decltype_type (init, id, tf_warning_or_error);
22307       if (type != auto_node)
22308         {
22309           error ("%qT as type rather than plain %<decltype(auto)%>", type);
22310           return error_mark_node;
22311         }
22312     }
22313   else
22314     {
22315       tree parms = build_tree_list (NULL_TREE, type);
22316       tree tparms = make_tree_vec (1);
22317       int val;
22318
22319       TREE_VEC_ELT (tparms, 0)
22320         = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
22321       val = type_unification_real (tparms, targs, parms, &init, 1, 0,
22322                                    DEDUCE_CALL, LOOKUP_NORMAL,
22323                                    NULL, /*explain_p=*/false);
22324       if (val > 0)
22325         {
22326           if (processing_template_decl)
22327             /* Try again at instantiation time.  */
22328             return type;
22329           if (type && type != error_mark_node)
22330             /* If type is error_mark_node a diagnostic must have been
22331                emitted by now.  Also, having a mention to '<type error>'
22332                in the diagnostic is not really useful to the user.  */
22333             {
22334               if (cfun && auto_node == current_function_auto_return_pattern
22335                   && LAMBDA_FUNCTION_P (current_function_decl))
22336                 error ("unable to deduce lambda return type from %qE", init);
22337               else
22338                 error ("unable to deduce %qT from %qE", type, init);
22339             }
22340           return error_mark_node;
22341         }
22342     }
22343
22344   /* If the list of declarators contains more than one declarator, the type
22345      of each declared variable is determined as described above. If the
22346      type deduced for the template parameter U is not the same in each
22347      deduction, the program is ill-formed.  */
22348   if (TREE_TYPE (auto_node)
22349       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
22350     {
22351       if (cfun && auto_node == current_function_auto_return_pattern
22352           && LAMBDA_FUNCTION_P (current_function_decl))
22353         error ("inconsistent types %qT and %qT deduced for "
22354                "lambda return type", TREE_TYPE (auto_node),
22355                TREE_VEC_ELT (targs, 0));
22356       else
22357         error ("inconsistent deduction for %qT: %qT and then %qT",
22358                auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
22359       return error_mark_node;
22360     }
22361   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
22362
22363   if (processing_template_decl)
22364     targs = add_to_template_args (current_template_args (), targs);
22365   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
22366 }
22367
22368 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
22369    result.  */
22370
22371 tree
22372 splice_late_return_type (tree type, tree late_return_type)
22373 {
22374   tree argvec;
22375
22376   if (late_return_type == NULL_TREE)
22377     return type;
22378   argvec = make_tree_vec (1);
22379   TREE_VEC_ELT (argvec, 0) = late_return_type;
22380   if (processing_template_parmlist)
22381     /* For a late-specified return type in a template type-parameter, we
22382        need to add a dummy argument level for its parmlist.  */
22383     argvec = add_to_template_args
22384       (make_tree_vec (processing_template_parmlist), argvec);
22385   if (current_template_parms)
22386     argvec = add_to_template_args (current_template_args (), argvec);
22387   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
22388 }
22389
22390 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
22391    'decltype(auto)'.  */
22392
22393 bool
22394 is_auto (const_tree type)
22395 {
22396   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22397       && (TYPE_IDENTIFIER (type) == get_identifier ("auto")
22398           || TYPE_IDENTIFIER (type) == get_identifier ("decltype(auto)")))
22399     return true;
22400   else
22401     return false;
22402 }
22403
22404 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
22405    a use of `auto'.  Returns NULL_TREE otherwise.  */
22406
22407 tree
22408 type_uses_auto (tree type)
22409 {
22410   return find_type_usage (type, is_auto);
22411 }
22412
22413 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto',
22414    'decltype(auto)' or a concept.  */
22415
22416 bool
22417 is_auto_or_concept (const_tree type)
22418 {
22419   return is_auto (type); // or concept
22420 }
22421
22422 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing a generic type (`auto' or
22423    a concept identifier) iff TYPE contains a use of a generic type.  Returns
22424    NULL_TREE otherwise.  */
22425
22426 tree
22427 type_uses_auto_or_concept (tree type)
22428 {
22429   return find_type_usage (type, is_auto_or_concept);
22430 }
22431
22432
22433 /* For a given template T, return the vector of typedefs referenced
22434    in T for which access check is needed at T instantiation time.
22435    T is either  a FUNCTION_DECL or a RECORD_TYPE.
22436    Those typedefs were added to T by the function
22437    append_type_to_template_for_access_check.  */
22438
22439 vec<qualified_typedef_usage_t, va_gc> *
22440 get_types_needing_access_check (tree t)
22441 {
22442   tree ti;
22443   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
22444
22445   if (!t || t == error_mark_node)
22446     return NULL;
22447
22448   if (!(ti = get_template_info (t)))
22449     return NULL;
22450
22451   if (CLASS_TYPE_P (t)
22452       || TREE_CODE (t) == FUNCTION_DECL)
22453     {
22454       if (!TI_TEMPLATE (ti))
22455         return NULL;
22456
22457       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
22458     }
22459
22460   return result;
22461 }
22462
22463 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
22464    tied to T. That list of typedefs will be access checked at
22465    T instantiation time.
22466    T is either a FUNCTION_DECL or a RECORD_TYPE.
22467    TYPE_DECL is a TYPE_DECL node representing a typedef.
22468    SCOPE is the scope through which TYPE_DECL is accessed.
22469    LOCATION is the location of the usage point of TYPE_DECL.
22470
22471    This function is a subroutine of
22472    append_type_to_template_for_access_check.  */
22473
22474 static void
22475 append_type_to_template_for_access_check_1 (tree t,
22476                                             tree type_decl,
22477                                             tree scope,
22478                                             location_t location)
22479 {
22480   qualified_typedef_usage_t typedef_usage;
22481   tree ti;
22482
22483   if (!t || t == error_mark_node)
22484     return;
22485
22486   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
22487                || CLASS_TYPE_P (t))
22488               && type_decl
22489               && TREE_CODE (type_decl) == TYPE_DECL
22490               && scope);
22491
22492   if (!(ti = get_template_info (t)))
22493     return;
22494
22495   gcc_assert (TI_TEMPLATE (ti));
22496
22497   typedef_usage.typedef_decl = type_decl;
22498   typedef_usage.context = scope;
22499   typedef_usage.locus = location;
22500
22501   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
22502 }
22503
22504 /* Append TYPE_DECL to the template TEMPL.
22505    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
22506    At TEMPL instanciation time, TYPE_DECL will be checked to see
22507    if it can be accessed through SCOPE.
22508    LOCATION is the location of the usage point of TYPE_DECL.
22509
22510    e.g. consider the following code snippet:
22511
22512      class C
22513      {
22514        typedef int myint;
22515      };
22516
22517      template<class U> struct S
22518      {
22519        C::myint mi; // <-- usage point of the typedef C::myint
22520      };
22521
22522      S<char> s;
22523
22524    At S<char> instantiation time, we need to check the access of C::myint
22525    In other words, we need to check the access of the myint typedef through
22526    the C scope. For that purpose, this function will add the myint typedef
22527    and the scope C through which its being accessed to a list of typedefs
22528    tied to the template S. That list will be walked at template instantiation
22529    time and access check performed on each typedefs it contains.
22530    Note that this particular code snippet should yield an error because
22531    myint is private to C.  */
22532
22533 void
22534 append_type_to_template_for_access_check (tree templ,
22535                                           tree type_decl,
22536                                           tree scope,
22537                                           location_t location)
22538 {
22539   qualified_typedef_usage_t *iter;
22540   unsigned i;
22541
22542   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
22543
22544   /* Make sure we don't append the type to the template twice.  */
22545   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
22546     if (iter->typedef_decl == type_decl && scope == iter->context)
22547       return;
22548
22549   append_type_to_template_for_access_check_1 (templ, type_decl,
22550                                               scope, location);
22551 }
22552
22553 /* Convert the generic type parameters in PARM that match the types given in the
22554    range [START_IDX, END_IDX) from the current_template_parms into generic type
22555    packs.  */
22556
22557 tree
22558 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
22559 {
22560   tree current = current_template_parms;
22561   int depth = TMPL_PARMS_DEPTH (current);
22562   current = INNERMOST_TEMPLATE_PARMS (current);
22563   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
22564
22565   for (int i = 0; i < start_idx; ++i)
22566     TREE_VEC_ELT (replacement, i)
22567       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
22568
22569   for (int i = start_idx; i < end_idx; ++i)
22570     {
22571       /* Create a distinct parameter pack type from the current parm and add it
22572          to the replacement args to tsubst below into the generic function
22573          parameter.  */
22574
22575       tree o = TREE_TYPE (TREE_VALUE
22576                           (TREE_VEC_ELT (current, i)));
22577       tree t = copy_type (o);
22578       TEMPLATE_TYPE_PARM_INDEX (t)
22579         = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
22580                                       o, 0, 0, tf_none);
22581       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
22582       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
22583       TYPE_MAIN_VARIANT (t) = t;
22584       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
22585       TYPE_CANONICAL (t) = canonical_type_parameter (t);
22586       TREE_VEC_ELT (replacement, i) = t;
22587       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
22588     }
22589
22590   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
22591     TREE_VEC_ELT (replacement, i)
22592       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
22593
22594   /* If there are more levels then build up the replacement with the outer
22595      template parms.  */
22596   if (depth > 1)
22597     replacement = add_to_template_args (template_parms_to_args
22598                                         (TREE_CHAIN (current_template_parms)),
22599                                         replacement);
22600
22601   return tsubst (parm, replacement, tf_none, NULL_TREE);
22602 }
22603
22604
22605 /* Set up the hash tables for template instantiations.  */
22606
22607 void
22608 init_template_processing (void)
22609 {
22610   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
22611   type_specializations = hash_table<spec_hasher>::create_ggc (37);
22612 }
22613
22614 /* Print stats about the template hash tables for -fstats.  */
22615
22616 void
22617 print_template_statistics (void)
22618 {
22619   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
22620            "%f collisions\n", (long) decl_specializations->size (),
22621            (long) decl_specializations->elements (),
22622            decl_specializations->collisions ());
22623   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
22624            "%f collisions\n", (long) type_specializations->size (),
22625            (long) type_specializations->elements (),
22626            type_specializations->collisions ());
22627 }
22628
22629 #include "gt-cp-pt.h"