187f9d857bc09254cb547e9848f326035bbb7020
[platform/upstream/gcc.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2019 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 "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43 #include "gcc-rich-location.h"
44 #include "selftest.h"
45
46 /* The type of functions taking a tree, and some additional data, and
47    returning an int.  */
48 typedef int (*tree_fn_t) (tree, void*);
49
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51    instantiations have been deferred, either because their definitions
52    were not yet available, or because we were putting off doing the work.  */
53 struct GTY ((chain_next ("%h.next"))) pending_template
54 {
55   struct pending_template *next;
56   struct tinst_level *tinst;
57 };
58
59 static GTY(()) struct pending_template *pending_templates;
60 static GTY(()) struct pending_template *last_pending_template;
61
62 int processing_template_parmlist;
63 static int template_header_count;
64
65 static GTY(()) tree saved_trees;
66 static vec<int> inline_parm_levels;
67
68 static GTY(()) struct tinst_level *current_tinst_level;
69
70 static GTY(()) vec<tree, va_gc> *saved_access_scope;
71
72 /* Live only within one (recursive) call to tsubst_expr.  We use
73    this to pass the statement expression node from the STMT_EXPR
74    to the EXPR_STMT that is its result.  */
75 static tree cur_stmt_expr;
76
77 // -------------------------------------------------------------------------- //
78 // Local Specialization Stack
79 //
80 // Implementation of the RAII helper for creating new local
81 // specializations.
82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83   : saved (local_specializations)
84 {
85   if (policy == lss_blank || !saved)
86     local_specializations = new hash_map<tree, tree>;
87   else
88     local_specializations = new hash_map<tree, tree>(*saved);
89 }
90
91 local_specialization_stack::~local_specialization_stack ()
92 {
93   delete local_specializations;
94   local_specializations = saved;
95 }
96
97 /* True if we've recursed into fn_type_unification too many times.  */
98 static bool excessive_deduction_depth;
99
100 struct GTY((for_user)) spec_entry
101 {
102   tree tmpl;
103   tree args;
104   tree spec;
105 };
106
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
108 {
109   static hashval_t hash (spec_entry *);
110   static bool equal (spec_entry *, spec_entry *);
111 };
112
113 static GTY (()) hash_table<spec_hasher> *decl_specializations;
114
115 static GTY (()) hash_table<spec_hasher> *type_specializations;
116
117 /* Contains canonical template parameter types. The vector is indexed by
118    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
119    TREE_LIST, whose TREE_VALUEs contain the canonical template
120    parameters of various types and levels.  */
121 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
122
123 #define UNIFY_ALLOW_NONE 0
124 #define UNIFY_ALLOW_MORE_CV_QUAL 1
125 #define UNIFY_ALLOW_LESS_CV_QUAL 2
126 #define UNIFY_ALLOW_DERIVED 4
127 #define UNIFY_ALLOW_INTEGER 8
128 #define UNIFY_ALLOW_OUTER_LEVEL 16
129 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
130 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
131
132 enum template_base_result {
133   tbr_incomplete_type,
134   tbr_ambiguous_baseclass,
135   tbr_success
136 };
137
138 static void push_access_scope (tree);
139 static void pop_access_scope (tree);
140 static bool resolve_overloaded_unification (tree, tree, tree, tree,
141                                             unification_kind_t, int,
142                                             bool);
143 static int try_one_overload (tree, tree, tree, tree, tree,
144                              unification_kind_t, int, bool, bool);
145 static int unify (tree, tree, tree, tree, int, bool);
146 static void add_pending_template (tree);
147 static tree reopen_tinst_level (struct tinst_level *);
148 static tree tsubst_initializer_list (tree, tree);
149 static tree get_partial_spec_bindings (tree, tree, tree);
150 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
151                                    bool, bool);
152 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
153                                               bool, bool);
154 static void tsubst_enum (tree, tree, tree);
155 static tree add_to_template_args (tree, tree);
156 static tree add_outermost_template_args (tree, tree);
157 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
158 static int check_non_deducible_conversion (tree, tree, int, int,
159                                            struct conversion **, bool);
160 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
161                                              tree);
162 static int type_unification_real (tree, tree, tree, const tree *,
163                                   unsigned int, int, unification_kind_t,
164                                   vec<deferred_access_check, va_gc> **,
165                                   bool);
166 static void note_template_header (int);
167 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
168 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
169 static tree convert_template_argument (tree, tree, tree,
170                                        tsubst_flags_t, int, tree);
171 static tree for_each_template_parm (tree, tree_fn_t, void*,
172                                     hash_set<tree> *, bool, tree_fn_t = NULL);
173 static tree expand_template_argument_pack (tree);
174 static tree build_template_parm_index (int, int, int, tree, tree);
175 static bool inline_needs_template_parms (tree, bool);
176 static void push_inline_template_parms_recursive (tree, int);
177 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
178 static int mark_template_parm (tree, void *);
179 static int template_parm_this_level_p (tree, void *);
180 static tree tsubst_friend_function (tree, tree);
181 static tree tsubst_friend_class (tree, tree);
182 static int can_complete_type_without_circularity (tree);
183 static tree get_bindings (tree, tree, tree, bool);
184 static int template_decl_level (tree);
185 static int check_cv_quals_for_unify (int, tree, tree);
186 static void template_parm_level_and_index (tree, int*, int*);
187 static int unify_pack_expansion (tree, tree, tree,
188                                  tree, unification_kind_t, bool, bool);
189 static tree copy_template_args (tree);
190 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
192 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
193 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
194 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
195 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
196 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
197 static bool check_specialization_scope (void);
198 static tree process_partial_specialization (tree);
199 static void set_current_access_from_decl (tree);
200 static enum template_base_result get_template_base (tree, tree, tree, tree,
201                                                     bool , tree *);
202 static tree try_class_unification (tree, tree, tree, tree, bool);
203 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
204                                            tree, tree);
205 static bool template_template_parm_bindings_ok_p (tree, tree);
206 static void tsubst_default_arguments (tree, tsubst_flags_t);
207 static tree for_each_template_parm_r (tree *, int *, void *);
208 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
209 static void copy_default_args_to_explicit_spec (tree);
210 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
211 static bool dependent_template_arg_p (tree);
212 static bool any_template_arguments_need_structural_equality_p (tree);
213 static bool dependent_type_p_r (tree);
214 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
215 static tree tsubst_decl (tree, tree, tsubst_flags_t);
216 static void perform_typedefs_access_check (tree tmpl, tree targs);
217 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
218                                                         location_t);
219 static tree listify (tree);
220 static tree listify_autos (tree, tree);
221 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
222 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
223 static bool complex_alias_template_p (const_tree tmpl);
224 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
225 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
226 static tree make_argument_pack (tree);
227 static void register_parameter_specializations (tree, tree);
228 static tree enclosing_instantiation_of (tree tctx);
229
230 /* Make the current scope suitable for access checking when we are
231    processing T.  T can be FUNCTION_DECL for instantiated function
232    template, VAR_DECL for static member variable, or TYPE_DECL for
233    alias template (needed by instantiate_decl).  */
234
235 static void
236 push_access_scope (tree t)
237 {
238   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
239               || TREE_CODE (t) == TYPE_DECL);
240
241   if (DECL_FRIEND_CONTEXT (t))
242     push_nested_class (DECL_FRIEND_CONTEXT (t));
243   else if (DECL_CLASS_SCOPE_P (t))
244     push_nested_class (DECL_CONTEXT (t));
245   else
246     push_to_top_level ();
247
248   if (TREE_CODE (t) == FUNCTION_DECL)
249     {
250       vec_safe_push (saved_access_scope, current_function_decl);
251       current_function_decl = t;
252     }
253 }
254
255 /* Restore the scope set up by push_access_scope.  T is the node we
256    are processing.  */
257
258 static void
259 pop_access_scope (tree t)
260 {
261   if (TREE_CODE (t) == FUNCTION_DECL)
262     current_function_decl = saved_access_scope->pop();
263
264   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
265     pop_nested_class ();
266   else
267     pop_from_top_level ();
268 }
269
270 /* Do any processing required when DECL (a member template
271    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
272    to DECL, unless it is a specialization, in which case the DECL
273    itself is returned.  */
274
275 tree
276 finish_member_template_decl (tree decl)
277 {
278   if (decl == error_mark_node)
279     return error_mark_node;
280
281   gcc_assert (DECL_P (decl));
282
283   if (TREE_CODE (decl) == TYPE_DECL)
284     {
285       tree type;
286
287       type = TREE_TYPE (decl);
288       if (type == error_mark_node)
289         return error_mark_node;
290       if (MAYBE_CLASS_TYPE_P (type)
291           && CLASSTYPE_TEMPLATE_INFO (type)
292           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
293         {
294           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
295           check_member_template (tmpl);
296           return tmpl;
297         }
298       return NULL_TREE;
299     }
300   else if (TREE_CODE (decl) == FIELD_DECL)
301     error ("data member %qD cannot be a member template", decl);
302   else if (DECL_TEMPLATE_INFO (decl))
303     {
304       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
305         {
306           check_member_template (DECL_TI_TEMPLATE (decl));
307           return DECL_TI_TEMPLATE (decl);
308         }
309       else
310         return decl;
311     }
312   else
313     error ("invalid member template declaration %qD", decl);
314
315   return error_mark_node;
316 }
317
318 /* Create a template info node.  */
319
320 tree
321 build_template_info (tree template_decl, tree template_args)
322 {
323   tree result = make_node (TEMPLATE_INFO);
324   TI_TEMPLATE (result) = template_decl;
325   TI_ARGS (result) = template_args;
326   return result;
327 }
328
329 /* Return the template info node corresponding to T, whatever T is.  */
330
331 tree
332 get_template_info (const_tree t)
333 {
334   tree tinfo = NULL_TREE;
335
336   if (!t || t == error_mark_node)
337     return NULL;
338
339   if (TREE_CODE (t) == NAMESPACE_DECL
340       || TREE_CODE (t) == PARM_DECL)
341     return NULL;
342
343   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
344     tinfo = DECL_TEMPLATE_INFO (t);
345
346   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
347     t = TREE_TYPE (t);
348
349   if (OVERLOAD_TYPE_P (t))
350     tinfo = TYPE_TEMPLATE_INFO (t);
351   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
352     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
353
354   return tinfo;
355 }
356
357 /* Returns the template nesting level of the indicated class TYPE.
358
359    For example, in:
360      template <class T>
361      struct A
362      {
363        template <class U>
364        struct B {};
365      };
366
367    A<T>::B<U> has depth two, while A<T> has depth one.
368    Both A<T>::B<int> and A<int>::B<U> have depth one, if
369    they are instantiations, not specializations.
370
371    This function is guaranteed to return 0 if passed NULL_TREE so
372    that, for example, `template_class_depth (current_class_type)' is
373    always safe.  */
374
375 int
376 template_class_depth (tree type)
377 {
378   int depth;
379
380   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
381     {
382       tree tinfo = get_template_info (type);
383
384       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
385           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
386         ++depth;
387
388       if (DECL_P (type))
389         type = CP_DECL_CONTEXT (type);
390       else if (LAMBDA_TYPE_P (type))
391         type = LAMBDA_TYPE_EXTRA_SCOPE (type);
392       else
393         type = CP_TYPE_CONTEXT (type);
394     }
395
396   return depth;
397 }
398
399 /* Return TRUE if NODE instantiates a template that has arguments of
400    its own, be it directly a primary template or indirectly through a
401    partial specializations.  */
402 static bool
403 instantiates_primary_template_p (tree node)
404 {
405   tree tinfo = get_template_info (node);
406   if (!tinfo)
407     return false;
408
409   tree tmpl = TI_TEMPLATE (tinfo);
410   if (PRIMARY_TEMPLATE_P (tmpl))
411     return true;
412
413   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
414     return false;
415
416   /* So now we know we have a specialization, but it could be a full
417      or a partial specialization.  To tell which, compare the depth of
418      its template arguments with those of its context.  */
419
420   tree ctxt = DECL_CONTEXT (tmpl);
421   tree ctinfo = get_template_info (ctxt);
422   if (!ctinfo)
423     return true;
424
425   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
426           > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
427 }
428
429 /* Subroutine of maybe_begin_member_template_processing.
430    Returns true if processing DECL needs us to push template parms.  */
431
432 static bool
433 inline_needs_template_parms (tree decl, bool nsdmi)
434 {
435   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
436     return false;
437
438   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
439           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
440 }
441
442 /* Subroutine of maybe_begin_member_template_processing.
443    Push the template parms in PARMS, starting from LEVELS steps into the
444    chain, and ending at the beginning, since template parms are listed
445    innermost first.  */
446
447 static void
448 push_inline_template_parms_recursive (tree parmlist, int levels)
449 {
450   tree parms = TREE_VALUE (parmlist);
451   int i;
452
453   if (levels > 1)
454     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
455
456   ++processing_template_decl;
457   current_template_parms
458     = tree_cons (size_int (processing_template_decl),
459                  parms, current_template_parms);
460   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
461
462   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
463                NULL);
464   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
465     {
466       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
467
468       if (error_operand_p (parm))
469         continue;
470
471       gcc_assert (DECL_P (parm));
472
473       switch (TREE_CODE (parm))
474         {
475         case TYPE_DECL:
476         case TEMPLATE_DECL:
477           pushdecl (parm);
478           break;
479
480         case PARM_DECL:
481           /* Push the CONST_DECL.  */
482           pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
483           break;
484
485         default:
486           gcc_unreachable ();
487         }
488     }
489 }
490
491 /* Restore the template parameter context for a member template, a
492    friend template defined in a class definition, or a non-template
493    member of template class.  */
494
495 void
496 maybe_begin_member_template_processing (tree decl)
497 {
498   tree parms;
499   int levels = 0;
500   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
501
502   if (nsdmi)
503     {
504       tree ctx = DECL_CONTEXT (decl);
505       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
506               /* Disregard full specializations (c++/60999).  */
507               && uses_template_parms (ctx)
508               ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
509     }
510
511   if (inline_needs_template_parms (decl, nsdmi))
512     {
513       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
514       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
515
516       if (DECL_TEMPLATE_SPECIALIZATION (decl))
517         {
518           --levels;
519           parms = TREE_CHAIN (parms);
520         }
521
522       push_inline_template_parms_recursive (parms, levels);
523     }
524
525   /* Remember how many levels of template parameters we pushed so that
526      we can pop them later.  */
527   inline_parm_levels.safe_push (levels);
528 }
529
530 /* Undo the effects of maybe_begin_member_template_processing.  */
531
532 void
533 maybe_end_member_template_processing (void)
534 {
535   int i;
536   int last;
537
538   if (inline_parm_levels.length () == 0)
539     return;
540
541   last = inline_parm_levels.pop ();
542   for (i = 0; i < last; ++i)
543     {
544       --processing_template_decl;
545       current_template_parms = TREE_CHAIN (current_template_parms);
546       poplevel (0, 0, 0);
547     }
548 }
549
550 /* Return a new template argument vector which contains all of ARGS,
551    but has as its innermost set of arguments the EXTRA_ARGS.  */
552
553 static tree
554 add_to_template_args (tree args, tree extra_args)
555 {
556   tree new_args;
557   int extra_depth;
558   int i;
559   int j;
560
561   if (args == NULL_TREE || extra_args == error_mark_node)
562     return extra_args;
563
564   extra_depth = TMPL_ARGS_DEPTH (extra_args);
565   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
566
567   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
568     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
569
570   for (j = 1; j <= extra_depth; ++j, ++i)
571     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
572
573   return new_args;
574 }
575
576 /* Like add_to_template_args, but only the outermost ARGS are added to
577    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
578    (EXTRA_ARGS) levels are added.  This function is used to combine
579    the template arguments from a partial instantiation with the
580    template arguments used to attain the full instantiation from the
581    partial instantiation.  */
582
583 static tree
584 add_outermost_template_args (tree args, tree extra_args)
585 {
586   tree new_args;
587
588   /* If there are more levels of EXTRA_ARGS than there are ARGS,
589      something very fishy is going on.  */
590   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
591
592   /* If *all* the new arguments will be the EXTRA_ARGS, just return
593      them.  */
594   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
595     return extra_args;
596
597   /* For the moment, we make ARGS look like it contains fewer levels.  */
598   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
599
600   new_args = add_to_template_args (args, extra_args);
601
602   /* Now, we restore ARGS to its full dimensions.  */
603   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
604
605   return new_args;
606 }
607
608 /* Return the N levels of innermost template arguments from the ARGS.  */
609
610 tree
611 get_innermost_template_args (tree args, int n)
612 {
613   tree new_args;
614   int extra_levels;
615   int i;
616
617   gcc_assert (n >= 0);
618
619   /* If N is 1, just return the innermost set of template arguments.  */
620   if (n == 1)
621     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
622
623   /* If we're not removing anything, just return the arguments we were
624      given.  */
625   extra_levels = TMPL_ARGS_DEPTH (args) - n;
626   gcc_assert (extra_levels >= 0);
627   if (extra_levels == 0)
628     return args;
629
630   /* Make a new set of arguments, not containing the outer arguments.  */
631   new_args = make_tree_vec (n);
632   for (i = 1; i <= n; ++i)
633     SET_TMPL_ARGS_LEVEL (new_args, i,
634                          TMPL_ARGS_LEVEL (args, i + extra_levels));
635
636   return new_args;
637 }
638
639 /* The inverse of get_innermost_template_args: Return all but the innermost
640    EXTRA_LEVELS levels of template arguments from the ARGS.  */
641
642 static tree
643 strip_innermost_template_args (tree args, int extra_levels)
644 {
645   tree new_args;
646   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
647   int i;
648
649   gcc_assert (n >= 0);
650
651   /* If N is 1, just return the outermost set of template arguments.  */
652   if (n == 1)
653     return TMPL_ARGS_LEVEL (args, 1);
654
655   /* If we're not removing anything, just return the arguments we were
656      given.  */
657   gcc_assert (extra_levels >= 0);
658   if (extra_levels == 0)
659     return args;
660
661   /* Make a new set of arguments, not containing the inner arguments.  */
662   new_args = make_tree_vec (n);
663   for (i = 1; i <= n; ++i)
664     SET_TMPL_ARGS_LEVEL (new_args, i,
665                          TMPL_ARGS_LEVEL (args, i));
666
667   return new_args;
668 }
669
670 /* We've got a template header coming up; push to a new level for storing
671    the parms.  */
672
673 void
674 begin_template_parm_list (void)
675 {
676   /* We use a non-tag-transparent scope here, which causes pushtag to
677      put tags in this scope, rather than in the enclosing class or
678      namespace scope.  This is the right thing, since we want
679      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
680      global template class, push_template_decl handles putting the
681      TEMPLATE_DECL into top-level scope.  For a nested template class,
682      e.g.:
683
684        template <class T> struct S1 {
685          template <class T> struct S2 {};
686        };
687
688      pushtag contains special code to insert the TEMPLATE_DECL for S2
689      at the right scope.  */
690   begin_scope (sk_template_parms, NULL);
691   ++processing_template_decl;
692   ++processing_template_parmlist;
693   note_template_header (0);
694
695   /* Add a dummy parameter level while we process the parameter list.  */
696   current_template_parms
697     = tree_cons (size_int (processing_template_decl),
698                  make_tree_vec (0),
699                  current_template_parms);
700 }
701
702 /* This routine is called when a specialization is declared.  If it is
703    invalid to declare a specialization here, an error is reported and
704    false is returned, otherwise this routine will return true.  */
705
706 static bool
707 check_specialization_scope (void)
708 {
709   tree scope = current_scope ();
710
711   /* [temp.expl.spec]
712
713      An explicit specialization shall be declared in the namespace of
714      which the template is a member, or, for member templates, in the
715      namespace of which the enclosing class or enclosing class
716      template is a member.  An explicit specialization of a member
717      function, member class or static data member of a class template
718      shall be declared in the namespace of which the class template
719      is a member.  */
720   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
721     {
722       error ("explicit specialization in non-namespace scope %qD", scope);
723       return false;
724     }
725
726   /* [temp.expl.spec]
727
728      In an explicit specialization declaration for a member of a class
729      template or a member template that appears in namespace scope,
730      the member template and some of its enclosing class templates may
731      remain unspecialized, except that the declaration shall not
732      explicitly specialize a class member template if its enclosing
733      class templates are not explicitly specialized as well.  */
734   if (current_template_parms)
735     {
736       error ("enclosing class templates are not explicitly specialized");
737       return false;
738     }
739
740   return true;
741 }
742
743 /* We've just seen template <>.  */
744
745 bool
746 begin_specialization (void)
747 {
748   begin_scope (sk_template_spec, NULL);
749   note_template_header (1);
750   return check_specialization_scope ();
751 }
752
753 /* Called at then end of processing a declaration preceded by
754    template<>.  */
755
756 void
757 end_specialization (void)
758 {
759   finish_scope ();
760   reset_specialization ();
761 }
762
763 /* Any template <>'s that we have seen thus far are not referring to a
764    function specialization.  */
765
766 void
767 reset_specialization (void)
768 {
769   processing_specialization = 0;
770   template_header_count = 0;
771 }
772
773 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
774    it was of the form template <>.  */
775
776 static void
777 note_template_header (int specialization)
778 {
779   processing_specialization = specialization;
780   template_header_count++;
781 }
782
783 /* We're beginning an explicit instantiation.  */
784
785 void
786 begin_explicit_instantiation (void)
787 {
788   gcc_assert (!processing_explicit_instantiation);
789   processing_explicit_instantiation = true;
790 }
791
792
793 void
794 end_explicit_instantiation (void)
795 {
796   gcc_assert (processing_explicit_instantiation);
797   processing_explicit_instantiation = false;
798 }
799
800 /* An explicit specialization or partial specialization of TMPL is being
801    declared.  Check that the namespace in which the specialization is
802    occurring is permissible.  Returns false iff it is invalid to
803    specialize TMPL in the current namespace.  */
804
805 static bool
806 check_specialization_namespace (tree tmpl)
807 {
808   tree tpl_ns = decl_namespace_context (tmpl);
809
810   /* [tmpl.expl.spec]
811
812      An explicit specialization shall be declared in a namespace enclosing the
813      specialized template. An explicit specialization whose declarator-id is
814      not qualified shall be declared in the nearest enclosing namespace of the
815      template, or, if the namespace is inline (7.3.1), any namespace from its
816      enclosing namespace set.  */
817   if (current_scope() != DECL_CONTEXT (tmpl)
818       && !at_namespace_scope_p ())
819     {
820       error ("specialization of %qD must appear at namespace scope", tmpl);
821       return false;
822     }
823
824   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
825     /* Same or enclosing namespace.  */
826     return true;
827   else
828     {
829       auto_diagnostic_group d;
830       if (permerror (input_location,
831                      "specialization of %qD in different namespace", tmpl))
832         inform (DECL_SOURCE_LOCATION (tmpl),
833                 "  from definition of %q#D", tmpl);
834       return false;
835     }
836 }
837
838 /* SPEC is an explicit instantiation.  Check that it is valid to
839    perform this explicit instantiation in the current namespace.  */
840
841 static void
842 check_explicit_instantiation_namespace (tree spec)
843 {
844   tree ns;
845
846   /* DR 275: An explicit instantiation shall appear in an enclosing
847      namespace of its template.  */
848   ns = decl_namespace_context (spec);
849   if (!is_nested_namespace (current_namespace, ns))
850     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
851                "(which does not enclose namespace %qD)",
852                spec, current_namespace, ns);
853 }
854
855 // Returns the type of a template specialization only if that
856 // specialization needs to be defined. Otherwise (e.g., if the type has
857 // already been defined), the function returns NULL_TREE.
858 static tree
859 maybe_new_partial_specialization (tree type)
860 {
861   // An implicit instantiation of an incomplete type implies
862   // the definition of a new class template.
863   //
864   //    template<typename T>
865   //      struct S;
866   //
867   //    template<typename T>
868   //      struct S<T*>;
869   //
870   // Here, S<T*> is an implicit instantiation of S whose type
871   // is incomplete.
872   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
873     return type;
874
875   // It can also be the case that TYPE is a completed specialization.
876   // Continuing the previous example, suppose we also declare:
877   //
878   //    template<typename T>
879   //      requires Integral<T>
880   //        struct S<T*>;
881   //
882   // Here, S<T*> refers to the specialization S<T*> defined
883   // above. However, we need to differentiate definitions because
884   // we intend to define a new partial specialization. In this case,
885   // we rely on the fact that the constraints are different for
886   // this declaration than that above.
887   //
888   // Note that we also get here for injected class names and
889   // late-parsed template definitions. We must ensure that we
890   // do not create new type declarations for those cases.
891   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
892     {
893       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
894       tree args = CLASSTYPE_TI_ARGS (type);
895
896       // If there are no template parameters, this cannot be a new
897       // partial template specializtion?
898       if (!current_template_parms)
899         return NULL_TREE;
900
901       // The injected-class-name is not a new partial specialization.
902       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
903         return NULL_TREE;
904
905       // If the constraints are not the same as those of the primary
906       // then, we can probably create a new specialization.
907       tree type_constr = current_template_constraints ();
908
909       if (type == TREE_TYPE (tmpl))
910         {
911           tree main_constr = get_constraints (tmpl);
912           if (equivalent_constraints (type_constr, main_constr))
913             return NULL_TREE;
914         }
915
916       // Also, if there's a pre-existing specialization with matching
917       // constraints, then this also isn't new.
918       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
919       while (specs)
920         {
921           tree spec_tmpl = TREE_VALUE (specs);
922           tree spec_args = TREE_PURPOSE (specs);
923           tree spec_constr = get_constraints (spec_tmpl);
924           if (comp_template_args (args, spec_args)
925               && equivalent_constraints (type_constr, spec_constr))
926             return NULL_TREE;
927           specs = TREE_CHAIN (specs);
928         }
929
930       // Create a new type node (and corresponding type decl)
931       // for the newly declared specialization.
932       tree t = make_class_type (TREE_CODE (type));
933       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
934       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
935
936       /* We only need a separate type node for storing the definition of this
937          partial specialization; uses of S<T*> are unconstrained, so all are
938          equivalent.  So keep TYPE_CANONICAL the same.  */
939       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
940
941       // Build the corresponding type decl.
942       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
943       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
944       DECL_SOURCE_LOCATION (d) = input_location;
945
946       return t;
947     }
948
949   return NULL_TREE;
950 }
951
952 /* The TYPE is being declared.  If it is a template type, that means it
953    is a partial specialization.  Do appropriate error-checking.  */
954
955 tree
956 maybe_process_partial_specialization (tree type)
957 {
958   tree context;
959
960   if (type == error_mark_node)
961     return error_mark_node;
962
963   /* A lambda that appears in specialization context is not itself a
964      specialization.  */
965   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
966     return type;
967
968   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
969     {
970       error ("name of class shadows template template parameter %qD",
971              TYPE_NAME (type));
972       return error_mark_node;
973     }
974
975   context = TYPE_CONTEXT (type);
976
977   if (TYPE_ALIAS_P (type))
978     {
979       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
980
981       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
982         error ("specialization of alias template %qD",
983                TI_TEMPLATE (tinfo));
984       else
985         error ("explicit specialization of non-template %qT", type);
986       return error_mark_node;
987     }
988   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
989     {
990       /* This is for ordinary explicit specialization and partial
991          specialization of a template class such as:
992
993            template <> class C<int>;
994
995          or:
996
997            template <class T> class C<T*>;
998
999          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1000
1001       if (tree t = maybe_new_partial_specialization (type))
1002         {
1003           if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1004               && !at_namespace_scope_p ())
1005             return error_mark_node;
1006           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1007           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1008           if (processing_template_decl)
1009             {
1010               tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1011               if (decl == error_mark_node)
1012                 return error_mark_node;
1013               return TREE_TYPE (decl);
1014             }
1015         }
1016       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1017         error ("specialization of %qT after instantiation", type);
1018       else if (errorcount && !processing_specialization
1019                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1020                && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1021         /* Trying to define a specialization either without a template<> header
1022            or in an inappropriate place.  We've already given an error, so just
1023            bail now so we don't actually define the specialization.  */
1024         return error_mark_node;
1025     }
1026   else if (CLASS_TYPE_P (type)
1027            && !CLASSTYPE_USE_TEMPLATE (type)
1028            && CLASSTYPE_TEMPLATE_INFO (type)
1029            && context && CLASS_TYPE_P (context)
1030            && CLASSTYPE_TEMPLATE_INFO (context))
1031     {
1032       /* This is for an explicit specialization of member class
1033          template according to [temp.expl.spec/18]:
1034
1035            template <> template <class U> class C<int>::D;
1036
1037          The context `C<int>' must be an implicit instantiation.
1038          Otherwise this is just a member class template declared
1039          earlier like:
1040
1041            template <> class C<int> { template <class U> class D; };
1042            template <> template <class U> class C<int>::D;
1043
1044          In the first case, `C<int>::D' is a specialization of `C<T>::D'
1045          while in the second case, `C<int>::D' is a primary template
1046          and `C<T>::D' may not exist.  */
1047
1048       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1049           && !COMPLETE_TYPE_P (type))
1050         {
1051           tree t;
1052           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1053
1054           if (current_namespace
1055               != decl_namespace_context (tmpl))
1056             {
1057               if (permerror (input_location,
1058                              "specialization of %qD in different namespace",
1059                              type))
1060                 inform (DECL_SOURCE_LOCATION (tmpl),
1061                         "from definition of %q#D", tmpl);
1062             }
1063
1064           /* Check for invalid specialization after instantiation:
1065
1066                template <> template <> class C<int>::D<int>;
1067                template <> template <class U> class C<int>::D;  */
1068
1069           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1070                t; t = TREE_CHAIN (t))
1071             {
1072               tree inst = TREE_VALUE (t);
1073               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1074                   || !COMPLETE_OR_OPEN_TYPE_P (inst))
1075                 {
1076                   /* We already have a full specialization of this partial
1077                      instantiation, or a full specialization has been
1078                      looked up but not instantiated.  Reassign it to the
1079                      new member specialization template.  */
1080                   spec_entry elt;
1081                   spec_entry *entry;
1082
1083                   elt.tmpl = most_general_template (tmpl);
1084                   elt.args = CLASSTYPE_TI_ARGS (inst);
1085                   elt.spec = inst;
1086
1087                   type_specializations->remove_elt (&elt);
1088
1089                   elt.tmpl = tmpl;
1090                   CLASSTYPE_TI_ARGS (inst)
1091                     = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1092
1093                   spec_entry **slot
1094                     = type_specializations->find_slot (&elt, INSERT);
1095                   entry = ggc_alloc<spec_entry> ();
1096                   *entry = elt;
1097                   *slot = entry;
1098                 }
1099               else
1100                 /* But if we've had an implicit instantiation, that's a
1101                    problem ([temp.expl.spec]/6).  */
1102                 error ("specialization %qT after instantiation %qT",
1103                        type, inst);
1104             }
1105
1106           /* Mark TYPE as a specialization.  And as a result, we only
1107              have one level of template argument for the innermost
1108              class template.  */
1109           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1110           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1111           CLASSTYPE_TI_ARGS (type)
1112             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1113         }
1114     }
1115   else if (processing_specialization)
1116     {
1117        /* Someday C++0x may allow for enum template specialization.  */
1118       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1119           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1120         pedwarn (input_location, OPT_Wpedantic, "template specialization "
1121                  "of %qD not allowed by ISO C++", type);
1122       else
1123         {
1124           error ("explicit specialization of non-template %qT", type);
1125           return error_mark_node;
1126         }
1127     }
1128
1129   return type;
1130 }
1131
1132 /* Returns nonzero if we can optimize the retrieval of specializations
1133    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1134    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1135
1136 static inline bool
1137 optimize_specialization_lookup_p (tree tmpl)
1138 {
1139   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1140           && DECL_CLASS_SCOPE_P (tmpl)
1141           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1142              parameter.  */
1143           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1144           /* The optimized lookup depends on the fact that the
1145              template arguments for the member function template apply
1146              purely to the containing class, which is not true if the
1147              containing class is an explicit or partial
1148              specialization.  */
1149           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1150           && !DECL_MEMBER_TEMPLATE_P (tmpl)
1151           && !DECL_CONV_FN_P (tmpl)
1152           /* It is possible to have a template that is not a member
1153              template and is not a member of a template class:
1154
1155              template <typename T>
1156              struct S { friend A::f(); };
1157
1158              Here, the friend function is a template, but the context does
1159              not have template information.  The optimized lookup relies
1160              on having ARGS be the template arguments for both the class
1161              and the function template.  */
1162           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1163 }
1164
1165 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1166    gone through coerce_template_parms by now.  */
1167
1168 static void
1169 verify_unstripped_args_1 (tree inner)
1170 {
1171   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1172     {
1173       tree arg = TREE_VEC_ELT (inner, i);
1174       if (TREE_CODE (arg) == TEMPLATE_DECL)
1175         /* OK */;
1176       else if (TYPE_P (arg))
1177         gcc_assert (strip_typedefs (arg, NULL) == arg);
1178       else if (ARGUMENT_PACK_P (arg))
1179         verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1180       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1181         /* Allow typedefs on the type of a non-type argument, since a
1182            parameter can have them.  */;
1183       else
1184         gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1185     }
1186 }
1187
1188 static void
1189 verify_unstripped_args (tree args)
1190 {
1191   ++processing_template_decl;
1192   if (!any_dependent_template_arguments_p (args))
1193     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1194   --processing_template_decl;
1195 }
1196
1197 /* Retrieve the specialization (in the sense of [temp.spec] - a
1198    specialization is either an instantiation or an explicit
1199    specialization) of TMPL for the given template ARGS.  If there is
1200    no such specialization, return NULL_TREE.  The ARGS are a vector of
1201    arguments, or a vector of vectors of arguments, in the case of
1202    templates with more than one level of parameters.
1203
1204    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1205    then we search for a partial specialization matching ARGS.  This
1206    parameter is ignored if TMPL is not a class template.
1207
1208    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1209    result is a NONTYPE_ARGUMENT_PACK.  */
1210
1211 static tree
1212 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1213 {
1214   if (tmpl == NULL_TREE)
1215     return NULL_TREE;
1216
1217   if (args == error_mark_node)
1218     return NULL_TREE;
1219
1220   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1221               || TREE_CODE (tmpl) == FIELD_DECL);
1222
1223   /* There should be as many levels of arguments as there are
1224      levels of parameters.  */
1225   gcc_assert (TMPL_ARGS_DEPTH (args)
1226               == (TREE_CODE (tmpl) == TEMPLATE_DECL
1227                   ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1228                   : template_class_depth (DECL_CONTEXT (tmpl))));
1229
1230   if (flag_checking)
1231     verify_unstripped_args (args);
1232
1233   /* Lambda functions in templates aren't instantiated normally, but through
1234      tsubst_lambda_expr.  */
1235   if (lambda_fn_in_template_p (tmpl))
1236     return NULL_TREE;
1237
1238   if (optimize_specialization_lookup_p (tmpl))
1239     {
1240       /* The template arguments actually apply to the containing
1241          class.  Find the class specialization with those
1242          arguments.  */
1243       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1244       tree class_specialization
1245         = retrieve_specialization (class_template, args, 0);
1246       if (!class_specialization)
1247         return NULL_TREE;
1248
1249       /* Find the instance of TMPL.  */
1250       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1251       for (ovl_iterator iter (fns); iter; ++iter)
1252         {
1253           tree fn = *iter;
1254           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1255               /* using-declarations can add base methods to the method vec,
1256                  and we don't want those here.  */
1257               && DECL_CONTEXT (fn) == class_specialization)
1258             return fn;
1259         }
1260       return NULL_TREE;
1261     }
1262   else
1263     {
1264       spec_entry *found;
1265       spec_entry elt;
1266       hash_table<spec_hasher> *specializations;
1267
1268       elt.tmpl = tmpl;
1269       elt.args = args;
1270       elt.spec = NULL_TREE;
1271
1272       if (DECL_CLASS_TEMPLATE_P (tmpl))
1273         specializations = type_specializations;
1274       else
1275         specializations = decl_specializations;
1276
1277       if (hash == 0)
1278         hash = spec_hasher::hash (&elt);
1279       found = specializations->find_with_hash (&elt, hash);
1280       if (found)
1281         return found->spec;
1282     }
1283
1284   return NULL_TREE;
1285 }
1286
1287 /* Like retrieve_specialization, but for local declarations.  */
1288
1289 tree
1290 retrieve_local_specialization (tree tmpl)
1291 {
1292   if (local_specializations == NULL)
1293     return NULL_TREE;
1294
1295   tree *slot = local_specializations->get (tmpl);
1296   return slot ? *slot : NULL_TREE;
1297 }
1298
1299 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1300
1301 int
1302 is_specialization_of (tree decl, tree tmpl)
1303 {
1304   tree t;
1305
1306   if (TREE_CODE (decl) == FUNCTION_DECL)
1307     {
1308       for (t = decl;
1309            t != NULL_TREE;
1310            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1311         if (t == tmpl)
1312           return 1;
1313     }
1314   else
1315     {
1316       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1317
1318       for (t = TREE_TYPE (decl);
1319            t != NULL_TREE;
1320            t = CLASSTYPE_USE_TEMPLATE (t)
1321              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1322         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1323           return 1;
1324     }
1325
1326   return 0;
1327 }
1328
1329 /* Returns nonzero iff DECL is a specialization of friend declaration
1330    FRIEND_DECL according to [temp.friend].  */
1331
1332 bool
1333 is_specialization_of_friend (tree decl, tree friend_decl)
1334 {
1335   bool need_template = true;
1336   int template_depth;
1337
1338   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1339               || TREE_CODE (decl) == TYPE_DECL);
1340
1341   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1342      of a template class, we want to check if DECL is a specialization
1343      if this.  */
1344   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1345       && DECL_TEMPLATE_INFO (friend_decl)
1346       && !DECL_USE_TEMPLATE (friend_decl))
1347     {
1348       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1349       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1350       need_template = false;
1351     }
1352   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1353            && !PRIMARY_TEMPLATE_P (friend_decl))
1354     need_template = false;
1355
1356   /* There is nothing to do if this is not a template friend.  */
1357   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1358     return false;
1359
1360   if (is_specialization_of (decl, friend_decl))
1361     return true;
1362
1363   /* [temp.friend/6]
1364      A member of a class template may be declared to be a friend of a
1365      non-template class.  In this case, the corresponding member of
1366      every specialization of the class template is a friend of the
1367      class granting friendship.
1368
1369      For example, given a template friend declaration
1370
1371        template <class T> friend void A<T>::f();
1372
1373      the member function below is considered a friend
1374
1375        template <> struct A<int> {
1376          void f();
1377        };
1378
1379      For this type of template friend, TEMPLATE_DEPTH below will be
1380      nonzero.  To determine if DECL is a friend of FRIEND, we first
1381      check if the enclosing class is a specialization of another.  */
1382
1383   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1384   if (template_depth
1385       && DECL_CLASS_SCOPE_P (decl)
1386       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1387                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1388     {
1389       /* Next, we check the members themselves.  In order to handle
1390          a few tricky cases, such as when FRIEND_DECL's are
1391
1392            template <class T> friend void A<T>::g(T t);
1393            template <class T> template <T t> friend void A<T>::h();
1394
1395          and DECL's are
1396
1397            void A<int>::g(int);
1398            template <int> void A<int>::h();
1399
1400          we need to figure out ARGS, the template arguments from
1401          the context of DECL.  This is required for template substitution
1402          of `T' in the function parameter of `g' and template parameter
1403          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1404
1405       tree context = DECL_CONTEXT (decl);
1406       tree args = NULL_TREE;
1407       int current_depth = 0;
1408
1409       while (current_depth < template_depth)
1410         {
1411           if (CLASSTYPE_TEMPLATE_INFO (context))
1412             {
1413               if (current_depth == 0)
1414                 args = TYPE_TI_ARGS (context);
1415               else
1416                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1417               current_depth++;
1418             }
1419           context = TYPE_CONTEXT (context);
1420         }
1421
1422       if (TREE_CODE (decl) == FUNCTION_DECL)
1423         {
1424           bool is_template;
1425           tree friend_type;
1426           tree decl_type;
1427           tree friend_args_type;
1428           tree decl_args_type;
1429
1430           /* Make sure that both DECL and FRIEND_DECL are templates or
1431              non-templates.  */
1432           is_template = DECL_TEMPLATE_INFO (decl)
1433                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1434           if (need_template ^ is_template)
1435             return false;
1436           else if (is_template)
1437             {
1438               /* If both are templates, check template parameter list.  */
1439               tree friend_parms
1440                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1441                                          args, tf_none);
1442               if (!comp_template_parms
1443                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1444                       friend_parms))
1445                 return false;
1446
1447               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1448             }
1449           else
1450             decl_type = TREE_TYPE (decl);
1451
1452           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1453                                               tf_none, NULL_TREE);
1454           if (friend_type == error_mark_node)
1455             return false;
1456
1457           /* Check if return types match.  */
1458           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1459             return false;
1460
1461           /* Check if function parameter types match, ignoring the
1462              `this' parameter.  */
1463           friend_args_type = TYPE_ARG_TYPES (friend_type);
1464           decl_args_type = TYPE_ARG_TYPES (decl_type);
1465           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1466             friend_args_type = TREE_CHAIN (friend_args_type);
1467           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1468             decl_args_type = TREE_CHAIN (decl_args_type);
1469
1470           return compparms (decl_args_type, friend_args_type);
1471         }
1472       else
1473         {
1474           /* DECL is a TYPE_DECL */
1475           bool is_template;
1476           tree decl_type = TREE_TYPE (decl);
1477
1478           /* Make sure that both DECL and FRIEND_DECL are templates or
1479              non-templates.  */
1480           is_template
1481             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1482               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1483
1484           if (need_template ^ is_template)
1485             return false;
1486           else if (is_template)
1487             {
1488               tree friend_parms;
1489               /* If both are templates, check the name of the two
1490                  TEMPLATE_DECL's first because is_friend didn't.  */
1491               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1492                   != DECL_NAME (friend_decl))
1493                 return false;
1494
1495               /* Now check template parameter list.  */
1496               friend_parms
1497                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1498                                          args, tf_none);
1499               return comp_template_parms
1500                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1501                  friend_parms);
1502             }
1503           else
1504             return (DECL_NAME (decl)
1505                     == DECL_NAME (friend_decl));
1506         }
1507     }
1508   return false;
1509 }
1510
1511 /* Register the specialization SPEC as a specialization of TMPL with
1512    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1513    is actually just a friend declaration.  ATTRLIST is the list of
1514    attributes that the specialization is declared with or NULL when
1515    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1516    available.
1517
1518    We also store instantiations of field packs in the hash table, even
1519    though they are not themselves templates, to make lookup easier.  */
1520
1521 static tree
1522 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1523                          hashval_t hash)
1524 {
1525   tree fn;
1526   spec_entry **slot = NULL;
1527   spec_entry elt;
1528
1529   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1530               || (TREE_CODE (tmpl) == FIELD_DECL
1531                   && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1532
1533   if (TREE_CODE (spec) == FUNCTION_DECL
1534       && uses_template_parms (DECL_TI_ARGS (spec)))
1535     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1536        register it; we want the corresponding TEMPLATE_DECL instead.
1537        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1538        the more obvious `uses_template_parms (spec)' to avoid problems
1539        with default function arguments.  In particular, given
1540        something like this:
1541
1542           template <class T> void f(T t1, T t = T())
1543
1544        the default argument expression is not substituted for in an
1545        instantiation unless and until it is actually needed.  */
1546     return spec;
1547
1548   if (optimize_specialization_lookup_p (tmpl))
1549     /* We don't put these specializations in the hash table, but we might
1550        want to give an error about a mismatch.  */
1551     fn = retrieve_specialization (tmpl, args, 0);
1552   else
1553     {
1554       elt.tmpl = tmpl;
1555       elt.args = args;
1556       elt.spec = spec;
1557
1558       if (hash == 0)
1559         hash = spec_hasher::hash (&elt);
1560
1561       slot =
1562         decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1563       if (*slot)
1564         fn = ((spec_entry *) *slot)->spec;
1565       else
1566         fn = NULL_TREE;
1567     }
1568
1569   /* We can sometimes try to re-register a specialization that we've
1570      already got.  In particular, regenerate_decl_from_template calls
1571      duplicate_decls which will update the specialization list.  But,
1572      we'll still get called again here anyhow.  It's more convenient
1573      to simply allow this than to try to prevent it.  */
1574   if (fn == spec)
1575     return spec;
1576   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1577     {
1578       if (DECL_TEMPLATE_INSTANTIATION (fn))
1579         {
1580           if (DECL_ODR_USED (fn)
1581               || DECL_EXPLICIT_INSTANTIATION (fn))
1582             {
1583               error ("specialization of %qD after instantiation",
1584                      fn);
1585               return error_mark_node;
1586             }
1587           else
1588             {
1589               tree clone;
1590               /* This situation should occur only if the first
1591                  specialization is an implicit instantiation, the
1592                  second is an explicit specialization, and the
1593                  implicit instantiation has not yet been used.  That
1594                  situation can occur if we have implicitly
1595                  instantiated a member function and then specialized
1596                  it later.
1597
1598                  We can also wind up here if a friend declaration that
1599                  looked like an instantiation turns out to be a
1600                  specialization:
1601
1602                    template <class T> void foo(T);
1603                    class S { friend void foo<>(int) };
1604                    template <> void foo(int);
1605
1606                  We transform the existing DECL in place so that any
1607                  pointers to it become pointers to the updated
1608                  declaration.
1609
1610                  If there was a definition for the template, but not
1611                  for the specialization, we want this to look as if
1612                  there were no definition, and vice versa.  */
1613               DECL_INITIAL (fn) = NULL_TREE;
1614               duplicate_decls (spec, fn, is_friend);
1615               /* The call to duplicate_decls will have applied
1616                  [temp.expl.spec]:
1617
1618                    An explicit specialization of a function template
1619                    is inline only if it is explicitly declared to be,
1620                    and independently of whether its function template
1621                    is.
1622
1623                 to the primary function; now copy the inline bits to
1624                 the various clones.  */
1625               FOR_EACH_CLONE (clone, fn)
1626                 {
1627                   DECL_DECLARED_INLINE_P (clone)
1628                     = DECL_DECLARED_INLINE_P (fn);
1629                   DECL_SOURCE_LOCATION (clone)
1630                     = DECL_SOURCE_LOCATION (fn);
1631                   DECL_DELETED_FN (clone)
1632                     = DECL_DELETED_FN (fn);
1633                 }
1634               check_specialization_namespace (tmpl);
1635
1636               return fn;
1637             }
1638         }
1639       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1640         {
1641           tree dd = duplicate_decls (spec, fn, is_friend);
1642           if (dd == error_mark_node)
1643             /* We've already complained in duplicate_decls.  */
1644             return error_mark_node;
1645
1646           if (dd == NULL_TREE && DECL_INITIAL (spec))
1647             /* Dup decl failed, but this is a new definition. Set the
1648                line number so any errors match this new
1649                definition.  */
1650             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1651
1652           return fn;
1653         }
1654     }
1655   else if (fn)
1656     return duplicate_decls (spec, fn, is_friend);
1657
1658   /* A specialization must be declared in the same namespace as the
1659      template it is specializing.  */
1660   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1661       && !check_specialization_namespace (tmpl))
1662     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1663
1664   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1665     {
1666       spec_entry *entry = ggc_alloc<spec_entry> ();
1667       gcc_assert (tmpl && args && spec);
1668       *entry = elt;
1669       *slot = entry;
1670       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1671            && PRIMARY_TEMPLATE_P (tmpl)
1672            && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1673           || variable_template_p (tmpl))
1674         /* If TMPL is a forward declaration of a template function, keep a list
1675            of all specializations in case we need to reassign them to a friend
1676            template later in tsubst_friend_function.
1677
1678            Also keep a list of all variable template instantiations so that
1679            process_partial_specialization can check whether a later partial
1680            specialization would have used it.  */
1681         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1682           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1683     }
1684
1685   return spec;
1686 }
1687
1688 /* Returns true iff two spec_entry nodes are equivalent.  */
1689
1690 int comparing_specializations;
1691
1692 bool
1693 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1694 {
1695   int equal;
1696
1697   ++comparing_specializations;
1698   equal = (e1->tmpl == e2->tmpl
1699            && comp_template_args (e1->args, e2->args));
1700   if (equal && flag_concepts
1701       /* tmpl could be a FIELD_DECL for a capture pack.  */
1702       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1703       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1704       && uses_template_parms (e1->args))
1705     {
1706       /* Partial specializations of a variable template can be distinguished by
1707          constraints.  */
1708       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1709       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1710       equal = equivalent_constraints (c1, c2);
1711     }
1712   --comparing_specializations;
1713
1714   return equal;
1715 }
1716
1717 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1718
1719 static hashval_t
1720 hash_tmpl_and_args (tree tmpl, tree args)
1721 {
1722   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1723   return iterative_hash_template_arg (args, val);
1724 }
1725
1726 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1727    ignoring SPEC.  */
1728
1729 hashval_t
1730 spec_hasher::hash (spec_entry *e)
1731 {
1732   return hash_tmpl_and_args (e->tmpl, e->args);
1733 }
1734
1735 /* Recursively calculate a hash value for a template argument ARG, for use
1736    in the hash tables of template specializations.  */
1737
1738 hashval_t
1739 iterative_hash_template_arg (tree arg, hashval_t val)
1740 {
1741   unsigned HOST_WIDE_INT i;
1742   enum tree_code code;
1743   char tclass;
1744
1745   if (arg == NULL_TREE)
1746     return iterative_hash_object (arg, val);
1747
1748   if (!TYPE_P (arg))
1749     STRIP_NOPS (arg);
1750
1751   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1752     gcc_unreachable ();
1753
1754   code = TREE_CODE (arg);
1755   tclass = TREE_CODE_CLASS (code);
1756
1757   val = iterative_hash_object (code, val);
1758
1759   switch (code)
1760     {
1761     case ERROR_MARK:
1762       return val;
1763
1764     case IDENTIFIER_NODE:
1765       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1766
1767     case TREE_VEC:
1768       {
1769         int i, len = TREE_VEC_LENGTH (arg);
1770         for (i = 0; i < len; ++i)
1771           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1772         return val;
1773       }
1774
1775     case TYPE_PACK_EXPANSION:
1776     case EXPR_PACK_EXPANSION:
1777       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1778       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1779
1780     case TYPE_ARGUMENT_PACK:
1781     case NONTYPE_ARGUMENT_PACK:
1782       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1783
1784     case TREE_LIST:
1785       for (; arg; arg = TREE_CHAIN (arg))
1786         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1787       return val;
1788
1789     case OVERLOAD:
1790       for (lkp_iterator iter (arg); iter; ++iter)
1791         val = iterative_hash_template_arg (*iter, val);
1792       return val;
1793
1794     case CONSTRUCTOR:
1795       {
1796         tree field, value;
1797         iterative_hash_template_arg (TREE_TYPE (arg), val);
1798         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1799           {
1800             val = iterative_hash_template_arg (field, val);
1801             val = iterative_hash_template_arg (value, val);
1802           }
1803         return val;
1804       }
1805
1806     case PARM_DECL:
1807       if (!DECL_ARTIFICIAL (arg))
1808         {
1809           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1810           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1811         }
1812       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1813
1814     case TARGET_EXPR:
1815       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1816
1817     case PTRMEM_CST:
1818       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1819       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1820
1821     case TEMPLATE_PARM_INDEX:
1822       val = iterative_hash_template_arg
1823         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1824       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1825       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1826
1827     case TRAIT_EXPR:
1828       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1829       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1830       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1831
1832     case BASELINK:
1833       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1834                                          val);
1835       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1836                                           val);
1837
1838     case MODOP_EXPR:
1839       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1840       code = TREE_CODE (TREE_OPERAND (arg, 1));
1841       val = iterative_hash_object (code, val);
1842       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1843
1844     case LAMBDA_EXPR:
1845       /* [temp.over.link] Two lambda-expressions are never considered
1846          equivalent.
1847
1848          So just hash the closure type.  */
1849       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1850
1851     case CAST_EXPR:
1852     case IMPLICIT_CONV_EXPR:
1853     case STATIC_CAST_EXPR:
1854     case REINTERPRET_CAST_EXPR:
1855     case CONST_CAST_EXPR:
1856     case DYNAMIC_CAST_EXPR:
1857     case NEW_EXPR:
1858       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1859       /* Now hash operands as usual.  */
1860       break;
1861
1862     case CALL_EXPR:
1863       {
1864         tree fn = CALL_EXPR_FN (arg);
1865         if (tree name = dependent_name (fn))
1866           {
1867             if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1868               val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1869             fn = name;
1870           }
1871         val = iterative_hash_template_arg (fn, val);
1872         call_expr_arg_iterator ai;
1873         for (tree x = first_call_expr_arg (arg, &ai); x;
1874              x = next_call_expr_arg (&ai))
1875           val = iterative_hash_template_arg (x, val);
1876         return val;
1877       }
1878
1879     default:
1880       break;
1881     }
1882
1883   switch (tclass)
1884     {
1885     case tcc_type:
1886       if (alias_template_specialization_p (arg))
1887         {
1888           // We want an alias specialization that survived strip_typedefs
1889           // to hash differently from its TYPE_CANONICAL, to avoid hash
1890           // collisions that compare as different in template_args_equal.
1891           // These could be dependent specializations that strip_typedefs
1892           // left alone, or untouched specializations because
1893           // coerce_template_parms returns the unconverted template
1894           // arguments if it sees incomplete argument packs.
1895           tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1896           return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1897         }
1898       if (TYPE_CANONICAL (arg))
1899         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1900                                       val);
1901       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1902         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1903       /* Otherwise just compare the types during lookup.  */
1904       return val;
1905
1906     case tcc_declaration:
1907     case tcc_constant:
1908       return iterative_hash_expr (arg, val);
1909
1910     default:
1911       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1912       {
1913         unsigned n = cp_tree_operand_length (arg);
1914         for (i = 0; i < n; ++i)
1915           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1916         return val;
1917       }
1918     }
1919   gcc_unreachable ();
1920   return 0;
1921 }
1922
1923 /* Unregister the specialization SPEC as a specialization of TMPL.
1924    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1925    if the SPEC was listed as a specialization of TMPL.
1926
1927    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1928
1929 bool
1930 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1931 {
1932   spec_entry *entry;
1933   spec_entry elt;
1934
1935   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1936   elt.args = TI_ARGS (tinfo);
1937   elt.spec = NULL_TREE;
1938
1939   entry = decl_specializations->find (&elt);
1940   if (entry != NULL)
1941     {
1942       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1943       gcc_assert (new_spec != NULL_TREE);
1944       entry->spec = new_spec;
1945       return 1;
1946     }
1947
1948   return 0;
1949 }
1950
1951 /* Like register_specialization, but for local declarations.  We are
1952    registering SPEC, an instantiation of TMPL.  */
1953
1954 void
1955 register_local_specialization (tree spec, tree tmpl)
1956 {
1957   gcc_assert (tmpl != spec);
1958   local_specializations->put (tmpl, spec);
1959 }
1960
1961 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1962    specialized class.  */
1963
1964 bool
1965 explicit_class_specialization_p (tree type)
1966 {
1967   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1968     return false;
1969   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1970 }
1971
1972 /* Print the list of functions at FNS, going through all the overloads
1973    for each element of the list.  Alternatively, FNS cannot be a
1974    TREE_LIST, in which case it will be printed together with all the
1975    overloads.
1976
1977    MORE and *STR should respectively be FALSE and NULL when the function
1978    is called from the outside.  They are used internally on recursive
1979    calls.  print_candidates manages the two parameters and leaves NULL
1980    in *STR when it ends.  */
1981
1982 static void
1983 print_candidates_1 (tree fns, char **str, bool more = false)
1984 {
1985   if (TREE_CODE (fns) == TREE_LIST)
1986     for (; fns; fns = TREE_CHAIN (fns))
1987       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1988   else
1989     for (lkp_iterator iter (fns); iter;)
1990       {
1991         tree cand = *iter;
1992         ++iter;
1993
1994         const char *pfx = *str;
1995         if (!pfx)
1996           {
1997             if (more || iter)
1998               pfx = _("candidates are:");
1999             else
2000               pfx = _("candidate is:");
2001             *str = get_spaces (pfx);
2002           }
2003         inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2004       }
2005 }
2006
2007 /* Print the list of candidate FNS in an error message.  FNS can also
2008    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2009
2010 void
2011 print_candidates (tree fns)
2012 {
2013   char *str = NULL;
2014   print_candidates_1 (fns, &str);
2015   free (str);
2016 }
2017
2018 /* Get a (possibly) constrained template declaration for the
2019    purpose of ordering candidates.  */
2020 static tree
2021 get_template_for_ordering (tree list)
2022 {
2023   gcc_assert (TREE_CODE (list) == TREE_LIST);
2024   tree f = TREE_VALUE (list);
2025   if (tree ti = DECL_TEMPLATE_INFO (f))
2026     return TI_TEMPLATE (ti);
2027   return f;
2028 }
2029
2030 /* Among candidates having the same signature, return the
2031    most constrained or NULL_TREE if there is no best candidate.
2032    If the signatures of candidates vary (e.g., template
2033    specialization vs. member function), then there can be no
2034    most constrained.
2035
2036    Note that we don't compare constraints on the functions
2037    themselves, but rather those of their templates. */
2038 static tree
2039 most_constrained_function (tree candidates)
2040 {
2041   // Try to find the best candidate in a first pass.
2042   tree champ = candidates;
2043   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2044     {
2045       int winner = more_constrained (get_template_for_ordering (champ),
2046                                      get_template_for_ordering (c));
2047       if (winner == -1)
2048         champ = c; // The candidate is more constrained
2049       else if (winner == 0)
2050         return NULL_TREE; // Neither is more constrained
2051     }
2052
2053   // Verify that the champ is better than previous candidates.
2054   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2055     if (!more_constrained (get_template_for_ordering (champ),
2056                            get_template_for_ordering (c)))
2057       return NULL_TREE;
2058   }
2059
2060   return champ;
2061 }
2062
2063
2064 /* Returns the template (one of the functions given by TEMPLATE_ID)
2065    which can be specialized to match the indicated DECL with the
2066    explicit template args given in TEMPLATE_ID.  The DECL may be
2067    NULL_TREE if none is available.  In that case, the functions in
2068    TEMPLATE_ID are non-members.
2069
2070    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2071    specialization of a member template.
2072
2073    The TEMPLATE_COUNT is the number of references to qualifying
2074    template classes that appeared in the name of the function. See
2075    check_explicit_specialization for a more accurate description.
2076
2077    TSK indicates what kind of template declaration (if any) is being
2078    declared.  TSK_TEMPLATE indicates that the declaration given by
2079    DECL, though a FUNCTION_DECL, has template parameters, and is
2080    therefore a template function.
2081
2082    The template args (those explicitly specified and those deduced)
2083    are output in a newly created vector *TARGS_OUT.
2084
2085    If it is impossible to determine the result, an error message is
2086    issued.  The error_mark_node is returned to indicate failure.  */
2087
2088 static tree
2089 determine_specialization (tree template_id,
2090                           tree decl,
2091                           tree* targs_out,
2092                           int need_member_template,
2093                           int template_count,
2094                           tmpl_spec_kind tsk)
2095 {
2096   tree fns;
2097   tree targs;
2098   tree explicit_targs;
2099   tree candidates = NULL_TREE;
2100
2101   /* A TREE_LIST of templates of which DECL may be a specialization.
2102      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2103      corresponding TREE_PURPOSE is the set of template arguments that,
2104      when used to instantiate the template, would produce a function
2105      with the signature of DECL.  */
2106   tree templates = NULL_TREE;
2107   int header_count;
2108   cp_binding_level *b;
2109
2110   *targs_out = NULL_TREE;
2111
2112   if (template_id == error_mark_node || decl == error_mark_node)
2113     return error_mark_node;
2114
2115   /* We shouldn't be specializing a member template of an
2116      unspecialized class template; we already gave an error in
2117      check_specialization_scope, now avoid crashing.  */
2118   if (!VAR_P (decl)
2119       && template_count && DECL_CLASS_SCOPE_P (decl)
2120       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2121     {
2122       gcc_assert (errorcount);
2123       return error_mark_node;
2124     }
2125
2126   fns = TREE_OPERAND (template_id, 0);
2127   explicit_targs = TREE_OPERAND (template_id, 1);
2128
2129   if (fns == error_mark_node)
2130     return error_mark_node;
2131
2132   /* Check for baselinks.  */
2133   if (BASELINK_P (fns))
2134     fns = BASELINK_FUNCTIONS (fns);
2135
2136   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2137     {
2138       error ("%qD is not a function template", fns);
2139       return error_mark_node;
2140     }
2141   else if (VAR_P (decl) && !variable_template_p (fns))
2142     {
2143       error ("%qD is not a variable template", fns);
2144       return error_mark_node;
2145     }
2146
2147   /* Count the number of template headers specified for this
2148      specialization.  */
2149   header_count = 0;
2150   for (b = current_binding_level;
2151        b->kind == sk_template_parms;
2152        b = b->level_chain)
2153     ++header_count;
2154
2155   tree orig_fns = fns;
2156
2157   if (variable_template_p (fns))
2158     {
2159       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2160       targs = coerce_template_parms (parms, explicit_targs, fns,
2161                                      tf_warning_or_error,
2162                                      /*req_all*/true, /*use_defarg*/true);
2163       if (targs != error_mark_node)
2164         templates = tree_cons (targs, fns, templates);
2165     }
2166   else for (lkp_iterator iter (fns); iter; ++iter)
2167     {
2168       tree fn = *iter;
2169
2170       if (TREE_CODE (fn) == TEMPLATE_DECL)
2171         {
2172           tree decl_arg_types;
2173           tree fn_arg_types;
2174           tree insttype;
2175
2176           /* In case of explicit specialization, we need to check if
2177              the number of template headers appearing in the specialization
2178              is correct. This is usually done in check_explicit_specialization,
2179              but the check done there cannot be exhaustive when specializing
2180              member functions. Consider the following code:
2181
2182              template <> void A<int>::f(int);
2183              template <> template <> void A<int>::f(int);
2184
2185              Assuming that A<int> is not itself an explicit specialization
2186              already, the first line specializes "f" which is a non-template
2187              member function, whilst the second line specializes "f" which
2188              is a template member function. So both lines are syntactically
2189              correct, and check_explicit_specialization does not reject
2190              them.
2191
2192              Here, we can do better, as we are matching the specialization
2193              against the declarations. We count the number of template
2194              headers, and we check if they match TEMPLATE_COUNT + 1
2195              (TEMPLATE_COUNT is the number of qualifying template classes,
2196              plus there must be another header for the member template
2197              itself).
2198
2199              Notice that if header_count is zero, this is not a
2200              specialization but rather a template instantiation, so there
2201              is no check we can perform here.  */
2202           if (header_count && header_count != template_count + 1)
2203             continue;
2204
2205           /* Check that the number of template arguments at the
2206              innermost level for DECL is the same as for FN.  */
2207           if (current_binding_level->kind == sk_template_parms
2208               && !current_binding_level->explicit_spec_p
2209               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2210                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2211                                       (current_template_parms))))
2212             continue;
2213
2214           /* DECL might be a specialization of FN.  */
2215           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2216           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2217
2218           /* For a non-static member function, we need to make sure
2219              that the const qualification is the same.  Since
2220              get_bindings does not try to merge the "this" parameter,
2221              we must do the comparison explicitly.  */
2222           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2223             {
2224               if (!same_type_p (TREE_VALUE (fn_arg_types),
2225                                 TREE_VALUE (decl_arg_types)))
2226                 continue;
2227
2228               /* And the ref-qualification.  */
2229               if (type_memfn_rqual (TREE_TYPE (decl))
2230                   != type_memfn_rqual (TREE_TYPE (fn)))
2231                 continue;
2232             }
2233
2234           /* Skip the "this" parameter and, for constructors of
2235              classes with virtual bases, the VTT parameter.  A
2236              full specialization of a constructor will have a VTT
2237              parameter, but a template never will.  */
2238           decl_arg_types
2239             = skip_artificial_parms_for (decl, decl_arg_types);
2240           fn_arg_types
2241             = skip_artificial_parms_for (fn, fn_arg_types);
2242
2243           /* Function templates cannot be specializations; there are
2244              no partial specializations of functions.  Therefore, if
2245              the type of DECL does not match FN, there is no
2246              match.
2247
2248              Note that it should never be the case that we have both
2249              candidates added here, and for regular member functions
2250              below. */
2251           if (tsk == tsk_template)
2252             {
2253               if (compparms (fn_arg_types, decl_arg_types))
2254                 candidates = tree_cons (NULL_TREE, fn, candidates);
2255               continue;
2256             }
2257
2258           /* See whether this function might be a specialization of this
2259              template.  Suppress access control because we might be trying
2260              to make this specialization a friend, and we have already done
2261              access control for the declaration of the specialization.  */
2262           push_deferring_access_checks (dk_no_check);
2263           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2264           pop_deferring_access_checks ();
2265
2266           if (!targs)
2267             /* We cannot deduce template arguments that when used to
2268                specialize TMPL will produce DECL.  */
2269             continue;
2270
2271           if (uses_template_parms (targs))
2272             /* We deduced something involving 'auto', which isn't a valid
2273                template argument.  */
2274             continue;
2275
2276           /* Remove, from the set of candidates, all those functions
2277              whose constraints are not satisfied. */
2278           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2279             continue;
2280
2281           // Then, try to form the new function type.
2282           insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2283           if (insttype == error_mark_node)
2284             continue;
2285           fn_arg_types
2286             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2287           if (!compparms (fn_arg_types, decl_arg_types))
2288             continue;
2289
2290           /* Save this template, and the arguments deduced.  */
2291           templates = tree_cons (targs, fn, templates);
2292         }
2293       else if (need_member_template)
2294         /* FN is an ordinary member function, and we need a
2295            specialization of a member template.  */
2296         ;
2297       else if (TREE_CODE (fn) != FUNCTION_DECL)
2298         /* We can get IDENTIFIER_NODEs here in certain erroneous
2299            cases.  */
2300         ;
2301       else if (!DECL_FUNCTION_MEMBER_P (fn))
2302         /* This is just an ordinary non-member function.  Nothing can
2303            be a specialization of that.  */
2304         ;
2305       else if (DECL_ARTIFICIAL (fn))
2306         /* Cannot specialize functions that are created implicitly.  */
2307         ;
2308       else
2309         {
2310           tree decl_arg_types;
2311
2312           /* This is an ordinary member function.  However, since
2313              we're here, we can assume its enclosing class is a
2314              template class.  For example,
2315
2316                template <typename T> struct S { void f(); };
2317                template <> void S<int>::f() {}
2318
2319              Here, S<int>::f is a non-template, but S<int> is a
2320              template class.  If FN has the same type as DECL, we
2321              might be in business.  */
2322
2323           if (!DECL_TEMPLATE_INFO (fn))
2324             /* Its enclosing class is an explicit specialization
2325                of a template class.  This is not a candidate.  */
2326             continue;
2327
2328           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2329                             TREE_TYPE (TREE_TYPE (fn))))
2330             /* The return types differ.  */
2331             continue;
2332
2333           /* Adjust the type of DECL in case FN is a static member.  */
2334           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2335           if (DECL_STATIC_FUNCTION_P (fn)
2336               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2337             decl_arg_types = TREE_CHAIN (decl_arg_types);
2338
2339           if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2340                          decl_arg_types))
2341             continue;
2342
2343           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2344               && (type_memfn_rqual (TREE_TYPE (decl))
2345                   != type_memfn_rqual (TREE_TYPE (fn))))
2346             continue;
2347
2348           // If the deduced arguments do not satisfy the constraints,
2349           // this is not a candidate.
2350           if (flag_concepts && !constraints_satisfied_p (fn))
2351             continue;
2352
2353           // Add the candidate.
2354           candidates = tree_cons (NULL_TREE, fn, candidates);
2355         }
2356     }
2357
2358   if (templates && TREE_CHAIN (templates))
2359     {
2360       /* We have:
2361
2362            [temp.expl.spec]
2363
2364            It is possible for a specialization with a given function
2365            signature to be instantiated from more than one function
2366            template.  In such cases, explicit specification of the
2367            template arguments must be used to uniquely identify the
2368            function template specialization being specialized.
2369
2370          Note that here, there's no suggestion that we're supposed to
2371          determine which of the candidate templates is most
2372          specialized.  However, we, also have:
2373
2374            [temp.func.order]
2375
2376            Partial ordering of overloaded function template
2377            declarations is used in the following contexts to select
2378            the function template to which a function template
2379            specialization refers:
2380
2381            -- when an explicit specialization refers to a function
2382               template.
2383
2384          So, we do use the partial ordering rules, at least for now.
2385          This extension can only serve to make invalid programs valid,
2386          so it's safe.  And, there is strong anecdotal evidence that
2387          the committee intended the partial ordering rules to apply;
2388          the EDG front end has that behavior, and John Spicer claims
2389          that the committee simply forgot to delete the wording in
2390          [temp.expl.spec].  */
2391       tree tmpl = most_specialized_instantiation (templates);
2392       if (tmpl != error_mark_node)
2393         {
2394           templates = tmpl;
2395           TREE_CHAIN (templates) = NULL_TREE;
2396         }
2397     }
2398
2399   // Concepts allows multiple declarations of member functions
2400   // with the same signature. Like above, we need to rely on
2401   // on the partial ordering of those candidates to determine which
2402   // is the best.
2403   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2404     {
2405       if (tree cand = most_constrained_function (candidates))
2406         {
2407           candidates = cand;
2408           TREE_CHAIN (cand) = NULL_TREE;
2409         }
2410     }
2411
2412   if (templates == NULL_TREE && candidates == NULL_TREE)
2413     {
2414       error ("template-id %qD for %q+D does not match any template "
2415              "declaration", template_id, decl);
2416       if (header_count && header_count != template_count + 1)
2417         inform (input_location, "saw %d %<template<>%>, need %d for "
2418                 "specializing a member function template",
2419                 header_count, template_count + 1);
2420       else
2421         print_candidates (orig_fns);
2422       return error_mark_node;
2423     }
2424   else if ((templates && TREE_CHAIN (templates))
2425            || (candidates && TREE_CHAIN (candidates))
2426            || (templates && candidates))
2427     {
2428       error ("ambiguous template specialization %qD for %q+D",
2429              template_id, decl);
2430       candidates = chainon (candidates, templates);
2431       print_candidates (candidates);
2432       return error_mark_node;
2433     }
2434
2435   /* We have one, and exactly one, match.  */
2436   if (candidates)
2437     {
2438       tree fn = TREE_VALUE (candidates);
2439       *targs_out = copy_node (DECL_TI_ARGS (fn));
2440
2441       // Propagate the candidate's constraints to the declaration.
2442       set_constraints (decl, get_constraints (fn));
2443
2444       /* DECL is a re-declaration or partial instantiation of a template
2445          function.  */
2446       if (TREE_CODE (fn) == TEMPLATE_DECL)
2447         return fn;
2448       /* It was a specialization of an ordinary member function in a
2449          template class.  */
2450       return DECL_TI_TEMPLATE (fn);
2451     }
2452
2453   /* It was a specialization of a template.  */
2454   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2455   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2456     {
2457       *targs_out = copy_node (targs);
2458       SET_TMPL_ARGS_LEVEL (*targs_out,
2459                            TMPL_ARGS_DEPTH (*targs_out),
2460                            TREE_PURPOSE (templates));
2461     }
2462   else
2463     *targs_out = TREE_PURPOSE (templates);
2464   return TREE_VALUE (templates);
2465 }
2466
2467 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2468    but with the default argument values filled in from those in the
2469    TMPL_TYPES.  */
2470
2471 static tree
2472 copy_default_args_to_explicit_spec_1 (tree spec_types,
2473                                       tree tmpl_types)
2474 {
2475   tree new_spec_types;
2476
2477   if (!spec_types)
2478     return NULL_TREE;
2479
2480   if (spec_types == void_list_node)
2481     return void_list_node;
2482
2483   /* Substitute into the rest of the list.  */
2484   new_spec_types =
2485     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2486                                           TREE_CHAIN (tmpl_types));
2487
2488   /* Add the default argument for this parameter.  */
2489   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2490                          TREE_VALUE (spec_types),
2491                          new_spec_types);
2492 }
2493
2494 /* DECL is an explicit specialization.  Replicate default arguments
2495    from the template it specializes.  (That way, code like:
2496
2497      template <class T> void f(T = 3);
2498      template <> void f(double);
2499      void g () { f (); }
2500
2501    works, as required.)  An alternative approach would be to look up
2502    the correct default arguments at the call-site, but this approach
2503    is consistent with how implicit instantiations are handled.  */
2504
2505 static void
2506 copy_default_args_to_explicit_spec (tree decl)
2507 {
2508   tree tmpl;
2509   tree spec_types;
2510   tree tmpl_types;
2511   tree new_spec_types;
2512   tree old_type;
2513   tree new_type;
2514   tree t;
2515   tree object_type = NULL_TREE;
2516   tree in_charge = NULL_TREE;
2517   tree vtt = NULL_TREE;
2518
2519   /* See if there's anything we need to do.  */
2520   tmpl = DECL_TI_TEMPLATE (decl);
2521   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2522   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2523     if (TREE_PURPOSE (t))
2524       break;
2525   if (!t)
2526     return;
2527
2528   old_type = TREE_TYPE (decl);
2529   spec_types = TYPE_ARG_TYPES (old_type);
2530
2531   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2532     {
2533       /* Remove the this pointer, but remember the object's type for
2534          CV quals.  */
2535       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2536       spec_types = TREE_CHAIN (spec_types);
2537       tmpl_types = TREE_CHAIN (tmpl_types);
2538
2539       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2540         {
2541           /* DECL may contain more parameters than TMPL due to the extra
2542              in-charge parameter in constructors and destructors.  */
2543           in_charge = spec_types;
2544           spec_types = TREE_CHAIN (spec_types);
2545         }
2546       if (DECL_HAS_VTT_PARM_P (decl))
2547         {
2548           vtt = spec_types;
2549           spec_types = TREE_CHAIN (spec_types);
2550         }
2551     }
2552
2553   /* Compute the merged default arguments.  */
2554   new_spec_types =
2555     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2556
2557   /* Compute the new FUNCTION_TYPE.  */
2558   if (object_type)
2559     {
2560       if (vtt)
2561         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2562                                          TREE_VALUE (vtt),
2563                                          new_spec_types);
2564
2565       if (in_charge)
2566         /* Put the in-charge parameter back.  */
2567         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2568                                          TREE_VALUE (in_charge),
2569                                          new_spec_types);
2570
2571       new_type = build_method_type_directly (object_type,
2572                                              TREE_TYPE (old_type),
2573                                              new_spec_types);
2574     }
2575   else
2576     new_type = build_function_type (TREE_TYPE (old_type),
2577                                     new_spec_types);
2578   new_type = cp_build_type_attribute_variant (new_type,
2579                                               TYPE_ATTRIBUTES (old_type));
2580   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2581
2582   TREE_TYPE (decl) = new_type;
2583 }
2584
2585 /* Return the number of template headers we expect to see for a definition
2586    or specialization of CTYPE or one of its non-template members.  */
2587
2588 int
2589 num_template_headers_for_class (tree ctype)
2590 {
2591   int num_templates = 0;
2592
2593   while (ctype && CLASS_TYPE_P (ctype))
2594     {
2595       /* You're supposed to have one `template <...>' for every
2596          template class, but you don't need one for a full
2597          specialization.  For example:
2598
2599          template <class T> struct S{};
2600          template <> struct S<int> { void f(); };
2601          void S<int>::f () {}
2602
2603          is correct; there shouldn't be a `template <>' for the
2604          definition of `S<int>::f'.  */
2605       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2606         /* If CTYPE does not have template information of any
2607            kind,  then it is not a template, nor is it nested
2608            within a template.  */
2609         break;
2610       if (explicit_class_specialization_p (ctype))
2611         break;
2612       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2613         ++num_templates;
2614
2615       ctype = TYPE_CONTEXT (ctype);
2616     }
2617
2618   return num_templates;
2619 }
2620
2621 /* Do a simple sanity check on the template headers that precede the
2622    variable declaration DECL.  */
2623
2624 void
2625 check_template_variable (tree decl)
2626 {
2627   tree ctx = CP_DECL_CONTEXT (decl);
2628   int wanted = num_template_headers_for_class (ctx);
2629   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2630       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2631     {
2632       if (cxx_dialect < cxx14)
2633         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2634                  "variable templates only available with "
2635                  "%<-std=c++14%> or %<-std=gnu++14%>");
2636
2637       // Namespace-scope variable templates should have a template header.
2638       ++wanted;
2639     }
2640   if (template_header_count > wanted)
2641     {
2642       auto_diagnostic_group d;
2643       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2644                              "too many template headers for %qD "
2645                              "(should be %d)",
2646                              decl, wanted);
2647       if (warned && CLASS_TYPE_P (ctx)
2648           && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2649         inform (DECL_SOURCE_LOCATION (decl),
2650                 "members of an explicitly specialized class are defined "
2651                 "without a template header");
2652     }
2653 }
2654
2655 /* An explicit specialization whose declarator-id or class-head-name is not
2656    qualified shall be declared in the nearest enclosing namespace of the
2657    template, or, if the namespace is inline (7.3.1), any namespace from its
2658    enclosing namespace set.
2659
2660    If the name declared in the explicit instantiation is an unqualified name,
2661    the explicit instantiation shall appear in the namespace where its template
2662    is declared or, if that namespace is inline (7.3.1), any namespace from its
2663    enclosing namespace set.  */
2664
2665 void
2666 check_unqualified_spec_or_inst (tree t, location_t loc)
2667 {
2668   tree tmpl = most_general_template (t);
2669   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2670       && !is_nested_namespace (current_namespace,
2671                                CP_DECL_CONTEXT (tmpl), true))
2672     {
2673       if (processing_specialization)
2674         permerror (loc, "explicit specialization of %qD outside its "
2675                    "namespace must use a nested-name-specifier", tmpl);
2676       else if (processing_explicit_instantiation
2677                && cxx_dialect >= cxx11)
2678         /* This was allowed in C++98, so only pedwarn.  */
2679         pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2680                  "outside its namespace must use a nested-name-"
2681                  "specifier", tmpl);
2682     }
2683 }
2684
2685 /* Warn for a template specialization SPEC that is missing some of a set
2686    of function or type attributes that the template TEMPL is declared with.
2687    ATTRLIST is a list of additional attributes that SPEC should be taken
2688    to ultimately be declared with.  */
2689
2690 static void
2691 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2692 {
2693   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2694     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2695
2696   /* Avoid warning if the difference between the primary and
2697      the specialization is not in one of the attributes below.  */
2698   const char* const blacklist[] = {
2699     "alloc_align", "alloc_size", "assume_aligned", "format",
2700     "format_arg", "malloc", "nonnull", NULL
2701   };
2702
2703   /* Put together a list of the black listed attributes that the primary
2704      template is declared with that the specialization is not, in case
2705      it's not apparent from the most recent declaration of the primary.  */
2706   pretty_printer str;
2707   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2708                                                  blacklist, &str);
2709
2710   if (!nattrs)
2711     return;
2712
2713   auto_diagnostic_group d;
2714   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2715                   "explicit specialization %q#D may be missing attributes",
2716                   spec))
2717     inform (DECL_SOURCE_LOCATION (tmpl),
2718             nattrs > 1
2719             ? G_("missing primary template attributes %s")
2720             : G_("missing primary template attribute %s"),
2721             pp_formatted_text (&str));
2722 }
2723
2724 /* Check to see if the function just declared, as indicated in
2725    DECLARATOR, and in DECL, is a specialization of a function
2726    template.  We may also discover that the declaration is an explicit
2727    instantiation at this point.
2728
2729    Returns DECL, or an equivalent declaration that should be used
2730    instead if all goes well.  Issues an error message if something is
2731    amiss.  Returns error_mark_node if the error is not easily
2732    recoverable.
2733
2734    FLAGS is a bitmask consisting of the following flags:
2735
2736    2: The function has a definition.
2737    4: The function is a friend.
2738
2739    The TEMPLATE_COUNT is the number of references to qualifying
2740    template classes that appeared in the name of the function.  For
2741    example, in
2742
2743      template <class T> struct S { void f(); };
2744      void S<int>::f();
2745
2746    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2747    classes are not counted in the TEMPLATE_COUNT, so that in
2748
2749      template <class T> struct S {};
2750      template <> struct S<int> { void f(); }
2751      template <> void S<int>::f();
2752
2753    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2754    invalid; there should be no template <>.)
2755
2756    If the function is a specialization, it is marked as such via
2757    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2758    is set up correctly, and it is added to the list of specializations
2759    for that template.  */
2760
2761 tree
2762 check_explicit_specialization (tree declarator,
2763                                tree decl,
2764                                int template_count,
2765                                int flags,
2766                                tree attrlist)
2767 {
2768   int have_def = flags & 2;
2769   int is_friend = flags & 4;
2770   bool is_concept = flags & 8;
2771   int specialization = 0;
2772   int explicit_instantiation = 0;
2773   int member_specialization = 0;
2774   tree ctype = DECL_CLASS_CONTEXT (decl);
2775   tree dname = DECL_NAME (decl);
2776   tmpl_spec_kind tsk;
2777
2778   if (is_friend)
2779     {
2780       if (!processing_specialization)
2781         tsk = tsk_none;
2782       else
2783         tsk = tsk_excessive_parms;
2784     }
2785   else
2786     tsk = current_tmpl_spec_kind (template_count);
2787
2788   switch (tsk)
2789     {
2790     case tsk_none:
2791       if (processing_specialization && !VAR_P (decl))
2792         {
2793           specialization = 1;
2794           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2795         }
2796       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2797         {
2798           if (is_friend)
2799             /* This could be something like:
2800
2801                template <class T> void f(T);
2802                class S { friend void f<>(int); }  */
2803             specialization = 1;
2804           else
2805             {
2806               /* This case handles bogus declarations like template <>
2807                  template <class T> void f<int>(); */
2808
2809               error ("template-id %qD in declaration of primary template",
2810                      declarator);
2811               return decl;
2812             }
2813         }
2814       break;
2815
2816     case tsk_invalid_member_spec:
2817       /* The error has already been reported in
2818          check_specialization_scope.  */
2819       return error_mark_node;
2820
2821     case tsk_invalid_expl_inst:
2822       error ("template parameter list used in explicit instantiation");
2823
2824       /* Fall through.  */
2825
2826     case tsk_expl_inst:
2827       if (have_def)
2828         error ("definition provided for explicit instantiation");
2829
2830       explicit_instantiation = 1;
2831       break;
2832
2833     case tsk_excessive_parms:
2834     case tsk_insufficient_parms:
2835       if (tsk == tsk_excessive_parms)
2836         error ("too many template parameter lists in declaration of %qD",
2837                decl);
2838       else if (template_header_count)
2839         error("too few template parameter lists in declaration of %qD", decl);
2840       else
2841         error("explicit specialization of %qD must be introduced by "
2842               "%<template <>%>", decl);
2843
2844       /* Fall through.  */
2845     case tsk_expl_spec:
2846       if (is_concept)
2847         error ("explicit specialization declared %<concept%>");
2848
2849       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2850         /* In cases like template<> constexpr bool v = true;
2851            We'll give an error in check_template_variable.  */
2852         break;
2853
2854       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2855       if (ctype)
2856         member_specialization = 1;
2857       else
2858         specialization = 1;
2859       break;
2860
2861     case tsk_template:
2862       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2863         {
2864           /* This case handles bogus declarations like template <>
2865              template <class T> void f<int>(); */
2866
2867           if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2868             error ("template-id %qD in declaration of primary template",
2869                    declarator);
2870           else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2871             {
2872               /* Partial specialization of variable template.  */
2873               SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2874               specialization = 1;
2875               goto ok;
2876             }
2877           else if (cxx_dialect < cxx14)
2878             error ("non-type partial specialization %qD "
2879                    "is not allowed", declarator);
2880           else
2881             error ("non-class, non-variable partial specialization %qD "
2882                    "is not allowed", declarator);
2883           return decl;
2884         ok:;
2885         }
2886
2887       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2888         /* This is a specialization of a member template, without
2889            specialization the containing class.  Something like:
2890
2891              template <class T> struct S {
2892                template <class U> void f (U);
2893              };
2894              template <> template <class U> void S<int>::f(U) {}
2895
2896            That's a specialization -- but of the entire template.  */
2897         specialization = 1;
2898       break;
2899
2900     default:
2901       gcc_unreachable ();
2902     }
2903
2904   if ((specialization || member_specialization)
2905       /* This doesn't apply to variable templates.  */
2906       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2907     {
2908       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2909       for (; t; t = TREE_CHAIN (t))
2910         if (TREE_PURPOSE (t))
2911           {
2912             permerror (input_location,
2913                        "default argument specified in explicit specialization");
2914             break;
2915           }
2916     }
2917
2918   if (specialization || member_specialization || explicit_instantiation)
2919     {
2920       tree tmpl = NULL_TREE;
2921       tree targs = NULL_TREE;
2922       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2923
2924       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2925       if (!was_template_id)
2926         {
2927           tree fns;
2928
2929           gcc_assert (identifier_p (declarator));
2930           if (ctype)
2931             fns = dname;
2932           else
2933             {
2934               /* If there is no class context, the explicit instantiation
2935                  must be at namespace scope.  */
2936               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2937
2938               /* Find the namespace binding, using the declaration
2939                  context.  */
2940               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2941                                            false, true);
2942               if (fns == error_mark_node)
2943                 /* If lookup fails, look for a friend declaration so we can
2944                    give a better diagnostic.  */
2945                 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2946                                              /*type*/false, /*complain*/true,
2947                                              /*hidden*/true);
2948
2949               if (fns == error_mark_node || !is_overloaded_fn (fns))
2950                 {
2951                   error ("%qD is not a template function", dname);
2952                   fns = error_mark_node;
2953                 }
2954             }
2955
2956           declarator = lookup_template_function (fns, NULL_TREE);
2957         }
2958
2959       if (declarator == error_mark_node)
2960         return error_mark_node;
2961
2962       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2963         {
2964           if (!explicit_instantiation)
2965             /* A specialization in class scope.  This is invalid,
2966                but the error will already have been flagged by
2967                check_specialization_scope.  */
2968             return error_mark_node;
2969           else
2970             {
2971               /* It's not valid to write an explicit instantiation in
2972                  class scope, e.g.:
2973
2974                    class C { template void f(); }
2975
2976                    This case is caught by the parser.  However, on
2977                    something like:
2978
2979                    template class C { void f(); };
2980
2981                    (which is invalid) we can get here.  The error will be
2982                    issued later.  */
2983               ;
2984             }
2985
2986           return decl;
2987         }
2988       else if (ctype != NULL_TREE
2989                && (identifier_p (TREE_OPERAND (declarator, 0))))
2990         {
2991           // We'll match variable templates in start_decl.
2992           if (VAR_P (decl))
2993             return decl;
2994
2995           /* Find the list of functions in ctype that have the same
2996              name as the declared function.  */
2997           tree name = TREE_OPERAND (declarator, 0);
2998
2999           if (constructor_name_p (name, ctype))
3000             {
3001               if (DECL_CONSTRUCTOR_P (decl)
3002                   ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3003                   : !CLASSTYPE_DESTRUCTOR (ctype))
3004                 {
3005                   /* From [temp.expl.spec]:
3006
3007                      If such an explicit specialization for the member
3008                      of a class template names an implicitly-declared
3009                      special member function (clause _special_), the
3010                      program is ill-formed.
3011
3012                      Similar language is found in [temp.explicit].  */
3013                   error ("specialization of implicitly-declared special member function");
3014                   return error_mark_node;
3015                 }
3016
3017               name = DECL_NAME (decl);
3018             }
3019
3020           /* For a type-conversion operator, We might be looking for
3021              `operator int' which will be a specialization of
3022              `operator T'.  Grab all the conversion operators, and
3023              then select from them.  */
3024           tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3025                                         ? conv_op_identifier : name);
3026
3027           if (fns == NULL_TREE)
3028             {
3029               error ("no member function %qD declared in %qT", name, ctype);
3030               return error_mark_node;
3031             }
3032           else
3033             TREE_OPERAND (declarator, 0) = fns;
3034         }
3035
3036       /* Figure out what exactly is being specialized at this point.
3037          Note that for an explicit instantiation, even one for a
3038          member function, we cannot tell a priori whether the
3039          instantiation is for a member template, or just a member
3040          function of a template class.  Even if a member template is
3041          being instantiated, the member template arguments may be
3042          elided if they can be deduced from the rest of the
3043          declaration.  */
3044       tmpl = determine_specialization (declarator, decl,
3045                                        &targs,
3046                                        member_specialization,
3047                                        template_count,
3048                                        tsk);
3049
3050       if (!tmpl || tmpl == error_mark_node)
3051         /* We couldn't figure out what this declaration was
3052            specializing.  */
3053         return error_mark_node;
3054       else
3055         {
3056           if (TREE_CODE (decl) == FUNCTION_DECL
3057               && DECL_HIDDEN_FRIEND_P (tmpl))
3058             {
3059               auto_diagnostic_group d;
3060               if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3061                            "friend declaration %qD is not visible to "
3062                            "explicit specialization", tmpl))
3063                 inform (DECL_SOURCE_LOCATION (tmpl),
3064                         "friend declaration here");
3065             }
3066           else if (!ctype && !is_friend
3067                    && CP_DECL_CONTEXT (decl) == current_namespace)
3068             check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3069
3070           tree gen_tmpl = most_general_template (tmpl);
3071
3072           if (explicit_instantiation)
3073             {
3074               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3075                  is done by do_decl_instantiation later.  */
3076
3077               int arg_depth = TMPL_ARGS_DEPTH (targs);
3078               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3079
3080               if (arg_depth > parm_depth)
3081                 {
3082                   /* If TMPL is not the most general template (for
3083                      example, if TMPL is a friend template that is
3084                      injected into namespace scope), then there will
3085                      be too many levels of TARGS.  Remove some of them
3086                      here.  */
3087                   int i;
3088                   tree new_targs;
3089
3090                   new_targs = make_tree_vec (parm_depth);
3091                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3092                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3093                       = TREE_VEC_ELT (targs, i);
3094                   targs = new_targs;
3095                 }
3096
3097               return instantiate_template (tmpl, targs, tf_error);
3098             }
3099
3100           /* If we thought that the DECL was a member function, but it
3101              turns out to be specializing a static member function,
3102              make DECL a static member function as well.  */
3103           if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3104               && DECL_STATIC_FUNCTION_P (tmpl)
3105               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3106             revert_static_member_fn (decl);
3107
3108           /* If this is a specialization of a member template of a
3109              template class, we want to return the TEMPLATE_DECL, not
3110              the specialization of it.  */
3111           if (tsk == tsk_template && !was_template_id)
3112             {
3113               tree result = DECL_TEMPLATE_RESULT (tmpl);
3114               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3115               DECL_INITIAL (result) = NULL_TREE;
3116               if (have_def)
3117                 {
3118                   tree parm;
3119                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3120                   DECL_SOURCE_LOCATION (result)
3121                     = DECL_SOURCE_LOCATION (decl);
3122                   /* We want to use the argument list specified in the
3123                      definition, not in the original declaration.  */
3124                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3125                   for (parm = DECL_ARGUMENTS (result); parm;
3126                        parm = DECL_CHAIN (parm))
3127                     DECL_CONTEXT (parm) = result;
3128                 }
3129               return register_specialization (tmpl, gen_tmpl, targs,
3130                                               is_friend, 0);
3131             }
3132
3133           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3134           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3135
3136           if (was_template_id)
3137             TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3138
3139           /* Inherit default function arguments from the template
3140              DECL is specializing.  */
3141           if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3142             copy_default_args_to_explicit_spec (decl);
3143
3144           /* This specialization has the same protection as the
3145              template it specializes.  */
3146           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3147           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3148
3149           /* 7.1.1-1 [dcl.stc]
3150
3151              A storage-class-specifier shall not be specified in an
3152              explicit specialization...
3153
3154              The parser rejects these, so unless action is taken here,
3155              explicit function specializations will always appear with
3156              global linkage.
3157
3158              The action recommended by the C++ CWG in response to C++
3159              defect report 605 is to make the storage class and linkage
3160              of the explicit specialization match the templated function:
3161
3162              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3163            */
3164           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3165             {
3166               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3167               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3168
3169               /* A concept cannot be specialized.  */
3170               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3171                 {
3172                   error ("explicit specialization of function concept %qD",
3173                          gen_tmpl);
3174                   return error_mark_node;
3175                 }
3176
3177               /* This specialization has the same linkage and visibility as
3178                  the function template it specializes.  */
3179               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3180               if (! TREE_PUBLIC (decl))
3181                 {
3182                   DECL_INTERFACE_KNOWN (decl) = 1;
3183                   DECL_NOT_REALLY_EXTERN (decl) = 1;
3184                 }
3185               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3186               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3187                 {
3188                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3189                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3190                 }
3191             }
3192
3193           /* If DECL is a friend declaration, declared using an
3194              unqualified name, the namespace associated with DECL may
3195              have been set incorrectly.  For example, in:
3196
3197                template <typename T> void f(T);
3198                namespace N {
3199                  struct S { friend void f<int>(int); }
3200                }
3201
3202              we will have set the DECL_CONTEXT for the friend
3203              declaration to N, rather than to the global namespace.  */
3204           if (DECL_NAMESPACE_SCOPE_P (decl))
3205             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3206
3207           if (is_friend && !have_def)
3208             /* This is not really a declaration of a specialization.
3209                It's just the name of an instantiation.  But, it's not
3210                a request for an instantiation, either.  */
3211             SET_DECL_IMPLICIT_INSTANTIATION (decl);
3212           else if (TREE_CODE (decl) == FUNCTION_DECL)
3213             /* A specialization is not necessarily COMDAT.  */
3214             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3215                                   && DECL_DECLARED_INLINE_P (decl));
3216           else if (VAR_P (decl))
3217             DECL_COMDAT (decl) = false;
3218
3219           /* If this is a full specialization, register it so that we can find
3220              it again.  Partial specializations will be registered in
3221              process_partial_specialization.  */
3222           if (!processing_template_decl)
3223             {
3224               warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3225
3226               decl = register_specialization (decl, gen_tmpl, targs,
3227                                               is_friend, 0);
3228             }
3229
3230
3231           /* A 'structor should already have clones.  */
3232           gcc_assert (decl == error_mark_node
3233                       || variable_template_p (tmpl)
3234                       || !(DECL_CONSTRUCTOR_P (decl)
3235                            || DECL_DESTRUCTOR_P (decl))
3236                       || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3237         }
3238     }
3239
3240   return decl;
3241 }
3242
3243 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3244    parameters.  These are represented in the same format used for
3245    DECL_TEMPLATE_PARMS.  */
3246
3247 int
3248 comp_template_parms (const_tree parms1, const_tree parms2)
3249 {
3250   const_tree p1;
3251   const_tree p2;
3252
3253   if (parms1 == parms2)
3254     return 1;
3255
3256   for (p1 = parms1, p2 = parms2;
3257        p1 != NULL_TREE && p2 != NULL_TREE;
3258        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3259     {
3260       tree t1 = TREE_VALUE (p1);
3261       tree t2 = TREE_VALUE (p2);
3262       int i;
3263
3264       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3265       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3266
3267       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3268         return 0;
3269
3270       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3271         {
3272           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3273           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3274
3275           /* If either of the template parameters are invalid, assume
3276              they match for the sake of error recovery. */
3277           if (error_operand_p (parm1) || error_operand_p (parm2))
3278             return 1;
3279
3280           if (TREE_CODE (parm1) != TREE_CODE (parm2))
3281             return 0;
3282
3283           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3284               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3285                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3286             continue;
3287           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3288             return 0;
3289         }
3290     }
3291
3292   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3293     /* One set of parameters has more parameters lists than the
3294        other.  */
3295     return 0;
3296
3297   return 1;
3298 }
3299
3300 /* Determine whether PARM is a parameter pack.  */
3301
3302 bool
3303 template_parameter_pack_p (const_tree parm)
3304 {
3305   /* Determine if we have a non-type template parameter pack.  */
3306   if (TREE_CODE (parm) == PARM_DECL)
3307     return (DECL_TEMPLATE_PARM_P (parm)
3308             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3309   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3310     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3311
3312   /* If this is a list of template parameters, we could get a
3313      TYPE_DECL or a TEMPLATE_DECL.  */
3314   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3315     parm = TREE_TYPE (parm);
3316
3317   /* Otherwise it must be a type template parameter.  */
3318   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3319            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3320           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3321 }
3322
3323 /* Determine if T is a function parameter pack.  */
3324
3325 bool
3326 function_parameter_pack_p (const_tree t)
3327 {
3328   if (t && TREE_CODE (t) == PARM_DECL)
3329     return DECL_PACK_P (t);
3330   return false;
3331 }
3332
3333 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3334    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3335
3336 tree
3337 get_function_template_decl (const_tree primary_func_tmpl_inst)
3338 {
3339   if (! primary_func_tmpl_inst
3340       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3341       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3342     return NULL;
3343
3344   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3345 }
3346
3347 /* Return true iff the function parameter PARAM_DECL was expanded
3348    from the function parameter pack PACK.  */
3349
3350 bool
3351 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3352 {
3353   if (DECL_ARTIFICIAL (param_decl)
3354       || !function_parameter_pack_p (pack))
3355     return false;
3356
3357   /* The parameter pack and its pack arguments have the same
3358      DECL_PARM_INDEX.  */
3359   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3360 }
3361
3362 /* Determine whether ARGS describes a variadic template args list,
3363    i.e., one that is terminated by a template argument pack.  */
3364
3365 static bool
3366 template_args_variadic_p (tree args)
3367 {
3368   int nargs;
3369   tree last_parm;
3370
3371   if (args == NULL_TREE)
3372     return false;
3373
3374   args = INNERMOST_TEMPLATE_ARGS (args);
3375   nargs = TREE_VEC_LENGTH (args);
3376
3377   if (nargs == 0)
3378     return false;
3379
3380   last_parm = TREE_VEC_ELT (args, nargs - 1);
3381
3382   return ARGUMENT_PACK_P (last_parm);
3383 }
3384
3385 /* Generate a new name for the parameter pack name NAME (an
3386    IDENTIFIER_NODE) that incorporates its */
3387
3388 static tree
3389 make_ith_pack_parameter_name (tree name, int i)
3390 {
3391   /* Munge the name to include the parameter index.  */
3392 #define NUMBUF_LEN 128
3393   char numbuf[NUMBUF_LEN];
3394   char* newname;
3395   int newname_len;
3396
3397   if (name == NULL_TREE)
3398     return name;
3399   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3400   newname_len = IDENTIFIER_LENGTH (name)
3401                 + strlen (numbuf) + 2;
3402   newname = (char*)alloca (newname_len);
3403   snprintf (newname, newname_len,
3404             "%s#%i", IDENTIFIER_POINTER (name), i);
3405   return get_identifier (newname);
3406 }
3407
3408 /* Return true if T is a primary function, class or alias template
3409    specialization, not including the template pattern.  */
3410
3411 bool
3412 primary_template_specialization_p (const_tree t)
3413 {
3414   if (!t)
3415     return false;
3416
3417   if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3418     return (DECL_LANG_SPECIFIC (t)
3419             && DECL_USE_TEMPLATE (t)
3420             && DECL_TEMPLATE_INFO (t)
3421             && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3422   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3423     return (CLASSTYPE_TEMPLATE_INFO (t)
3424             && CLASSTYPE_USE_TEMPLATE (t)
3425             && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3426   else if (alias_template_specialization_p (t))
3427     return true;
3428   return false;
3429 }
3430
3431 /* Return true if PARM is a template template parameter.  */
3432
3433 bool
3434 template_template_parameter_p (const_tree parm)
3435 {
3436   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3437 }
3438
3439 /* Return true iff PARM is a DECL representing a type template
3440    parameter.  */
3441
3442 bool
3443 template_type_parameter_p (const_tree parm)
3444 {
3445   return (parm
3446           && (TREE_CODE (parm) == TYPE_DECL
3447               || TREE_CODE (parm) == TEMPLATE_DECL)
3448           && DECL_TEMPLATE_PARM_P (parm));
3449 }
3450
3451 /* Return the template parameters of T if T is a
3452    primary template instantiation, NULL otherwise.  */
3453
3454 tree
3455 get_primary_template_innermost_parameters (const_tree t)
3456 {
3457   tree parms = NULL, template_info = NULL;
3458
3459   if ((template_info = get_template_info (t))
3460       && primary_template_specialization_p (t))
3461     parms = INNERMOST_TEMPLATE_PARMS
3462         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3463
3464   return parms;
3465 }
3466
3467 /* Return the template parameters of the LEVELth level from the full list
3468    of template parameters PARMS.  */
3469
3470 tree
3471 get_template_parms_at_level (tree parms, int level)
3472 {
3473   tree p;
3474   if (!parms
3475       || TREE_CODE (parms) != TREE_LIST
3476       || level > TMPL_PARMS_DEPTH (parms))
3477     return NULL_TREE;
3478
3479   for (p = parms; p; p = TREE_CHAIN (p))
3480     if (TMPL_PARMS_DEPTH (p) == level)
3481       return p;
3482
3483   return NULL_TREE;
3484 }
3485
3486 /* Returns the template arguments of T if T is a template instantiation,
3487    NULL otherwise.  */
3488
3489 tree
3490 get_template_innermost_arguments (const_tree t)
3491 {
3492   tree args = NULL, template_info = NULL;
3493
3494   if ((template_info = get_template_info (t))
3495       && TI_ARGS (template_info))
3496     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3497
3498   return args;
3499 }
3500
3501 /* Return the argument pack elements of T if T is a template argument pack,
3502    NULL otherwise.  */
3503
3504 tree
3505 get_template_argument_pack_elems (const_tree t)
3506 {
3507   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3508       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3509     return NULL;
3510
3511   return ARGUMENT_PACK_ARGS (t);
3512 }
3513
3514 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3515    ARGUMENT_PACK_SELECT represents. */
3516
3517 static tree
3518 argument_pack_select_arg (tree t)
3519 {
3520   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3521   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3522
3523   /* If the selected argument is an expansion E, that most likely means we were
3524      called from gen_elem_of_pack_expansion_instantiation during the
3525      substituting of an argument pack (of which the Ith element is a pack
3526      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3527      In this case, the Ith element resulting from this substituting is going to
3528      be a pack expansion, which pattern is the pattern of E.  Let's return the
3529      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3530      resulting pack expansion from it.  */
3531   if (PACK_EXPANSION_P (arg))
3532     {
3533       /* Make sure we aren't throwing away arg info.  */
3534       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3535       arg = PACK_EXPANSION_PATTERN (arg);
3536     }
3537
3538   return arg;
3539 }
3540
3541
3542 /* True iff FN is a function representing a built-in variadic parameter
3543    pack.  */
3544
3545 bool
3546 builtin_pack_fn_p (tree fn)
3547 {
3548   if (!fn
3549       || TREE_CODE (fn) != FUNCTION_DECL
3550       || !DECL_IS_BUILTIN (fn))
3551     return false;
3552
3553   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3554     return true;
3555
3556   return false;
3557 }
3558
3559 /* True iff CALL is a call to a function representing a built-in variadic
3560    parameter pack.  */
3561
3562 static bool
3563 builtin_pack_call_p (tree call)
3564 {
3565   if (TREE_CODE (call) != CALL_EXPR)
3566     return false;
3567   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3568 }
3569
3570 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3571
3572 static tree
3573 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3574                      tree in_decl)
3575 {
3576   tree ohi = CALL_EXPR_ARG (call, 0);
3577   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3578                                    false/*fn*/, true/*int_cst*/);
3579
3580   if (value_dependent_expression_p (hi))
3581     {
3582       if (hi != ohi)
3583         {
3584           call = copy_node (call);
3585           CALL_EXPR_ARG (call, 0) = hi;
3586         }
3587       tree ex = make_pack_expansion (call, complain);
3588       tree vec = make_tree_vec (1);
3589       TREE_VEC_ELT (vec, 0) = ex;
3590       return vec;
3591     }
3592   else
3593     {
3594       hi = cxx_constant_value (hi);
3595       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3596
3597       /* Calculate the largest value of len that won't make the size of the vec
3598          overflow an int.  The compiler will exceed resource limits long before
3599          this, but it seems a decent place to diagnose.  */
3600       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3601
3602       if (len < 0 || len > max)
3603         {
3604           if ((complain & tf_error)
3605               && hi != error_mark_node)
3606             error ("argument to %<__integer_pack%> must be between 0 and %d",
3607                    max);
3608           return error_mark_node;
3609         }
3610
3611       tree vec = make_tree_vec (len);
3612
3613       for (int i = 0; i < len; ++i)
3614         TREE_VEC_ELT (vec, i) = size_int (i);
3615
3616       return vec;
3617     }
3618 }
3619
3620 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3621    CALL.  */
3622
3623 static tree
3624 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3625                           tree in_decl)
3626 {
3627   if (!builtin_pack_call_p (call))
3628     return NULL_TREE;
3629
3630   tree fn = CALL_EXPR_FN (call);
3631
3632   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3633     return expand_integer_pack (call, args, complain, in_decl);
3634
3635   return NULL_TREE;
3636 }
3637
3638 /* Structure used to track the progress of find_parameter_packs_r.  */
3639 struct find_parameter_pack_data
3640 {
3641   /* TREE_LIST that will contain all of the parameter packs found by
3642      the traversal.  */
3643   tree* parameter_packs;
3644
3645   /* Set of AST nodes that have been visited by the traversal.  */
3646   hash_set<tree> *visited;
3647
3648   /* True iff we're making a type pack expansion.  */
3649   bool type_pack_expansion_p;
3650 };
3651
3652 /* Identifies all of the argument packs that occur in a template
3653    argument and appends them to the TREE_LIST inside DATA, which is a
3654    find_parameter_pack_data structure. This is a subroutine of
3655    make_pack_expansion and uses_parameter_packs.  */
3656 static tree
3657 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3658 {
3659   tree t = *tp;
3660   struct find_parameter_pack_data* ppd =
3661     (struct find_parameter_pack_data*)data;
3662   bool parameter_pack_p = false;
3663
3664   /* Handle type aliases/typedefs.  */
3665   if (TYPE_ALIAS_P (t))
3666     {
3667       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3668         cp_walk_tree (&TI_ARGS (tinfo),
3669                       &find_parameter_packs_r,
3670                       ppd, ppd->visited);
3671       *walk_subtrees = 0;
3672       return NULL_TREE;
3673     }
3674
3675   /* Identify whether this is a parameter pack or not.  */
3676   switch (TREE_CODE (t))
3677     {
3678     case TEMPLATE_PARM_INDEX:
3679       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3680         parameter_pack_p = true;
3681       break;
3682
3683     case TEMPLATE_TYPE_PARM:
3684       t = TYPE_MAIN_VARIANT (t);
3685       /* FALLTHRU */
3686     case TEMPLATE_TEMPLATE_PARM:
3687       /* If the placeholder appears in the decl-specifier-seq of a function
3688          parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3689          is a pack expansion, the invented template parameter is a template
3690          parameter pack.  */
3691       if (ppd->type_pack_expansion_p && is_auto (t))
3692         TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3693       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3694         parameter_pack_p = true;
3695       break;
3696
3697     case FIELD_DECL:
3698     case PARM_DECL:
3699       if (DECL_PACK_P (t))
3700         {
3701           /* We don't want to walk into the type of a PARM_DECL,
3702              because we don't want to see the type parameter pack.  */
3703           *walk_subtrees = 0;
3704           parameter_pack_p = true;
3705         }
3706       break;
3707
3708     case VAR_DECL:
3709       if (DECL_PACK_P (t))
3710         {
3711           /* We don't want to walk into the type of a variadic capture proxy,
3712              because we don't want to see the type parameter pack.  */
3713           *walk_subtrees = 0;
3714           parameter_pack_p = true;
3715         }
3716       else if (variable_template_specialization_p (t))
3717         {
3718           cp_walk_tree (&DECL_TI_ARGS (t),
3719                         find_parameter_packs_r,
3720                         ppd, ppd->visited);
3721           *walk_subtrees = 0;
3722         }
3723       break;
3724
3725     case CALL_EXPR:
3726       if (builtin_pack_call_p (t))
3727         parameter_pack_p = true;
3728       break;
3729
3730     case BASES:
3731       parameter_pack_p = true;
3732       break;
3733     default:
3734       /* Not a parameter pack.  */
3735       break;
3736     }
3737
3738   if (parameter_pack_p)
3739     {
3740       /* Add this parameter pack to the list.  */
3741       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3742     }
3743
3744   if (TYPE_P (t))
3745     cp_walk_tree (&TYPE_CONTEXT (t),
3746                   &find_parameter_packs_r, ppd, ppd->visited);
3747
3748   /* This switch statement will return immediately if we don't find a
3749      parameter pack.  */
3750   switch (TREE_CODE (t))
3751     {
3752     case TEMPLATE_PARM_INDEX:
3753       return NULL_TREE;
3754
3755     case BOUND_TEMPLATE_TEMPLATE_PARM:
3756       /* Check the template itself.  */
3757       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3758                     &find_parameter_packs_r, ppd, ppd->visited);
3759       /* Check the template arguments.  */
3760       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3761                     ppd->visited);
3762       *walk_subtrees = 0;
3763       return NULL_TREE;
3764
3765     case TEMPLATE_TYPE_PARM:
3766     case TEMPLATE_TEMPLATE_PARM:
3767       return NULL_TREE;
3768
3769     case PARM_DECL:
3770       return NULL_TREE;
3771
3772     case DECL_EXPR:
3773       /* Ignore the declaration of a capture proxy for a parameter pack.  */
3774       if (is_capture_proxy (DECL_EXPR_DECL (t)))
3775         *walk_subtrees = 0;
3776       return NULL_TREE;
3777
3778     case RECORD_TYPE:
3779       if (TYPE_PTRMEMFUNC_P (t))
3780         return NULL_TREE;
3781       /* Fall through.  */
3782
3783     case UNION_TYPE:
3784     case ENUMERAL_TYPE:
3785       if (TYPE_TEMPLATE_INFO (t))
3786         cp_walk_tree (&TYPE_TI_ARGS (t),
3787                       &find_parameter_packs_r, ppd, ppd->visited);
3788
3789       *walk_subtrees = 0;
3790       return NULL_TREE;
3791
3792     case TEMPLATE_DECL:
3793       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3794         return NULL_TREE;
3795       gcc_fallthrough();
3796
3797     case CONSTRUCTOR:
3798       cp_walk_tree (&TREE_TYPE (t),
3799                     &find_parameter_packs_r, ppd, ppd->visited);
3800       return NULL_TREE;
3801
3802     case TYPENAME_TYPE:
3803       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3804                    ppd, ppd->visited);
3805       *walk_subtrees = 0;
3806       return NULL_TREE;
3807
3808     case TYPE_PACK_EXPANSION:
3809     case EXPR_PACK_EXPANSION:
3810       *walk_subtrees = 0;
3811       return NULL_TREE;
3812
3813     case INTEGER_TYPE:
3814       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3815                     ppd, ppd->visited);
3816       *walk_subtrees = 0;
3817       return NULL_TREE;
3818
3819     case IDENTIFIER_NODE:
3820       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3821                     ppd->visited);
3822       *walk_subtrees = 0;
3823       return NULL_TREE;
3824
3825     case LAMBDA_EXPR:
3826       {
3827         /* Look at explicit captures.  */
3828         for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3829              cap; cap = TREE_CHAIN (cap))
3830           cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3831                         ppd->visited);
3832         /* Since we defer implicit capture, look in the parms and body.  */
3833         tree fn = lambda_function (t);
3834         cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
3835                       ppd->visited);
3836         cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3837                       ppd->visited);
3838         *walk_subtrees = 0;
3839         return NULL_TREE;
3840       }
3841
3842     case DECLTYPE_TYPE:
3843       {
3844         /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3845            type_pack_expansion_p to false so that any placeholders
3846            within the expression don't get marked as parameter packs.  */
3847         bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3848         ppd->type_pack_expansion_p = false;
3849         cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3850                       ppd, ppd->visited);
3851         ppd->type_pack_expansion_p = type_pack_expansion_p;
3852         *walk_subtrees = 0;
3853         return NULL_TREE;
3854       }
3855
3856     case IF_STMT:
3857       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
3858                     ppd, ppd->visited);
3859       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
3860                     ppd, ppd->visited);
3861       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
3862                     ppd, ppd->visited);
3863       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
3864       *walk_subtrees = 0;
3865       return NULL_TREE;
3866
3867     default:
3868       return NULL_TREE;
3869     }
3870
3871   return NULL_TREE;
3872 }
3873
3874 /* Determines if the expression or type T uses any parameter packs.  */
3875 tree
3876 uses_parameter_packs (tree t)
3877 {
3878   tree parameter_packs = NULL_TREE;
3879   struct find_parameter_pack_data ppd;
3880   ppd.parameter_packs = &parameter_packs;
3881   ppd.visited = new hash_set<tree>;
3882   ppd.type_pack_expansion_p = false;
3883   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3884   delete ppd.visited;
3885   return parameter_packs;
3886 }
3887
3888 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3889    representation a base-class initializer into a parameter pack
3890    expansion. If all goes well, the resulting node will be an
3891    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3892    respectively.  */
3893 tree
3894 make_pack_expansion (tree arg, tsubst_flags_t complain)
3895 {
3896   tree result;
3897   tree parameter_packs = NULL_TREE;
3898   bool for_types = false;
3899   struct find_parameter_pack_data ppd;
3900
3901   if (!arg || arg == error_mark_node)
3902     return arg;
3903
3904   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3905     {
3906       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3907          class initializer.  In this case, the TREE_PURPOSE will be a
3908          _TYPE node (representing the base class expansion we're
3909          initializing) and the TREE_VALUE will be a TREE_LIST
3910          containing the initialization arguments. 
3911
3912          The resulting expansion looks somewhat different from most
3913          expansions. Rather than returning just one _EXPANSION, we
3914          return a TREE_LIST whose TREE_PURPOSE is a
3915          TYPE_PACK_EXPANSION containing the bases that will be
3916          initialized.  The TREE_VALUE will be identical to the
3917          original TREE_VALUE, which is a list of arguments that will
3918          be passed to each base.  We do not introduce any new pack
3919          expansion nodes into the TREE_VALUE (although it is possible
3920          that some already exist), because the TREE_PURPOSE and
3921          TREE_VALUE all need to be expanded together with the same
3922          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3923          resulting TREE_PURPOSE will mention the parameter packs in
3924          both the bases and the arguments to the bases.  */
3925       tree purpose;
3926       tree value;
3927       tree parameter_packs = NULL_TREE;
3928
3929       /* Determine which parameter packs will be used by the base
3930          class expansion.  */
3931       ppd.visited = new hash_set<tree>;
3932       ppd.parameter_packs = &parameter_packs;
3933       ppd.type_pack_expansion_p = false;
3934       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3935       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3936                     &ppd, ppd.visited);
3937
3938       if (parameter_packs == NULL_TREE)
3939         {
3940           if (complain & tf_error)
3941             error ("base initializer expansion %qT contains no parameter packs",
3942                    arg);
3943           delete ppd.visited;
3944           return error_mark_node;
3945         }
3946
3947       if (TREE_VALUE (arg) != void_type_node)
3948         {
3949           /* Collect the sets of parameter packs used in each of the
3950              initialization arguments.  */
3951           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3952             {
3953               /* Determine which parameter packs will be expanded in this
3954                  argument.  */
3955               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3956                             &ppd, ppd.visited);
3957             }
3958         }
3959
3960       delete ppd.visited;
3961
3962       /* Create the pack expansion type for the base type.  */
3963       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3964       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3965       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3966       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
3967
3968       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3969          they will rarely be compared to anything.  */
3970       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3971
3972       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3973     }
3974
3975   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3976     for_types = true;
3977
3978   /* Build the PACK_EXPANSION_* node.  */
3979   result = for_types
3980      ? cxx_make_type (TYPE_PACK_EXPANSION)
3981      : make_node (EXPR_PACK_EXPANSION);
3982   SET_PACK_EXPANSION_PATTERN (result, arg);
3983   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3984     {
3985       /* Propagate type and const-expression information.  */
3986       TREE_TYPE (result) = TREE_TYPE (arg);
3987       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3988       /* Mark this read now, since the expansion might be length 0.  */
3989       mark_exp_read (arg);
3990     }
3991   else
3992     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3993        they will rarely be compared to anything.  */
3994     SET_TYPE_STRUCTURAL_EQUALITY (result);
3995
3996   /* Determine which parameter packs will be expanded.  */
3997   ppd.parameter_packs = &parameter_packs;
3998   ppd.visited = new hash_set<tree>;
3999   ppd.type_pack_expansion_p = TYPE_P (arg);
4000   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4001   delete ppd.visited;
4002
4003   /* Make sure we found some parameter packs.  */
4004   if (parameter_packs == NULL_TREE)
4005     {
4006       if (complain & tf_error)
4007         {
4008           if (TYPE_P (arg))
4009             error ("expansion pattern %qT contains no parameter packs", arg);
4010           else
4011             error ("expansion pattern %qE contains no parameter packs", arg);
4012         }
4013       return error_mark_node;
4014     }
4015   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4016
4017   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4018
4019   return result;
4020 }
4021
4022 /* Checks T for any "bare" parameter packs, which have not yet been
4023    expanded, and issues an error if any are found. This operation can
4024    only be done on full expressions or types (e.g., an expression
4025    statement, "if" condition, etc.), because we could have expressions like:
4026
4027      foo(f(g(h(args)))...)
4028
4029    where "args" is a parameter pack. check_for_bare_parameter_packs
4030    should not be called for the subexpressions args, h(args),
4031    g(h(args)), or f(g(h(args))), because we would produce erroneous
4032    error messages.
4033
4034    Returns TRUE and emits an error if there were bare parameter packs,
4035    returns FALSE otherwise.  */
4036 bool
4037 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4038 {
4039   tree parameter_packs = NULL_TREE;
4040   struct find_parameter_pack_data ppd;
4041
4042   if (!processing_template_decl || !t || t == error_mark_node)
4043     return false;
4044
4045   /* A lambda might use a parameter pack from the containing context.  */
4046   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4047       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4048     return false;
4049
4050   if (TREE_CODE (t) == TYPE_DECL)
4051     t = TREE_TYPE (t);
4052
4053   ppd.parameter_packs = &parameter_packs;
4054   ppd.visited = new hash_set<tree>;
4055   ppd.type_pack_expansion_p = false;
4056   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4057   delete ppd.visited;
4058
4059   if (parameter_packs)
4060     {
4061       if (loc == UNKNOWN_LOCATION)
4062         loc = cp_expr_loc_or_input_loc (t);
4063       error_at (loc, "parameter packs not expanded with %<...%>:");
4064       while (parameter_packs)
4065         {
4066           tree pack = TREE_VALUE (parameter_packs);
4067           tree name = NULL_TREE;
4068
4069           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4070               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4071             name = TYPE_NAME (pack);
4072           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4073             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4074           else if (TREE_CODE (pack) == CALL_EXPR)
4075             name = DECL_NAME (CALL_EXPR_FN (pack));
4076           else
4077             name = DECL_NAME (pack);
4078
4079           if (name)
4080             inform (loc, "        %qD", name);
4081           else
4082             inform (loc, "        %s", "<anonymous>");
4083
4084           parameter_packs = TREE_CHAIN (parameter_packs);
4085         }
4086
4087       return true;
4088     }
4089
4090   return false;
4091 }
4092
4093 /* Expand any parameter packs that occur in the template arguments in
4094    ARGS.  */
4095 tree
4096 expand_template_argument_pack (tree args)
4097 {
4098   if (args == error_mark_node)
4099     return error_mark_node;
4100
4101   tree result_args = NULL_TREE;
4102   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4103   int num_result_args = -1;
4104   int non_default_args_count = -1;
4105
4106   /* First, determine if we need to expand anything, and the number of
4107      slots we'll need.  */
4108   for (in_arg = 0; in_arg < nargs; ++in_arg)
4109     {
4110       tree arg = TREE_VEC_ELT (args, in_arg);
4111       if (arg == NULL_TREE)
4112         return args;
4113       if (ARGUMENT_PACK_P (arg))
4114         {
4115           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4116           if (num_result_args < 0)
4117             num_result_args = in_arg + num_packed;
4118           else
4119             num_result_args += num_packed;
4120         }
4121       else
4122         {
4123           if (num_result_args >= 0)
4124             num_result_args++;
4125         }
4126     }
4127
4128   /* If no expansion is necessary, we're done.  */
4129   if (num_result_args < 0)
4130     return args;
4131
4132   /* Expand arguments.  */
4133   result_args = make_tree_vec (num_result_args);
4134   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4135     non_default_args_count =
4136       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4137   for (in_arg = 0; in_arg < nargs; ++in_arg)
4138     {
4139       tree arg = TREE_VEC_ELT (args, in_arg);
4140       if (ARGUMENT_PACK_P (arg))
4141         {
4142           tree packed = ARGUMENT_PACK_ARGS (arg);
4143           int i, num_packed = TREE_VEC_LENGTH (packed);
4144           for (i = 0; i < num_packed; ++i, ++out_arg)
4145             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4146           if (non_default_args_count > 0)
4147             non_default_args_count += num_packed - 1;
4148         }
4149       else
4150         {
4151           TREE_VEC_ELT (result_args, out_arg) = arg;
4152           ++out_arg;
4153         }
4154     }
4155   if (non_default_args_count >= 0)
4156     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4157   return result_args;
4158 }
4159
4160 /* Checks if DECL shadows a template parameter.
4161
4162    [temp.local]: A template-parameter shall not be redeclared within its
4163    scope (including nested scopes).
4164
4165    Emits an error and returns TRUE if the DECL shadows a parameter,
4166    returns FALSE otherwise.  */
4167
4168 bool
4169 check_template_shadow (tree decl)
4170 {
4171   tree olddecl;
4172
4173   /* If we're not in a template, we can't possibly shadow a template
4174      parameter.  */
4175   if (!current_template_parms)
4176     return true;
4177
4178   /* Figure out what we're shadowing.  */
4179   decl = OVL_FIRST (decl);
4180   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4181
4182   /* If there's no previous binding for this name, we're not shadowing
4183      anything, let alone a template parameter.  */
4184   if (!olddecl)
4185     return true;
4186
4187   /* If we're not shadowing a template parameter, we're done.  Note
4188      that OLDDECL might be an OVERLOAD (or perhaps even an
4189      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4190      node.  */
4191   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4192     return true;
4193
4194   /* We check for decl != olddecl to avoid bogus errors for using a
4195      name inside a class.  We check TPFI to avoid duplicate errors for
4196      inline member templates.  */
4197   if (decl == olddecl
4198       || (DECL_TEMPLATE_PARM_P (decl)
4199           && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4200     return true;
4201
4202   /* Don't complain about the injected class name, as we've already
4203      complained about the class itself.  */
4204   if (DECL_SELF_REFERENCE_P (decl))
4205     return false;
4206
4207   if (DECL_TEMPLATE_PARM_P (decl))
4208     error ("declaration of template parameter %q+D shadows "
4209            "template parameter", decl);
4210   else
4211     error ("declaration of %q+#D shadows template parameter", decl);
4212   inform (DECL_SOURCE_LOCATION (olddecl),
4213           "template parameter %qD declared here", olddecl);
4214   return false;
4215 }
4216
4217 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4218    ORIG_LEVEL, DECL, and TYPE.  */
4219
4220 static tree
4221 build_template_parm_index (int index,
4222                            int level,
4223                            int orig_level,
4224                            tree decl,
4225                            tree type)
4226 {
4227   tree t = make_node (TEMPLATE_PARM_INDEX);
4228   TEMPLATE_PARM_IDX (t) = index;
4229   TEMPLATE_PARM_LEVEL (t) = level;
4230   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4231   TEMPLATE_PARM_DECL (t) = decl;
4232   TREE_TYPE (t) = type;
4233   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4234   TREE_READONLY (t) = TREE_READONLY (decl);
4235
4236   return t;
4237 }
4238
4239 /* Find the canonical type parameter for the given template type
4240    parameter.  Returns the canonical type parameter, which may be TYPE
4241    if no such parameter existed.  */
4242
4243 static tree
4244 canonical_type_parameter (tree type)
4245 {
4246   tree list;
4247   int idx = TEMPLATE_TYPE_IDX (type);
4248   if (!canonical_template_parms)
4249     vec_alloc (canonical_template_parms, idx + 1);
4250
4251   if (canonical_template_parms->length () <= (unsigned) idx)
4252     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4253
4254   list = (*canonical_template_parms)[idx];
4255   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4256     list = TREE_CHAIN (list);
4257
4258   if (list)
4259     return TREE_VALUE (list);
4260   else
4261     {
4262       (*canonical_template_parms)[idx]
4263         = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4264       return type;
4265     }
4266 }
4267
4268 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4269    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4270    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4271    new one is created.  */
4272
4273 static tree
4274 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4275                             tsubst_flags_t complain)
4276 {
4277   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4278       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4279           != TEMPLATE_PARM_LEVEL (index) - levels)
4280       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4281     {
4282       tree orig_decl = TEMPLATE_PARM_DECL (index);
4283       tree decl, t;
4284
4285       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4286                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4287       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4288       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4289       DECL_ARTIFICIAL (decl) = 1;
4290       SET_DECL_TEMPLATE_PARM_P (decl);
4291
4292       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4293                                      TEMPLATE_PARM_LEVEL (index) - levels,
4294                                      TEMPLATE_PARM_ORIG_LEVEL (index),
4295                                      decl, type);
4296       TEMPLATE_PARM_DESCENDANTS (index) = t;
4297       TEMPLATE_PARM_PARAMETER_PACK (t)
4298         = TEMPLATE_PARM_PARAMETER_PACK (index);
4299
4300         /* Template template parameters need this.  */
4301       if (TREE_CODE (decl) == TEMPLATE_DECL)
4302         {
4303           DECL_TEMPLATE_RESULT (decl)
4304             = build_decl (DECL_SOURCE_LOCATION (decl),
4305                           TYPE_DECL, DECL_NAME (decl), type);
4306           DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4307           DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4308             (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4309         }
4310     }
4311
4312   return TEMPLATE_PARM_DESCENDANTS (index);
4313 }
4314
4315 /* Process information from new template parameter PARM and append it
4316    to the LIST being built.  This new parameter is a non-type
4317    parameter iff IS_NON_TYPE is true. This new parameter is a
4318    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4319    is in PARM_LOC.  */
4320
4321 tree
4322 process_template_parm (tree list, location_t parm_loc, tree parm,
4323                        bool is_non_type, bool is_parameter_pack)
4324 {
4325   tree decl = 0;
4326   int idx = 0;
4327
4328   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4329   tree defval = TREE_PURPOSE (parm);
4330   tree constr = TREE_TYPE (parm);
4331
4332   if (list)
4333     {
4334       tree p = tree_last (list);
4335
4336       if (p && TREE_VALUE (p) != error_mark_node)
4337         {
4338           p = TREE_VALUE (p);
4339           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4340             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4341           else
4342             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4343         }
4344
4345       ++idx;
4346     }
4347
4348   if (is_non_type)
4349     {
4350       parm = TREE_VALUE (parm);
4351
4352       SET_DECL_TEMPLATE_PARM_P (parm);
4353
4354       if (TREE_TYPE (parm) != error_mark_node)
4355         {
4356           /* [temp.param]
4357
4358              The top-level cv-qualifiers on the template-parameter are
4359              ignored when determining its type.  */
4360           TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4361           if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4362             TREE_TYPE (parm) = error_mark_node;
4363           else if (uses_parameter_packs (TREE_TYPE (parm))
4364                    && !is_parameter_pack
4365                    /* If we're in a nested template parameter list, the template
4366                       template parameter could be a parameter pack.  */
4367                    && processing_template_parmlist == 1)
4368             {
4369               /* This template parameter is not a parameter pack, but it
4370                  should be. Complain about "bare" parameter packs.  */
4371               check_for_bare_parameter_packs (TREE_TYPE (parm));
4372
4373               /* Recover by calling this a parameter pack.  */
4374               is_parameter_pack = true;
4375             }
4376         }
4377
4378       /* A template parameter is not modifiable.  */
4379       TREE_CONSTANT (parm) = 1;
4380       TREE_READONLY (parm) = 1;
4381       decl = build_decl (parm_loc,
4382                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4383       TREE_CONSTANT (decl) = 1;
4384       TREE_READONLY (decl) = 1;
4385       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4386         = build_template_parm_index (idx, processing_template_decl,
4387                                      processing_template_decl,
4388                                      decl, TREE_TYPE (parm));
4389
4390       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4391         = is_parameter_pack;
4392     }
4393   else
4394     {
4395       tree t;
4396       parm = TREE_VALUE (TREE_VALUE (parm));
4397
4398       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4399         {
4400           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4401           /* This is for distinguishing between real templates and template
4402              template parameters */
4403           TREE_TYPE (parm) = t;
4404           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4405           decl = parm;
4406         }
4407       else
4408         {
4409           t = cxx_make_type (TEMPLATE_TYPE_PARM);
4410           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4411           decl = build_decl (parm_loc,
4412                              TYPE_DECL, parm, t);
4413         }
4414
4415       TYPE_NAME (t) = decl;
4416       TYPE_STUB_DECL (t) = decl;
4417       parm = decl;
4418       TEMPLATE_TYPE_PARM_INDEX (t)
4419         = build_template_parm_index (idx, processing_template_decl,
4420                                      processing_template_decl,
4421                                      decl, TREE_TYPE (parm));
4422       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4423       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4424     }
4425   DECL_ARTIFICIAL (decl) = 1;
4426   SET_DECL_TEMPLATE_PARM_P (decl);
4427
4428   /* Build requirements for the type/template parameter.
4429      This must be done after SET_DECL_TEMPLATE_PARM_P or
4430      process_template_parm could fail. */
4431   tree reqs = finish_shorthand_constraint (parm, constr);
4432
4433   decl = pushdecl (decl);
4434   if (!is_non_type)
4435     parm = decl;
4436
4437   /* Build the parameter node linking the parameter declaration,
4438      its default argument (if any), and its constraints (if any). */
4439   parm = build_tree_list (defval, parm);
4440   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4441
4442   return chainon (list, parm);
4443 }
4444
4445 /* The end of a template parameter list has been reached.  Process the
4446    tree list into a parameter vector, converting each parameter into a more
4447    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
4448    as PARM_DECLs.  */
4449
4450 tree
4451 end_template_parm_list (tree parms)
4452 {
4453   int nparms;
4454   tree parm, next;
4455   tree saved_parmlist = make_tree_vec (list_length (parms));
4456
4457   /* Pop the dummy parameter level and add the real one.  */
4458   current_template_parms = TREE_CHAIN (current_template_parms);
4459
4460   current_template_parms
4461     = tree_cons (size_int (processing_template_decl),
4462                  saved_parmlist, current_template_parms);
4463
4464   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4465     {
4466       next = TREE_CHAIN (parm);
4467       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4468       TREE_CHAIN (parm) = NULL_TREE;
4469     }
4470
4471   --processing_template_parmlist;
4472
4473   return saved_parmlist;
4474 }
4475
4476 // Explicitly indicate the end of the template parameter list. We assume
4477 // that the current template parameters have been constructed and/or
4478 // managed explicitly, as when creating new template template parameters
4479 // from a shorthand constraint.
4480 void
4481 end_template_parm_list ()
4482 {
4483   --processing_template_parmlist;
4484 }
4485
4486 /* end_template_decl is called after a template declaration is seen.  */
4487
4488 void
4489 end_template_decl (void)
4490 {
4491   reset_specialization ();
4492
4493   if (! processing_template_decl)
4494     return;
4495
4496   /* This matches the pushlevel in begin_template_parm_list.  */
4497   finish_scope ();
4498
4499   --processing_template_decl;
4500   current_template_parms = TREE_CHAIN (current_template_parms);
4501 }
4502
4503 /* Takes a TREE_LIST representing a template parameter and convert it
4504    into an argument suitable to be passed to the type substitution
4505    functions.  Note that If the TREE_LIST contains an error_mark
4506    node, the returned argument is error_mark_node.  */
4507
4508 tree
4509 template_parm_to_arg (tree t)
4510 {
4511
4512   if (t == NULL_TREE
4513       || TREE_CODE (t) != TREE_LIST)
4514     return t;
4515
4516   if (error_operand_p (TREE_VALUE (t)))
4517     return error_mark_node;
4518
4519   t = TREE_VALUE (t);
4520
4521   if (TREE_CODE (t) == TYPE_DECL
4522       || TREE_CODE (t) == TEMPLATE_DECL)
4523     {
4524       t = TREE_TYPE (t);
4525
4526       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4527         {
4528           /* Turn this argument into a TYPE_ARGUMENT_PACK
4529              with a single element, which expands T.  */
4530           tree vec = make_tree_vec (1);
4531           if (CHECKING_P)
4532             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4533
4534           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4535
4536           t = cxx_make_type (TYPE_ARGUMENT_PACK);
4537           SET_ARGUMENT_PACK_ARGS (t, vec);
4538         }
4539     }
4540   else
4541     {
4542       t = DECL_INITIAL (t);
4543
4544       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4545         {
4546           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4547              with a single element, which expands T.  */
4548           tree vec = make_tree_vec (1);
4549           if (CHECKING_P)
4550             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4551
4552           t = convert_from_reference (t);
4553           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4554
4555           t  = make_node (NONTYPE_ARGUMENT_PACK);
4556           SET_ARGUMENT_PACK_ARGS (t, vec);
4557         }
4558       else
4559         t = convert_from_reference (t);
4560     }
4561   return t;
4562 }
4563
4564 /* Given a single level of template parameters (a TREE_VEC), return it
4565    as a set of template arguments.  */
4566
4567 static tree
4568 template_parms_level_to_args (tree parms)
4569 {
4570   tree a = copy_node (parms);
4571   TREE_TYPE (a) = NULL_TREE;
4572   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4573     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4574
4575   if (CHECKING_P)
4576     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4577
4578   return a;
4579 }
4580
4581 /* Given a set of template parameters, return them as a set of template
4582    arguments.  The template parameters are represented as a TREE_VEC, in
4583    the form documented in cp-tree.h for template arguments.  */
4584
4585 static tree
4586 template_parms_to_args (tree parms)
4587 {
4588   tree header;
4589   tree args = NULL_TREE;
4590   int length = TMPL_PARMS_DEPTH (parms);
4591   int l = length;
4592
4593   /* If there is only one level of template parameters, we do not
4594      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4595      TREE_VEC containing the arguments.  */
4596   if (length > 1)
4597     args = make_tree_vec (length);
4598
4599   for (header = parms; header; header = TREE_CHAIN (header))
4600     {
4601       tree a = template_parms_level_to_args (TREE_VALUE (header));
4602
4603       if (length > 1)
4604         TREE_VEC_ELT (args, --l) = a;
4605       else
4606         args = a;
4607     }
4608
4609   return args;
4610 }
4611
4612 /* Within the declaration of a template, return the currently active
4613    template parameters as an argument TREE_VEC.  */
4614
4615 static tree
4616 current_template_args (void)
4617 {
4618   return template_parms_to_args (current_template_parms);
4619 }
4620
4621 /* Update the declared TYPE by doing any lookups which were thought to be
4622    dependent, but are not now that we know the SCOPE of the declarator.  */
4623
4624 tree
4625 maybe_update_decl_type (tree orig_type, tree scope)
4626 {
4627   tree type = orig_type;
4628
4629   if (type == NULL_TREE)
4630     return type;
4631
4632   if (TREE_CODE (orig_type) == TYPE_DECL)
4633     type = TREE_TYPE (type);
4634
4635   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4636       && dependent_type_p (type)
4637       /* Don't bother building up the args in this case.  */
4638       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4639     {
4640       /* tsubst in the args corresponding to the template parameters,
4641          including auto if present.  Most things will be unchanged, but
4642          make_typename_type and tsubst_qualified_id will resolve
4643          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4644       tree args = current_template_args ();
4645       tree auto_node = type_uses_auto (type);
4646       tree pushed;
4647       if (auto_node)
4648         {
4649           tree auto_vec = make_tree_vec (1);
4650           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4651           args = add_to_template_args (args, auto_vec);
4652         }
4653       pushed = push_scope (scope);
4654       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4655       if (pushed)
4656         pop_scope (scope);
4657     }
4658
4659   if (type == error_mark_node)
4660     return orig_type;
4661
4662   if (TREE_CODE (orig_type) == TYPE_DECL)
4663     {
4664       if (same_type_p (type, TREE_TYPE (orig_type)))
4665         type = orig_type;
4666       else
4667         type = TYPE_NAME (type);
4668     }
4669   return type;
4670 }
4671
4672 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4673    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4674    the new  template is a member template. */
4675
4676 static tree
4677 build_template_decl (tree decl, tree parms, bool member_template_p)
4678 {
4679   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4680   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4681   DECL_TEMPLATE_PARMS (tmpl) = parms;
4682   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4683   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4684   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4685
4686   return tmpl;
4687 }
4688
4689 struct template_parm_data
4690 {
4691   /* The level of the template parameters we are currently
4692      processing.  */
4693   int level;
4694
4695   /* The index of the specialization argument we are currently
4696      processing.  */
4697   int current_arg;
4698
4699   /* An array whose size is the number of template parameters.  The
4700      elements are nonzero if the parameter has been used in any one
4701      of the arguments processed so far.  */
4702   int* parms;
4703
4704   /* An array whose size is the number of template arguments.  The
4705      elements are nonzero if the argument makes use of template
4706      parameters of this level.  */
4707   int* arg_uses_template_parms;
4708 };
4709
4710 /* Subroutine of push_template_decl used to see if each template
4711    parameter in a partial specialization is used in the explicit
4712    argument list.  If T is of the LEVEL given in DATA (which is
4713    treated as a template_parm_data*), then DATA->PARMS is marked
4714    appropriately.  */
4715
4716 static int
4717 mark_template_parm (tree t, void* data)
4718 {
4719   int level;
4720   int idx;
4721   struct template_parm_data* tpd = (struct template_parm_data*) data;
4722
4723   template_parm_level_and_index (t, &level, &idx);
4724
4725   if (level == tpd->level)
4726     {
4727       tpd->parms[idx] = 1;
4728       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4729     }
4730
4731   /* In C++17 the type of a non-type argument is a deduced context.  */
4732   if (cxx_dialect >= cxx17
4733       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4734     for_each_template_parm (TREE_TYPE (t),
4735                             &mark_template_parm,
4736                             data,
4737                             NULL,
4738                             /*include_nondeduced_p=*/false);
4739
4740   /* Return zero so that for_each_template_parm will continue the
4741      traversal of the tree; we want to mark *every* template parm.  */
4742   return 0;
4743 }
4744
4745 /* Process the partial specialization DECL.  */
4746
4747 static tree
4748 process_partial_specialization (tree decl)
4749 {
4750   tree type = TREE_TYPE (decl);
4751   tree tinfo = get_template_info (decl);
4752   tree maintmpl = TI_TEMPLATE (tinfo);
4753   tree specargs = TI_ARGS (tinfo);
4754   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4755   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4756   tree inner_parms;
4757   tree inst;
4758   int nargs = TREE_VEC_LENGTH (inner_args);
4759   int ntparms;
4760   int  i;
4761   bool did_error_intro = false;
4762   struct template_parm_data tpd;
4763   struct template_parm_data tpd2;
4764
4765   gcc_assert (current_template_parms);
4766
4767   /* A concept cannot be specialized.  */
4768   if (flag_concepts && variable_concept_p (maintmpl))
4769     {
4770       error ("specialization of variable concept %q#D", maintmpl);
4771       return error_mark_node;
4772     }
4773
4774   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4775   ntparms = TREE_VEC_LENGTH (inner_parms);
4776
4777   /* We check that each of the template parameters given in the
4778      partial specialization is used in the argument list to the
4779      specialization.  For example:
4780
4781        template <class T> struct S;
4782        template <class T> struct S<T*>;
4783
4784      The second declaration is OK because `T*' uses the template
4785      parameter T, whereas
4786
4787        template <class T> struct S<int>;
4788
4789      is no good.  Even trickier is:
4790
4791        template <class T>
4792        struct S1
4793        {
4794           template <class U>
4795           struct S2;
4796           template <class U>
4797           struct S2<T>;
4798        };
4799
4800      The S2<T> declaration is actually invalid; it is a
4801      full-specialization.  Of course,
4802
4803           template <class U>
4804           struct S2<T (*)(U)>;
4805
4806      or some such would have been OK.  */
4807   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4808   tpd.parms = XALLOCAVEC (int, ntparms);
4809   memset (tpd.parms, 0, sizeof (int) * ntparms);
4810
4811   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4812   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4813   for (i = 0; i < nargs; ++i)
4814     {
4815       tpd.current_arg = i;
4816       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4817                               &mark_template_parm,
4818                               &tpd,
4819                               NULL,
4820                               /*include_nondeduced_p=*/false);
4821     }
4822   for (i = 0; i < ntparms; ++i)
4823     if (tpd.parms[i] == 0)
4824       {
4825         /* One of the template parms was not used in a deduced context in the
4826            specialization.  */
4827         if (!did_error_intro)
4828           {
4829             error ("template parameters not deducible in "
4830                    "partial specialization:");
4831             did_error_intro = true;
4832           }
4833
4834         inform (input_location, "        %qD",
4835                 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4836       }
4837
4838   if (did_error_intro)
4839     return error_mark_node;
4840
4841   /* [temp.class.spec]
4842
4843      The argument list of the specialization shall not be identical to
4844      the implicit argument list of the primary template.  */
4845   tree main_args
4846     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4847   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4848       && (!flag_concepts
4849           || !strictly_subsumes (current_template_constraints (),
4850                                  get_constraints (maintmpl))))
4851     {
4852       if (!flag_concepts)
4853         error ("partial specialization %q+D does not specialize "
4854                "any template arguments; to define the primary template, "
4855                "remove the template argument list", decl);
4856       else
4857         error ("partial specialization %q+D does not specialize any "
4858                "template arguments and is not more constrained than "
4859                "the primary template; to define the primary template, "
4860                "remove the template argument list", decl);
4861       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4862     }
4863
4864   /* A partial specialization that replaces multiple parameters of the
4865      primary template with a pack expansion is less specialized for those
4866      parameters.  */
4867   if (nargs < DECL_NTPARMS (maintmpl))
4868     {
4869       error ("partial specialization is not more specialized than the "
4870              "primary template because it replaces multiple parameters "
4871              "with a pack expansion");
4872       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4873       /* Avoid crash in process_partial_specialization.  */
4874       return decl;
4875     }
4876
4877   /* If we aren't in a dependent class, we can actually try deduction.  */
4878   else if (tpd.level == 1
4879            /* FIXME we should be able to handle a partial specialization of a
4880               partial instantiation, but currently we can't (c++/41727).  */
4881            && TMPL_ARGS_DEPTH (specargs) == 1
4882            && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4883     {
4884       auto_diagnostic_group d;
4885       if (permerror (input_location, "partial specialization %qD is not "
4886                      "more specialized than", decl))
4887         inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4888                 maintmpl);
4889     }
4890
4891   /* [temp.class.spec]
4892
4893      A partially specialized non-type argument expression shall not
4894      involve template parameters of the partial specialization except
4895      when the argument expression is a simple identifier.
4896
4897      The type of a template parameter corresponding to a specialized
4898      non-type argument shall not be dependent on a parameter of the
4899      specialization.
4900
4901      Also, we verify that pack expansions only occur at the
4902      end of the argument list.  */
4903   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4904   tpd2.parms = 0;
4905   for (i = 0; i < nargs; ++i)
4906     {
4907       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4908       tree arg = TREE_VEC_ELT (inner_args, i);
4909       tree packed_args = NULL_TREE;
4910       int j, len = 1;
4911
4912       if (ARGUMENT_PACK_P (arg))
4913         {
4914           /* Extract the arguments from the argument pack. We'll be
4915              iterating over these in the following loop.  */
4916           packed_args = ARGUMENT_PACK_ARGS (arg);
4917           len = TREE_VEC_LENGTH (packed_args);
4918         }
4919
4920       for (j = 0; j < len; j++)
4921         {
4922           if (packed_args)
4923             /* Get the Jth argument in the parameter pack.  */
4924             arg = TREE_VEC_ELT (packed_args, j);
4925
4926           if (PACK_EXPANSION_P (arg))
4927             {
4928               /* Pack expansions must come at the end of the
4929                  argument list.  */
4930               if ((packed_args && j < len - 1)
4931                   || (!packed_args && i < nargs - 1))
4932                 {
4933                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4934                     error ("parameter pack argument %qE must be at the "
4935                            "end of the template argument list", arg);
4936                   else
4937                     error ("parameter pack argument %qT must be at the "
4938                            "end of the template argument list", arg);
4939                 }
4940             }
4941
4942           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4943             /* We only care about the pattern.  */
4944             arg = PACK_EXPANSION_PATTERN (arg);
4945
4946           if (/* These first two lines are the `non-type' bit.  */
4947               !TYPE_P (arg)
4948               && TREE_CODE (arg) != TEMPLATE_DECL
4949               /* This next two lines are the `argument expression is not just a
4950                  simple identifier' condition and also the `specialized
4951                  non-type argument' bit.  */
4952               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4953               && !((REFERENCE_REF_P (arg)
4954                     || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
4955                    && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4956             {
4957               if ((!packed_args && tpd.arg_uses_template_parms[i])
4958                   || (packed_args && uses_template_parms (arg)))
4959                 error ("template argument %qE involves template parameter(s)",
4960                        arg);
4961               else 
4962                 {
4963                   /* Look at the corresponding template parameter,
4964                      marking which template parameters its type depends
4965                      upon.  */
4966                   tree type = TREE_TYPE (parm);
4967
4968                   if (!tpd2.parms)
4969                     {
4970                       /* We haven't yet initialized TPD2.  Do so now.  */
4971                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4972                       /* The number of parameters here is the number in the
4973                          main template, which, as checked in the assertion
4974                          above, is NARGS.  */
4975                       tpd2.parms = XALLOCAVEC (int, nargs);
4976                       tpd2.level = 
4977                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4978                     }
4979
4980                   /* Mark the template parameters.  But this time, we're
4981                      looking for the template parameters of the main
4982                      template, not in the specialization.  */
4983                   tpd2.current_arg = i;
4984                   tpd2.arg_uses_template_parms[i] = 0;
4985                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4986                   for_each_template_parm (type,
4987                                           &mark_template_parm,
4988                                           &tpd2,
4989                                           NULL,
4990                                           /*include_nondeduced_p=*/false);
4991
4992                   if (tpd2.arg_uses_template_parms [i])
4993                     {
4994                       /* The type depended on some template parameters.
4995                          If they are fully specialized in the
4996                          specialization, that's OK.  */
4997                       int j;
4998                       int count = 0;
4999                       for (j = 0; j < nargs; ++j)
5000                         if (tpd2.parms[j] != 0
5001                             && tpd.arg_uses_template_parms [j])
5002                           ++count;
5003                       if (count != 0)
5004                         error_n (input_location, count,
5005                                  "type %qT of template argument %qE depends "
5006                                  "on a template parameter",
5007                                  "type %qT of template argument %qE depends "
5008                                  "on template parameters",
5009                                  type,
5010                                  arg);
5011                     }
5012                 }
5013             }
5014         }
5015     }
5016
5017   /* We should only get here once.  */
5018   if (TREE_CODE (decl) == TYPE_DECL)
5019     gcc_assert (!COMPLETE_TYPE_P (type));
5020
5021   // Build the template decl.
5022   tree tmpl = build_template_decl (decl, current_template_parms,
5023                                    DECL_MEMBER_TEMPLATE_P (maintmpl));
5024   TREE_TYPE (tmpl) = type;
5025   DECL_TEMPLATE_RESULT (tmpl) = decl;
5026   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5027   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5028   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5029
5030   /* Give template template parms a DECL_CONTEXT of the template
5031      for which they are a parameter.  */
5032   for (i = 0; i < ntparms; ++i)
5033     {
5034       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5035       if (TREE_CODE (parm) == TEMPLATE_DECL)
5036         DECL_CONTEXT (parm) = tmpl;
5037     }
5038
5039   if (VAR_P (decl))
5040     /* We didn't register this in check_explicit_specialization so we could
5041        wait until the constraints were set.  */
5042     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5043   else
5044     associate_classtype_constraints (type);
5045
5046   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5047     = tree_cons (specargs, tmpl,
5048                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5049   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5050
5051   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5052        inst = TREE_CHAIN (inst))
5053     {
5054       tree instance = TREE_VALUE (inst);
5055       if (TYPE_P (instance)
5056           ? (COMPLETE_TYPE_P (instance)
5057              && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5058           : DECL_TEMPLATE_INSTANTIATION (instance))
5059         {
5060           tree spec = most_specialized_partial_spec (instance, tf_none);
5061           tree inst_decl = (DECL_P (instance)
5062                             ? instance : TYPE_NAME (instance));
5063           if (!spec)
5064             /* OK */;
5065           else if (spec == error_mark_node)
5066             permerror (input_location,
5067                        "declaration of %qD ambiguates earlier template "
5068                        "instantiation for %qD", decl, inst_decl);
5069           else if (TREE_VALUE (spec) == tmpl)
5070             permerror (input_location,
5071                        "partial specialization of %qD after instantiation "
5072                        "of %qD", decl, inst_decl);
5073         }
5074     }
5075
5076   return decl;
5077 }
5078
5079 /* PARM is a template parameter of some form; return the corresponding
5080    TEMPLATE_PARM_INDEX.  */
5081
5082 static tree
5083 get_template_parm_index (tree parm)
5084 {
5085   if (TREE_CODE (parm) == PARM_DECL
5086       || TREE_CODE (parm) == CONST_DECL)
5087     parm = DECL_INITIAL (parm);
5088   else if (TREE_CODE (parm) == TYPE_DECL
5089            || TREE_CODE (parm) == TEMPLATE_DECL)
5090     parm = TREE_TYPE (parm);
5091   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5092       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5093       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5094     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5095   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5096   return parm;
5097 }
5098
5099 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5100    parameter packs used by the template parameter PARM.  */
5101
5102 static void
5103 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5104 {
5105   /* A type parm can't refer to another parm.  */
5106   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5107     return;
5108   else if (TREE_CODE (parm) == PARM_DECL)
5109     {
5110       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5111                     ppd, ppd->visited);
5112       return;
5113     }
5114
5115   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5116
5117   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5118   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5119     {
5120       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5121       if (template_parameter_pack_p (p))
5122         /* Any packs in the type are expanded by this parameter.  */;
5123       else
5124         fixed_parameter_pack_p_1 (p, ppd);
5125     }
5126 }
5127
5128 /* PARM is a template parameter pack.  Return any parameter packs used in
5129    its type or the type of any of its template parameters.  If there are
5130    any such packs, it will be instantiated into a fixed template parameter
5131    list by partial instantiation rather than be fully deduced.  */
5132
5133 tree
5134 fixed_parameter_pack_p (tree parm)
5135 {
5136   /* This can only be true in a member template.  */
5137   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5138     return NULL_TREE;
5139   /* This can only be true for a parameter pack.  */
5140   if (!template_parameter_pack_p (parm))
5141     return NULL_TREE;
5142   /* A type parm can't refer to another parm.  */
5143   if (TREE_CODE (parm) == TYPE_DECL)
5144     return NULL_TREE;
5145
5146   tree parameter_packs = NULL_TREE;
5147   struct find_parameter_pack_data ppd;
5148   ppd.parameter_packs = &parameter_packs;
5149   ppd.visited = new hash_set<tree>;
5150   ppd.type_pack_expansion_p = false;
5151
5152   fixed_parameter_pack_p_1 (parm, &ppd);
5153
5154   delete ppd.visited;
5155   return parameter_packs;
5156 }
5157
5158 /* Check that a template declaration's use of default arguments and
5159    parameter packs is not invalid.  Here, PARMS are the template
5160    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5161    a primary template.  IS_PARTIAL is true if DECL is a partial
5162    specialization.
5163
5164    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5165    function template declaration or a friend class template
5166    declaration.  In the function case, 1 indicates a declaration, 2
5167    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5168    emitted for extraneous default arguments.
5169
5170    Returns TRUE if there were no errors found, FALSE otherwise. */
5171
5172 bool
5173 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5174                          bool is_partial, int is_friend_decl)
5175 {
5176   const char *msg;
5177   int last_level_to_check;
5178   tree parm_level;
5179   bool no_errors = true;
5180
5181   /* [temp.param]
5182
5183      A default template-argument shall not be specified in a
5184      function template declaration or a function template definition, nor
5185      in the template-parameter-list of the definition of a member of a
5186      class template.  */
5187
5188   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5189       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5190     /* You can't have a function template declaration in a local
5191        scope, nor you can you define a member of a class template in a
5192        local scope.  */
5193     return true;
5194
5195   if ((TREE_CODE (decl) == TYPE_DECL
5196        && TREE_TYPE (decl)
5197        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5198       || (TREE_CODE (decl) == FUNCTION_DECL
5199           && LAMBDA_FUNCTION_P (decl)))
5200     /* A lambda doesn't have an explicit declaration; don't complain
5201        about the parms of the enclosing class.  */
5202     return true;
5203
5204   if (current_class_type
5205       && !TYPE_BEING_DEFINED (current_class_type)
5206       && DECL_LANG_SPECIFIC (decl)
5207       && DECL_DECLARES_FUNCTION_P (decl)
5208       /* If this is either a friend defined in the scope of the class
5209          or a member function.  */
5210       && (DECL_FUNCTION_MEMBER_P (decl)
5211           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5212           : DECL_FRIEND_CONTEXT (decl)
5213           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5214           : false)
5215       /* And, if it was a member function, it really was defined in
5216          the scope of the class.  */
5217       && (!DECL_FUNCTION_MEMBER_P (decl)
5218           || DECL_INITIALIZED_IN_CLASS_P (decl)))
5219     /* We already checked these parameters when the template was
5220        declared, so there's no need to do it again now.  This function
5221        was defined in class scope, but we're processing its body now
5222        that the class is complete.  */
5223     return true;
5224
5225   /* Core issue 226 (C++0x only): the following only applies to class
5226      templates.  */
5227   if (is_primary
5228       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5229     {
5230       /* [temp.param]
5231
5232          If a template-parameter has a default template-argument, all
5233          subsequent template-parameters shall have a default
5234          template-argument supplied.  */
5235       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5236         {
5237           tree inner_parms = TREE_VALUE (parm_level);
5238           int ntparms = TREE_VEC_LENGTH (inner_parms);
5239           int seen_def_arg_p = 0;
5240           int i;
5241
5242           for (i = 0; i < ntparms; ++i)
5243             {
5244               tree parm = TREE_VEC_ELT (inner_parms, i);
5245
5246               if (parm == error_mark_node)
5247                 continue;
5248
5249               if (TREE_PURPOSE (parm))
5250                 seen_def_arg_p = 1;
5251               else if (seen_def_arg_p
5252                        && !template_parameter_pack_p (TREE_VALUE (parm)))
5253                 {
5254                   error ("no default argument for %qD", TREE_VALUE (parm));
5255                   /* For better subsequent error-recovery, we indicate that
5256                      there should have been a default argument.  */
5257                   TREE_PURPOSE (parm) = error_mark_node;
5258                   no_errors = false;
5259                 }
5260               else if (!is_partial
5261                        && !is_friend_decl
5262                        /* Don't complain about an enclosing partial
5263                           specialization.  */
5264                        && parm_level == parms
5265                        && TREE_CODE (decl) == TYPE_DECL
5266                        && i < ntparms - 1
5267                        && template_parameter_pack_p (TREE_VALUE (parm))
5268                        /* A fixed parameter pack will be partially
5269                           instantiated into a fixed length list.  */
5270                        && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5271                 {
5272                   /* A primary class template can only have one
5273                      parameter pack, at the end of the template
5274                      parameter list.  */
5275
5276                   error ("parameter pack %q+D must be at the end of the"
5277                          " template parameter list", TREE_VALUE (parm));
5278
5279                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5280                     = error_mark_node;
5281                   no_errors = false;
5282                 }
5283             }
5284         }
5285     }
5286
5287   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5288       || is_partial
5289       || !is_primary
5290       || is_friend_decl)
5291     /* For an ordinary class template, default template arguments are
5292        allowed at the innermost level, e.g.:
5293          template <class T = int>
5294          struct S {};
5295        but, in a partial specialization, they're not allowed even
5296        there, as we have in [temp.class.spec]:
5297
5298          The template parameter list of a specialization shall not
5299          contain default template argument values.
5300
5301        So, for a partial specialization, or for a function template
5302        (in C++98/C++03), we look at all of them.  */
5303     ;
5304   else
5305     /* But, for a primary class template that is not a partial
5306        specialization we look at all template parameters except the
5307        innermost ones.  */
5308     parms = TREE_CHAIN (parms);
5309
5310   /* Figure out what error message to issue.  */
5311   if (is_friend_decl == 2)
5312     msg = G_("default template arguments may not be used in function template "
5313              "friend re-declaration");
5314   else if (is_friend_decl)
5315     msg = G_("default template arguments may not be used in template "
5316              "friend declarations");
5317   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5318     msg = G_("default template arguments may not be used in function templates "
5319              "without %<-std=c++11%> or %<-std=gnu++11%>");
5320   else if (is_partial)
5321     msg = G_("default template arguments may not be used in "
5322              "partial specializations");
5323   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5324     msg = G_("default argument for template parameter for class enclosing %qD");
5325   else
5326     /* Per [temp.param]/9, "A default template-argument shall not be
5327        specified in the template-parameter-lists of the definition of
5328        a member of a class template that appears outside of the member's
5329        class.", thus if we aren't handling a member of a class template
5330        there is no need to examine the parameters.  */
5331     return true;
5332
5333   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5334     /* If we're inside a class definition, there's no need to
5335        examine the parameters to the class itself.  On the one
5336        hand, they will be checked when the class is defined, and,
5337        on the other, default arguments are valid in things like:
5338          template <class T = double>
5339          struct S { template <class U> void f(U); };
5340        Here the default argument for `S' has no bearing on the
5341        declaration of `f'.  */
5342     last_level_to_check = template_class_depth (current_class_type) + 1;
5343   else
5344     /* Check everything.  */
5345     last_level_to_check = 0;
5346
5347   for (parm_level = parms;
5348        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5349        parm_level = TREE_CHAIN (parm_level))
5350     {
5351       tree inner_parms = TREE_VALUE (parm_level);
5352       int i;
5353       int ntparms;
5354
5355       ntparms = TREE_VEC_LENGTH (inner_parms);
5356       for (i = 0; i < ntparms; ++i)
5357         {
5358           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5359             continue;
5360
5361           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5362             {
5363               if (msg)
5364                 {
5365                   no_errors = false;
5366                   if (is_friend_decl == 2)
5367                     return no_errors;
5368
5369                   error (msg, decl);
5370                   msg = 0;
5371                 }
5372
5373               /* Clear out the default argument so that we are not
5374                  confused later.  */
5375               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5376             }
5377         }
5378
5379       /* At this point, if we're still interested in issuing messages,
5380          they must apply to classes surrounding the object declared.  */
5381       if (msg)
5382         msg = G_("default argument for template parameter for class "
5383                  "enclosing %qD");
5384     }
5385
5386   return no_errors;
5387 }
5388
5389 /* Worker for push_template_decl_real, called via
5390    for_each_template_parm.  DATA is really an int, indicating the
5391    level of the parameters we are interested in.  If T is a template
5392    parameter of that level, return nonzero.  */
5393
5394 static int
5395 template_parm_this_level_p (tree t, void* data)
5396 {
5397   int this_level = *(int *)data;
5398   int level;
5399
5400   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5401     level = TEMPLATE_PARM_LEVEL (t);
5402   else
5403     level = TEMPLATE_TYPE_LEVEL (t);
5404   return level == this_level;
5405 }
5406
5407 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5408    DATA is really an int, indicating the innermost outer level of parameters.
5409    If T is a template parameter of that level or further out, return
5410    nonzero.  */
5411
5412 static int
5413 template_parm_outer_level (tree t, void *data)
5414 {
5415   int this_level = *(int *)data;
5416   int level;
5417
5418   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5419     level = TEMPLATE_PARM_LEVEL (t);
5420   else
5421     level = TEMPLATE_TYPE_LEVEL (t);
5422   return level <= this_level;
5423 }
5424
5425 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5426    parameters given by current_template_args, or reuses a
5427    previously existing one, if appropriate.  Returns the DECL, or an
5428    equivalent one, if it is replaced via a call to duplicate_decls.
5429
5430    If IS_FRIEND is true, DECL is a friend declaration.  */
5431
5432 tree
5433 push_template_decl_real (tree decl, bool is_friend)
5434 {
5435   tree tmpl;
5436   tree args;
5437   tree info;
5438   tree ctx;
5439   bool is_primary;
5440   bool is_partial;
5441   int new_template_p = 0;
5442   /* True if the template is a member template, in the sense of
5443      [temp.mem].  */
5444   bool member_template_p = false;
5445
5446   if (decl == error_mark_node || !current_template_parms)
5447     return error_mark_node;
5448
5449   /* See if this is a partial specialization.  */
5450   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5451                  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5452                  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5453                 || (VAR_P (decl)
5454                     && DECL_LANG_SPECIFIC (decl)
5455                     && DECL_TEMPLATE_SPECIALIZATION (decl)
5456                     && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5457
5458   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5459     is_friend = true;
5460
5461   if (is_friend)
5462     /* For a friend, we want the context of the friend, not
5463        the type of which it is a friend.  */
5464     ctx = CP_DECL_CONTEXT (decl);
5465   else if (CP_DECL_CONTEXT (decl)
5466            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5467     /* In the case of a virtual function, we want the class in which
5468        it is defined.  */
5469     ctx = CP_DECL_CONTEXT (decl);
5470   else
5471     /* Otherwise, if we're currently defining some class, the DECL
5472        is assumed to be a member of the class.  */
5473     ctx = current_scope ();
5474
5475   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5476     ctx = NULL_TREE;
5477
5478   if (!DECL_CONTEXT (decl))
5479     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5480
5481   /* See if this is a primary template.  */
5482   if (is_friend && ctx
5483       && uses_template_parms_level (ctx, processing_template_decl))
5484     /* A friend template that specifies a class context, i.e.
5485          template <typename T> friend void A<T>::f();
5486        is not primary.  */
5487     is_primary = false;
5488   else if (TREE_CODE (decl) == TYPE_DECL
5489            && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5490     is_primary = false;
5491   else
5492     is_primary = template_parm_scope_p ();
5493
5494   if (is_primary)
5495     {
5496       warning (OPT_Wtemplates, "template %qD declared", decl);
5497
5498       if (DECL_CLASS_SCOPE_P (decl))
5499         member_template_p = true;
5500       if (TREE_CODE (decl) == TYPE_DECL
5501           && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5502         {
5503           error ("template class without a name");
5504           return error_mark_node;
5505         }
5506       else if (TREE_CODE (decl) == FUNCTION_DECL)
5507         {
5508           if (member_template_p)
5509             {
5510               if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5511                 error ("member template %qD may not have virt-specifiers", decl);
5512             }
5513           if (DECL_DESTRUCTOR_P (decl))
5514             {
5515               /* [temp.mem]
5516
5517                  A destructor shall not be a member template.  */
5518               error ("destructor %qD declared as member template", decl);
5519               return error_mark_node;
5520             }
5521           if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5522               && (!prototype_p (TREE_TYPE (decl))
5523                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5524                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5525                   || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5526                       == void_list_node)))
5527             {
5528               /* [basic.stc.dynamic.allocation]
5529
5530                  An allocation function can be a function
5531                  template. ... Template allocation functions shall
5532                  have two or more parameters.  */
5533               error ("invalid template declaration of %qD", decl);
5534               return error_mark_node;
5535             }
5536         }
5537       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5538                && CLASS_TYPE_P (TREE_TYPE (decl)))
5539         {
5540           /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5541           tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5542           for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5543             {
5544               tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5545               if (TREE_CODE (t) == TYPE_DECL)
5546                 t = TREE_TYPE (t);
5547               if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5548                 TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5549             }
5550         }
5551       else if (TREE_CODE (decl) == TYPE_DECL
5552                && TYPE_DECL_ALIAS_P (decl))
5553         /* alias-declaration */
5554         gcc_assert (!DECL_ARTIFICIAL (decl));
5555       else if (VAR_P (decl))
5556         /* C++14 variable template. */;
5557       else
5558         {
5559           error ("template declaration of %q#D", decl);
5560           return error_mark_node;
5561         }
5562     }
5563
5564   /* Check to see that the rules regarding the use of default
5565      arguments are not being violated.  We check args for a friend
5566      functions when we know whether it's a definition, introducing
5567      declaration or re-declaration.  */
5568   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5569     check_default_tmpl_args (decl, current_template_parms,
5570                              is_primary, is_partial, is_friend);
5571
5572   /* Ensure that there are no parameter packs in the type of this
5573      declaration that have not been expanded.  */
5574   if (TREE_CODE (decl) == FUNCTION_DECL)
5575     {
5576       /* Check each of the arguments individually to see if there are
5577          any bare parameter packs.  */
5578       tree type = TREE_TYPE (decl);
5579       tree arg = DECL_ARGUMENTS (decl);
5580       tree argtype = TYPE_ARG_TYPES (type);
5581
5582       while (arg && argtype)
5583         {
5584           if (!DECL_PACK_P (arg)
5585               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5586             {
5587             /* This is a PARM_DECL that contains unexpanded parameter
5588                packs. We have already complained about this in the
5589                check_for_bare_parameter_packs call, so just replace
5590                these types with ERROR_MARK_NODE.  */
5591               TREE_TYPE (arg) = error_mark_node;
5592               TREE_VALUE (argtype) = error_mark_node;
5593             }
5594
5595           arg = DECL_CHAIN (arg);
5596           argtype = TREE_CHAIN (argtype);
5597         }
5598
5599       /* Check for bare parameter packs in the return type and the
5600          exception specifiers.  */
5601       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5602         /* Errors were already issued, set return type to int
5603            as the frontend doesn't expect error_mark_node as
5604            the return type.  */
5605         TREE_TYPE (type) = integer_type_node;
5606       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5607         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5608     }
5609   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5610                                             && TYPE_DECL_ALIAS_P (decl))
5611                                            ? DECL_ORIGINAL_TYPE (decl)
5612                                            : TREE_TYPE (decl)))
5613     {
5614       TREE_TYPE (decl) = error_mark_node;
5615       return error_mark_node;
5616     }
5617
5618   if (is_partial)
5619     return process_partial_specialization (decl);
5620
5621   args = current_template_args ();
5622
5623   if (!ctx
5624       || TREE_CODE (ctx) == FUNCTION_DECL
5625       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5626       || (TREE_CODE (decl) == TYPE_DECL
5627           && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5628       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5629     {
5630       if (DECL_LANG_SPECIFIC (decl)
5631           && DECL_TEMPLATE_INFO (decl)
5632           && DECL_TI_TEMPLATE (decl))
5633         tmpl = DECL_TI_TEMPLATE (decl);
5634       /* If DECL is a TYPE_DECL for a class-template, then there won't
5635          be DECL_LANG_SPECIFIC.  The information equivalent to
5636          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5637       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5638                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5639                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5640         {
5641           /* Since a template declaration already existed for this
5642              class-type, we must be redeclaring it here.  Make sure
5643              that the redeclaration is valid.  */
5644           redeclare_class_template (TREE_TYPE (decl),
5645                                     current_template_parms,
5646                                     current_template_constraints ());
5647           /* We don't need to create a new TEMPLATE_DECL; just use the
5648              one we already had.  */
5649           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5650         }
5651       else
5652         {
5653           tmpl = build_template_decl (decl, current_template_parms,
5654                                       member_template_p);
5655           new_template_p = 1;
5656
5657           if (DECL_LANG_SPECIFIC (decl)
5658               && DECL_TEMPLATE_SPECIALIZATION (decl))
5659             {
5660               /* A specialization of a member template of a template
5661                  class.  */
5662               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5663               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5664               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5665             }
5666         }
5667     }
5668   else
5669     {
5670       tree a, t, current, parms;
5671       int i;
5672       tree tinfo = get_template_info (decl);
5673
5674       if (!tinfo)
5675         {
5676           error ("template definition of non-template %q#D", decl);
5677           return error_mark_node;
5678         }
5679
5680       tmpl = TI_TEMPLATE (tinfo);
5681
5682       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5683           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5684           && DECL_TEMPLATE_SPECIALIZATION (decl)
5685           && DECL_MEMBER_TEMPLATE_P (tmpl))
5686         {
5687           tree new_tmpl;
5688
5689           /* The declaration is a specialization of a member
5690              template, declared outside the class.  Therefore, the
5691              innermost template arguments will be NULL, so we
5692              replace them with the arguments determined by the
5693              earlier call to check_explicit_specialization.  */
5694           args = DECL_TI_ARGS (decl);
5695
5696           new_tmpl
5697             = build_template_decl (decl, current_template_parms,
5698                                    member_template_p);
5699           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5700           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5701           DECL_TI_TEMPLATE (decl) = new_tmpl;
5702           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5703           DECL_TEMPLATE_INFO (new_tmpl)
5704             = build_template_info (tmpl, args);
5705
5706           register_specialization (new_tmpl,
5707                                    most_general_template (tmpl),
5708                                    args,
5709                                    is_friend, 0);
5710           return decl;
5711         }
5712
5713       /* Make sure the template headers we got make sense.  */
5714
5715       parms = DECL_TEMPLATE_PARMS (tmpl);
5716       i = TMPL_PARMS_DEPTH (parms);
5717       if (TMPL_ARGS_DEPTH (args) != i)
5718         {
5719           error ("expected %d levels of template parms for %q#D, got %d",
5720                  i, decl, TMPL_ARGS_DEPTH (args));
5721           DECL_INTERFACE_KNOWN (decl) = 1;
5722           return error_mark_node;
5723         }
5724       else
5725         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5726           {
5727             a = TMPL_ARGS_LEVEL (args, i);
5728             t = INNERMOST_TEMPLATE_PARMS (parms);
5729
5730             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5731               {
5732                 if (current == decl)
5733                   error ("got %d template parameters for %q#D",
5734                          TREE_VEC_LENGTH (a), decl);
5735                 else
5736                   error ("got %d template parameters for %q#T",
5737                          TREE_VEC_LENGTH (a), current);
5738                 error ("  but %d required", TREE_VEC_LENGTH (t));
5739                 /* Avoid crash in import_export_decl.  */
5740                 DECL_INTERFACE_KNOWN (decl) = 1;
5741                 return error_mark_node;
5742               }
5743
5744             if (current == decl)
5745               current = ctx;
5746             else if (current == NULL_TREE)
5747               /* Can happen in erroneous input.  */
5748               break;
5749             else
5750               current = get_containing_scope (current);
5751           }
5752
5753       /* Check that the parms are used in the appropriate qualifying scopes
5754          in the declarator.  */
5755       if (!comp_template_args
5756           (TI_ARGS (tinfo),
5757            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5758         {
5759           error ("template arguments to %qD do not match original "
5760                  "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5761           if (!uses_template_parms (TI_ARGS (tinfo)))
5762             inform (input_location, "use %<template<>%> for"
5763                     " an explicit specialization");
5764           /* Avoid crash in import_export_decl.  */
5765           DECL_INTERFACE_KNOWN (decl) = 1;
5766           return error_mark_node;
5767         }
5768     }
5769
5770   DECL_TEMPLATE_RESULT (tmpl) = decl;
5771   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5772
5773   /* Push template declarations for global functions and types.  Note
5774      that we do not try to push a global template friend declared in a
5775      template class; such a thing may well depend on the template
5776      parameters of the class.  */
5777   if (new_template_p && !ctx
5778       && !(is_friend && template_class_depth (current_class_type) > 0))
5779     {
5780       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5781       if (tmpl == error_mark_node)
5782         return error_mark_node;
5783
5784       /* Hide template friend classes that haven't been declared yet.  */
5785       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5786         {
5787           DECL_ANTICIPATED (tmpl) = 1;
5788           DECL_FRIEND_P (tmpl) = 1;
5789         }
5790     }
5791
5792   if (is_primary)
5793     {
5794       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5795
5796       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5797
5798       /* Give template template parms a DECL_CONTEXT of the template
5799          for which they are a parameter.  */
5800       parms = INNERMOST_TEMPLATE_PARMS (parms);
5801       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5802         {
5803           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5804           if (TREE_CODE (parm) == TEMPLATE_DECL)
5805             DECL_CONTEXT (parm) = tmpl;
5806         }
5807
5808       if (TREE_CODE (decl) == TYPE_DECL
5809           && TYPE_DECL_ALIAS_P (decl)
5810           && complex_alias_template_p (tmpl))
5811         TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5812     }
5813
5814   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5815      back to its most general template.  If TMPL is a specialization,
5816      ARGS may only have the innermost set of arguments.  Add the missing
5817      argument levels if necessary.  */
5818   if (DECL_TEMPLATE_INFO (tmpl))
5819     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5820
5821   info = build_template_info (tmpl, args);
5822
5823   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5824     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5825   else
5826     {
5827       if (is_primary)
5828         retrofit_lang_decl (decl);
5829       if (DECL_LANG_SPECIFIC (decl))
5830         DECL_TEMPLATE_INFO (decl) = info;
5831     }
5832
5833   if (flag_implicit_templates
5834       && !is_friend
5835       && TREE_PUBLIC (decl)
5836       && VAR_OR_FUNCTION_DECL_P (decl))
5837     /* Set DECL_COMDAT on template instantiations; if we force
5838        them to be emitted by explicit instantiation or -frepo,
5839        mark_needed will tell cgraph to do the right thing.  */
5840     DECL_COMDAT (decl) = true;
5841
5842   return DECL_TEMPLATE_RESULT (tmpl);
5843 }
5844
5845 tree
5846 push_template_decl (tree decl)
5847 {
5848   return push_template_decl_real (decl, false);
5849 }
5850
5851 /* FN is an inheriting constructor that inherits from the constructor
5852    template INHERITED; turn FN into a constructor template with a matching
5853    template header.  */
5854
5855 tree
5856 add_inherited_template_parms (tree fn, tree inherited)
5857 {
5858   tree inner_parms
5859     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5860   inner_parms = copy_node (inner_parms);
5861   tree parms
5862     = tree_cons (size_int (processing_template_decl + 1),
5863                  inner_parms, current_template_parms);
5864   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5865   tree args = template_parms_to_args (parms);
5866   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5867   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5868   DECL_TEMPLATE_RESULT (tmpl) = fn;
5869   DECL_ARTIFICIAL (tmpl) = true;
5870   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5871   return tmpl;
5872 }
5873
5874 /* Called when a class template TYPE is redeclared with the indicated
5875    template PARMS, e.g.:
5876
5877      template <class T> struct S;
5878      template <class T> struct S {};  */
5879
5880 bool
5881 redeclare_class_template (tree type, tree parms, tree cons)
5882 {
5883   tree tmpl;
5884   tree tmpl_parms;
5885   int i;
5886
5887   if (!TYPE_TEMPLATE_INFO (type))
5888     {
5889       error ("%qT is not a template type", type);
5890       return false;
5891     }
5892
5893   tmpl = TYPE_TI_TEMPLATE (type);
5894   if (!PRIMARY_TEMPLATE_P (tmpl))
5895     /* The type is nested in some template class.  Nothing to worry
5896        about here; there are no new template parameters for the nested
5897        type.  */
5898     return true;
5899
5900   if (!parms)
5901     {
5902       error ("template specifiers not specified in declaration of %qD",
5903              tmpl);
5904       return false;
5905     }
5906
5907   parms = INNERMOST_TEMPLATE_PARMS (parms);
5908   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5909
5910   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5911     {
5912       error_n (input_location, TREE_VEC_LENGTH (parms),
5913                "redeclared with %d template parameter",
5914                "redeclared with %d template parameters",
5915                TREE_VEC_LENGTH (parms));
5916       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5917                 "previous declaration %qD used %d template parameter",
5918                 "previous declaration %qD used %d template parameters",
5919                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5920       return false;
5921     }
5922
5923   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5924     {
5925       tree tmpl_parm;
5926       tree parm;
5927       tree tmpl_default;
5928       tree parm_default;
5929
5930       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5931           || TREE_VEC_ELT (parms, i) == error_mark_node)
5932         continue;
5933
5934       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5935       if (error_operand_p (tmpl_parm))
5936         return false;
5937
5938       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5939       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5940       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5941
5942       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5943          TEMPLATE_DECL.  */
5944       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5945           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5946               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5947           || (TREE_CODE (tmpl_parm) != PARM_DECL
5948               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5949                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5950           || (TREE_CODE (tmpl_parm) == PARM_DECL
5951               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5952                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5953         {
5954           error ("template parameter %q+#D", tmpl_parm);
5955           error ("redeclared here as %q#D", parm);
5956           return false;
5957         }
5958
5959       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5960         {
5961           /* We have in [temp.param]:
5962
5963              A template-parameter may not be given default arguments
5964              by two different declarations in the same scope.  */
5965           error_at (input_location, "redefinition of default argument for %q#D", parm);
5966           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5967                   "original definition appeared here");
5968           return false;
5969         }
5970
5971       if (parm_default != NULL_TREE)
5972         /* Update the previous template parameters (which are the ones
5973            that will really count) with the new default value.  */
5974         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5975       else if (tmpl_default != NULL_TREE)
5976         /* Update the new parameters, too; they'll be used as the
5977            parameters for any members.  */
5978         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5979
5980       /* Give each template template parm in this redeclaration a
5981          DECL_CONTEXT of the template for which they are a parameter.  */
5982       if (TREE_CODE (parm) == TEMPLATE_DECL)
5983         {
5984           gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5985           DECL_CONTEXT (parm) = tmpl;
5986         }
5987
5988       if (TREE_CODE (parm) == TYPE_DECL)
5989         TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
5990     }
5991
5992   // Cannot redeclare a class template with a different set of constraints.
5993   if (!equivalent_constraints (get_constraints (tmpl), cons))
5994     {
5995       error_at (input_location, "redeclaration %q#D with different "
5996                                 "constraints", tmpl);
5997       inform (DECL_SOURCE_LOCATION (tmpl),
5998               "original declaration appeared here");
5999     }
6000
6001     return true;
6002 }
6003
6004 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6005    to be used when the caller has already checked
6006    (processing_template_decl
6007     && !instantiation_dependent_expression_p (expr)
6008     && potential_constant_expression (expr))
6009    and cleared processing_template_decl.  */
6010
6011 tree
6012 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6013 {
6014   return tsubst_copy_and_build (expr,
6015                                 /*args=*/NULL_TREE,
6016                                 complain,
6017                                 /*in_decl=*/NULL_TREE,
6018                                 /*function_p=*/false,
6019                                 /*integral_constant_expression_p=*/true);
6020 }
6021
6022 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6023    (possibly simplified) expression.  */
6024
6025 tree
6026 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6027 {
6028   if (expr == NULL_TREE)
6029     return NULL_TREE;
6030
6031   /* If we're in a template, but EXPR isn't value dependent, simplify
6032      it.  We're supposed to treat:
6033
6034        template <typename T> void f(T[1 + 1]);
6035        template <typename T> void f(T[2]);
6036
6037      as two declarations of the same function, for example.  */
6038   if (processing_template_decl
6039       && is_nondependent_constant_expression (expr))
6040     {
6041       processing_template_decl_sentinel s;
6042       expr = instantiate_non_dependent_expr_internal (expr, complain);
6043     }
6044   return expr;
6045 }
6046
6047 tree
6048 instantiate_non_dependent_expr (tree expr)
6049 {
6050   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6051 }
6052
6053 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6054    an uninstantiated expression.  */
6055
6056 tree
6057 instantiate_non_dependent_or_null (tree expr)
6058 {
6059   if (expr == NULL_TREE)
6060     return NULL_TREE;
6061   if (processing_template_decl)
6062     {
6063       if (!is_nondependent_constant_expression (expr))
6064         expr = NULL_TREE;
6065       else
6066         {
6067           processing_template_decl_sentinel s;
6068           expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6069         }
6070     }
6071   return expr;
6072 }
6073
6074 /* True iff T is a specialization of a variable template.  */
6075
6076 bool
6077 variable_template_specialization_p (tree t)
6078 {
6079   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6080     return false;
6081   tree tmpl = DECL_TI_TEMPLATE (t);
6082   return variable_template_p (tmpl);
6083 }
6084
6085 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6086    template declaration, or a TYPE_DECL for an alias declaration.  */
6087
6088 bool
6089 alias_type_or_template_p (tree t)
6090 {
6091   if (t == NULL_TREE)
6092     return false;
6093   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6094           || (TYPE_P (t)
6095               && TYPE_NAME (t)
6096               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6097           || DECL_ALIAS_TEMPLATE_P (t));
6098 }
6099
6100 /* Return TRUE iff T is a specialization of an alias template.  */
6101
6102 bool
6103 alias_template_specialization_p (const_tree t)
6104 {
6105   /* It's an alias template specialization if it's an alias and its
6106      TYPE_NAME is a specialization of a primary template.  */
6107   if (TYPE_ALIAS_P (t))
6108     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6109       return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6110
6111   return false;
6112 }
6113
6114 /* An alias template is complex from a SFINAE perspective if a template-id
6115    using that alias can be ill-formed when the expansion is not, as with
6116    the void_t template.  We determine this by checking whether the
6117    expansion for the alias template uses all its template parameters.  */
6118
6119 struct uses_all_template_parms_data
6120 {
6121   int level;
6122   bool *seen;
6123 };
6124
6125 static int
6126 uses_all_template_parms_r (tree t, void *data_)
6127 {
6128   struct uses_all_template_parms_data &data
6129     = *(struct uses_all_template_parms_data*)data_;
6130   tree idx = get_template_parm_index (t);
6131
6132   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6133     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6134   return 0;
6135 }
6136
6137 static bool
6138 complex_alias_template_p (const_tree tmpl)
6139 {
6140   struct uses_all_template_parms_data data;
6141   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6142   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6143   data.level = TMPL_PARMS_DEPTH (parms);
6144   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6145   data.seen = XALLOCAVEC (bool, len);
6146   for (int i = 0; i < len; ++i)
6147     data.seen[i] = false;
6148
6149   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6150   for (int i = 0; i < len; ++i)
6151     if (!data.seen[i])
6152       return true;
6153   return false;
6154 }
6155
6156 /* Return TRUE iff T is a specialization of a complex alias template with
6157    dependent template-arguments.  */
6158
6159 bool
6160 dependent_alias_template_spec_p (const_tree t)
6161 {
6162   if (!alias_template_specialization_p (t))
6163     return false;
6164
6165   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6166   if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6167     return false;
6168
6169   tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6170   if (!any_dependent_template_arguments_p (args))
6171     return false;
6172
6173   return true;
6174 }
6175
6176 /* Return the number of innermost template parameters in TMPL.  */
6177
6178 static int
6179 num_innermost_template_parms (tree tmpl)
6180 {
6181   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6182   return TREE_VEC_LENGTH (parms);
6183 }
6184
6185 /* Return either TMPL or another template that it is equivalent to under DR
6186    1286: An alias that just changes the name of a template is equivalent to
6187    the other template.  */
6188
6189 static tree
6190 get_underlying_template (tree tmpl)
6191 {
6192   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6193   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6194     {
6195       /* Determine if the alias is equivalent to an underlying template.  */
6196       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6197       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6198       if (!tinfo)
6199         break;
6200
6201       tree underlying = TI_TEMPLATE (tinfo);
6202       if (!PRIMARY_TEMPLATE_P (underlying)
6203           || (num_innermost_template_parms (tmpl)
6204               != num_innermost_template_parms (underlying)))
6205         break;
6206
6207       tree alias_args = INNERMOST_TEMPLATE_ARGS
6208         (template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6209       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6210         break;
6211
6212       /* Alias is equivalent.  Strip it and repeat.  */
6213       tmpl = underlying;
6214     }
6215
6216   return tmpl;
6217 }
6218
6219 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6220    must be a reference-to-function or a pointer-to-function type, as specified
6221    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6222    and check that the resulting function has external linkage.  */
6223
6224 static tree
6225 convert_nontype_argument_function (tree type, tree expr,
6226                                    tsubst_flags_t complain)
6227 {
6228   tree fns = expr;
6229   tree fn, fn_no_ptr;
6230   linkage_kind linkage;
6231
6232   fn = instantiate_type (type, fns, tf_none);
6233   if (fn == error_mark_node)
6234     return error_mark_node;
6235
6236   if (value_dependent_expression_p (fn))
6237     goto accept;
6238
6239   fn_no_ptr = strip_fnptr_conv (fn);
6240   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6241     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6242   if (BASELINK_P (fn_no_ptr))
6243     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6244
6245   /* [temp.arg.nontype]/1
6246
6247      A template-argument for a non-type, non-template template-parameter
6248      shall be one of:
6249      [...]
6250      -- the address of an object or function with external [C++11: or
6251         internal] linkage.  */
6252
6253   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6254   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6255     {
6256       if (complain & tf_error)
6257         {
6258           error ("%qE is not a valid template argument for type %qT",
6259                  expr, type);
6260           if (TYPE_PTR_P (type))
6261             inform (input_location, "it must be the address of a function "
6262                     "with external linkage");
6263           else
6264             inform (input_location, "it must be the name of a function with "
6265                     "external linkage");
6266         }
6267       return NULL_TREE;
6268     }
6269
6270   linkage = decl_linkage (fn_no_ptr);
6271   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6272     {
6273       if (complain & tf_error)
6274         {
6275           if (cxx_dialect >= cxx11)
6276             error ("%qE is not a valid template argument for type %qT "
6277                    "because %qD has no linkage",
6278                    expr, type, fn_no_ptr);
6279           else
6280             error ("%qE is not a valid template argument for type %qT "
6281                    "because %qD does not have external linkage",
6282                    expr, type, fn_no_ptr);
6283         }
6284       return NULL_TREE;
6285     }
6286
6287  accept:
6288   if (TYPE_REF_P (type))
6289     {
6290       if (REFERENCE_REF_P (fn))
6291         fn = TREE_OPERAND (fn, 0);
6292       else
6293         fn = build_address (fn);
6294     }
6295   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6296     fn = build_nop (type, fn);
6297
6298   return fn;
6299 }
6300
6301 /* Subroutine of convert_nontype_argument.
6302    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6303    Emit an error otherwise.  */
6304
6305 static bool
6306 check_valid_ptrmem_cst_expr (tree type, tree expr,
6307                              tsubst_flags_t complain)
6308 {
6309   location_t loc = cp_expr_loc_or_input_loc (expr);
6310   tree orig_expr = expr;
6311   STRIP_NOPS (expr);
6312   if (null_ptr_cst_p (expr))
6313     return true;
6314   if (TREE_CODE (expr) == PTRMEM_CST
6315       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6316                       PTRMEM_CST_CLASS (expr)))
6317     return true;
6318   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6319     return true;
6320   if (processing_template_decl
6321       && TREE_CODE (expr) == ADDR_EXPR
6322       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6323     return true;
6324   if (complain & tf_error)
6325     {
6326       error_at (loc, "%qE is not a valid template argument for type %qT",
6327                 orig_expr, type);
6328       if (TREE_CODE (expr) != PTRMEM_CST)
6329         inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6330       else
6331         inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6332     }
6333   return false;
6334 }
6335
6336 /* Returns TRUE iff the address of OP is value-dependent.
6337
6338    14.6.2.4 [temp.dep.temp]:
6339    A non-integral non-type template-argument is dependent if its type is
6340    dependent or it has either of the following forms
6341      qualified-id
6342      & qualified-id
6343    and contains a nested-name-specifier which specifies a class-name that
6344    names a dependent type.
6345
6346    We generalize this to just say that the address of a member of a
6347    dependent class is value-dependent; the above doesn't cover the
6348    address of a static data member named with an unqualified-id.  */
6349
6350 static bool
6351 has_value_dependent_address (tree op)
6352 {
6353   /* We could use get_inner_reference here, but there's no need;
6354      this is only relevant for template non-type arguments, which
6355      can only be expressed as &id-expression.  */
6356   if (DECL_P (op))
6357     {
6358       tree ctx = CP_DECL_CONTEXT (op);
6359       if (TYPE_P (ctx) && dependent_type_p (ctx))
6360         return true;
6361     }
6362
6363   return false;
6364 }
6365
6366 /* The next set of functions are used for providing helpful explanatory
6367    diagnostics for failed overload resolution.  Their messages should be
6368    indented by two spaces for consistency with the messages in
6369    call.c  */
6370
6371 static int
6372 unify_success (bool /*explain_p*/)
6373 {
6374   return 0;
6375 }
6376
6377 /* Other failure functions should call this one, to provide a single function
6378    for setting a breakpoint on.  */
6379
6380 static int
6381 unify_invalid (bool /*explain_p*/)
6382 {
6383   return 1;
6384 }
6385
6386 static int
6387 unify_parameter_deduction_failure (bool explain_p, tree parm)
6388 {
6389   if (explain_p)
6390     inform (input_location,
6391             "  couldn%'t deduce template parameter %qD", parm);
6392   return unify_invalid (explain_p);
6393 }
6394
6395 static int
6396 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6397 {
6398   if (explain_p)
6399     inform (input_location,
6400             "  types %qT and %qT have incompatible cv-qualifiers",
6401             parm, arg);
6402   return unify_invalid (explain_p);
6403 }
6404
6405 static int
6406 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6407 {
6408   if (explain_p)
6409     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6410   return unify_invalid (explain_p);
6411 }
6412
6413 static int
6414 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6415 {
6416   if (explain_p)
6417     inform (input_location,
6418             "  template parameter %qD is not a parameter pack, but "
6419             "argument %qD is",
6420             parm, arg);
6421   return unify_invalid (explain_p);
6422 }
6423
6424 static int
6425 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6426 {
6427   if (explain_p)
6428     inform (input_location,
6429             "  template argument %qE does not match "
6430             "pointer-to-member constant %qE",
6431             arg, parm);
6432   return unify_invalid (explain_p);
6433 }
6434
6435 static int
6436 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6437 {
6438   if (explain_p)
6439     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6440   return unify_invalid (explain_p);
6441 }
6442
6443 static int
6444 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6445 {
6446   if (explain_p)
6447     inform (input_location,
6448             "  inconsistent parameter pack deduction with %qT and %qT",
6449             old_arg, new_arg);
6450   return unify_invalid (explain_p);
6451 }
6452
6453 static int
6454 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6455 {
6456   if (explain_p)
6457     {
6458       if (TYPE_P (parm))
6459         inform (input_location,
6460                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
6461                 parm, first, second);
6462       else
6463         inform (input_location,
6464                 "  deduced conflicting values for non-type parameter "
6465                 "%qE (%qE and %qE)", parm, first, second);
6466     }
6467   return unify_invalid (explain_p);
6468 }
6469
6470 static int
6471 unify_vla_arg (bool explain_p, tree arg)
6472 {
6473   if (explain_p)
6474     inform (input_location,
6475             "  variable-sized array type %qT is not "
6476             "a valid template argument",
6477             arg);
6478   return unify_invalid (explain_p);
6479 }
6480
6481 static int
6482 unify_method_type_error (bool explain_p, tree arg)
6483 {
6484   if (explain_p)
6485     inform (input_location,
6486             "  member function type %qT is not a valid template argument",
6487             arg);
6488   return unify_invalid (explain_p);
6489 }
6490
6491 static int
6492 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6493 {
6494   if (explain_p)
6495     {
6496       if (least_p)
6497         inform_n (input_location, wanted,
6498                   "  candidate expects at least %d argument, %d provided",
6499                   "  candidate expects at least %d arguments, %d provided",
6500                   wanted, have);
6501       else
6502         inform_n (input_location, wanted,
6503                   "  candidate expects %d argument, %d provided",
6504                   "  candidate expects %d arguments, %d provided",
6505                   wanted, have);
6506     }
6507   return unify_invalid (explain_p);
6508 }
6509
6510 static int
6511 unify_too_many_arguments (bool explain_p, int have, int wanted)
6512 {
6513   return unify_arity (explain_p, have, wanted);
6514 }
6515
6516 static int
6517 unify_too_few_arguments (bool explain_p, int have, int wanted,
6518                          bool least_p = false)
6519 {
6520   return unify_arity (explain_p, have, wanted, least_p);
6521 }
6522
6523 static int
6524 unify_arg_conversion (bool explain_p, tree to_type,
6525                       tree from_type, tree arg)
6526 {
6527   if (explain_p)
6528     inform (cp_expr_loc_or_input_loc (arg),
6529             "  cannot convert %qE (type %qT) to type %qT",
6530             arg, from_type, to_type);
6531   return unify_invalid (explain_p);
6532 }
6533
6534 static int
6535 unify_no_common_base (bool explain_p, enum template_base_result r,
6536                       tree parm, tree arg)
6537 {
6538   if (explain_p)
6539     switch (r)
6540       {
6541       case tbr_ambiguous_baseclass:
6542         inform (input_location, "  %qT is an ambiguous base class of %qT",
6543                 parm, arg);
6544         break;
6545       default:
6546         inform (input_location, "  %qT is not derived from %qT", arg, parm);
6547         break;
6548       }
6549   return unify_invalid (explain_p);
6550 }
6551
6552 static int
6553 unify_inconsistent_template_template_parameters (bool explain_p)
6554 {
6555   if (explain_p)
6556     inform (input_location,
6557             "  template parameters of a template template argument are "
6558             "inconsistent with other deduced template arguments");
6559   return unify_invalid (explain_p);
6560 }
6561
6562 static int
6563 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6564 {
6565   if (explain_p)
6566     inform (input_location,
6567             "  cannot deduce a template for %qT from non-template type %qT",
6568             parm, arg);
6569   return unify_invalid (explain_p);
6570 }
6571
6572 static int
6573 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6574 {
6575   if (explain_p)
6576     inform (input_location,
6577             "  template argument %qE does not match %qE", arg, parm);
6578   return unify_invalid (explain_p);
6579 }
6580
6581 /* True if T is a C++20 template parameter object to store the argument for a
6582    template parameter of class type.  */
6583
6584 bool
6585 template_parm_object_p (const_tree t)
6586 {
6587   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6588           && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6589 }
6590
6591 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6592    argument for TYPE, points to an unsuitable object.  */
6593
6594 static bool
6595 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
6596 {
6597   switch (TREE_CODE (expr))
6598     {
6599     CASE_CONVERT:
6600       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
6601                                        complain);
6602
6603     case TARGET_EXPR:
6604       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
6605                                        complain);
6606
6607     case CONSTRUCTOR:
6608       {
6609         unsigned i; tree elt;
6610         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
6611           if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
6612             return true;
6613       }
6614       break;
6615
6616     case ADDR_EXPR:
6617       {
6618         tree decl = TREE_OPERAND (expr, 0);
6619
6620         if (!VAR_P (decl))
6621           {
6622             if (complain & tf_error)
6623               error ("%qE is not a valid template argument of type %qT "
6624                      "because %qE is not a variable", expr, type, decl);
6625             return true;
6626           }
6627         else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6628           {
6629             if (complain & tf_error)
6630               error ("%qE is not a valid template argument of type %qT "
6631                      "in C++98 because %qD does not have external linkage",
6632                      expr, type, decl);
6633             return true;
6634           }
6635         else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6636                  && decl_linkage (decl) == lk_none)
6637           {
6638             if (complain & tf_error)
6639               error ("%qE is not a valid template argument of type %qT "
6640                      "because %qD has no linkage", expr, type, decl);
6641             return true;
6642           }
6643         /* C++17: For a non-type template-parameter of reference or pointer
6644            type, the value of the constant expression shall not refer to (or
6645            for a pointer type, shall not be the address of):
6646            * a subobject (4.5),
6647            * a temporary object (15.2),
6648            * a string literal (5.13.5),
6649            * the result of a typeid expression (8.2.8), or
6650            * a predefined __func__ variable (11.4.1).  */
6651         else if (DECL_ARTIFICIAL (decl))
6652           {
6653             if (complain & tf_error)
6654               error ("the address of %qD is not a valid template argument",
6655                      decl);
6656             return true;
6657           }
6658         else if (!same_type_ignoring_top_level_qualifiers_p
6659                  (strip_array_types (TREE_TYPE (type)),
6660                   strip_array_types (TREE_TYPE (decl))))
6661           {
6662             if (complain & tf_error)
6663               error ("the address of the %qT subobject of %qD is not a "
6664                      "valid template argument", TREE_TYPE (type), decl);
6665             return true;
6666           }
6667         else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6668           {
6669             if (complain & tf_error)
6670               error ("the address of %qD is not a valid template argument "
6671                      "because it does not have static storage duration",
6672                      decl);
6673             return true;
6674           }
6675       }
6676       break;
6677
6678     default:
6679       if (!INDIRECT_TYPE_P (type))
6680         /* We're only concerned about pointers and references here.  */;
6681       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6682         /* Null pointer values are OK in C++11.  */;
6683       else
6684         {
6685           if (VAR_P (expr))
6686             {
6687               if (complain & tf_error)
6688                 error ("%qD is not a valid template argument "
6689                        "because %qD is a variable, not the address of "
6690                        "a variable", expr, expr);
6691               return true;
6692             }
6693           else
6694             {
6695               if (complain & tf_error)
6696                 error ("%qE is not a valid template argument for %qT "
6697                        "because it is not the address of a variable",
6698                        expr, type);
6699               return true;
6700             }
6701         }
6702     }
6703   return false;
6704
6705 }
6706
6707 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
6708    template argument EXPR.  */
6709
6710 static tree
6711 get_template_parm_object (tree expr, tsubst_flags_t complain)
6712 {
6713   if (TREE_CODE (expr) == TARGET_EXPR)
6714     expr = TARGET_EXPR_INITIAL (expr);
6715
6716   if (!TREE_CONSTANT (expr))
6717     {
6718       if ((complain & tf_error)
6719           && require_rvalue_constant_expression (expr))
6720         cxx_constant_value (expr);
6721       return error_mark_node;
6722     }
6723   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
6724     return error_mark_node;
6725
6726   tree name = mangle_template_parm_object (expr);
6727   tree decl = get_global_binding (name);
6728   if (decl)
6729     return decl;
6730
6731   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
6732   decl = create_temporary_var (type);
6733   TREE_STATIC (decl) = true;
6734   DECL_DECLARED_CONSTEXPR_P (decl) = true;
6735   TREE_READONLY (decl) = true;
6736   DECL_NAME (decl) = name;
6737   SET_DECL_ASSEMBLER_NAME (decl, name);
6738   DECL_CONTEXT (decl) = global_namespace;
6739   comdat_linkage (decl);
6740   pushdecl_top_level_and_finish (decl, expr);
6741   return decl;
6742 }
6743
6744 /* Attempt to convert the non-type template parameter EXPR to the
6745    indicated TYPE.  If the conversion is successful, return the
6746    converted value.  If the conversion is unsuccessful, return
6747    NULL_TREE if we issued an error message, or error_mark_node if we
6748    did not.  We issue error messages for out-and-out bad template
6749    parameters, but not simply because the conversion failed, since we
6750    might be just trying to do argument deduction.  Both TYPE and EXPR
6751    must be non-dependent.
6752
6753    The conversion follows the special rules described in
6754    [temp.arg.nontype], and it is much more strict than an implicit
6755    conversion.
6756
6757    This function is called twice for each template argument (see
6758    lookup_template_class for a more accurate description of this
6759    problem). This means that we need to handle expressions which
6760    are not valid in a C++ source, but can be created from the
6761    first call (for instance, casts to perform conversions). These
6762    hacks can go away after we fix the double coercion problem.  */
6763
6764 static tree
6765 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6766 {
6767   tree expr_type;
6768   location_t loc = cp_expr_loc_or_input_loc (expr);
6769
6770   /* Detect immediately string literals as invalid non-type argument.
6771      This special-case is not needed for correctness (we would easily
6772      catch this later), but only to provide better diagnostic for this
6773      common user mistake. As suggested by DR 100, we do not mention
6774      linkage issues in the diagnostic as this is not the point.  */
6775   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
6776     {
6777       if (complain & tf_error)
6778         error ("%qE is not a valid template argument for type %qT "
6779                "because string literals can never be used in this context",
6780                expr, type);
6781       return NULL_TREE;
6782     }
6783
6784   /* Add the ADDR_EXPR now for the benefit of
6785      value_dependent_expression_p.  */
6786   if (TYPE_PTROBV_P (type)
6787       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6788     {
6789       expr = decay_conversion (expr, complain);
6790       if (expr == error_mark_node)
6791         return error_mark_node;
6792     }
6793
6794   /* If we are in a template, EXPR may be non-dependent, but still
6795      have a syntactic, rather than semantic, form.  For example, EXPR
6796      might be a SCOPE_REF, rather than the VAR_DECL to which the
6797      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6798      so that access checking can be performed when the template is
6799      instantiated -- but here we need the resolved form so that we can
6800      convert the argument.  */
6801   bool non_dep = false;
6802   if (TYPE_REF_OBJ_P (type)
6803       && has_value_dependent_address (expr))
6804     /* If we want the address and it's value-dependent, don't fold.  */;
6805   else if (processing_template_decl
6806            && is_nondependent_constant_expression (expr))
6807     non_dep = true;
6808   if (error_operand_p (expr))
6809     return error_mark_node;
6810   expr_type = TREE_TYPE (expr);
6811
6812   /* If the argument is non-dependent, perform any conversions in
6813      non-dependent context as well.  */
6814   processing_template_decl_sentinel s (non_dep);
6815   if (non_dep)
6816     expr = instantiate_non_dependent_expr_internal (expr, complain);
6817
6818   if (value_dependent_expression_p (expr))
6819     expr = canonicalize_expr_argument (expr, complain);
6820
6821   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6822      to a non-type argument of "nullptr".  */
6823   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6824     expr = fold_simple (convert (type, expr));
6825
6826   /* In C++11, integral or enumeration non-type template arguments can be
6827      arbitrary constant expressions.  Pointer and pointer to
6828      member arguments can be general constant expressions that evaluate
6829      to a null value, but otherwise still need to be of a specific form.  */
6830   if (cxx_dialect >= cxx11)
6831     {
6832       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
6833         /* A PTRMEM_CST is already constant, and a valid template
6834            argument for a parameter of pointer to member type, we just want
6835            to leave it in that form rather than lower it to a
6836            CONSTRUCTOR.  */;
6837       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6838                || cxx_dialect >= cxx17)
6839         {
6840           /* Calling build_converted_constant_expr might create a call to
6841              a conversion function with a value-dependent argument, which
6842              could invoke taking the address of a temporary representing
6843              the result of the conversion.  */
6844           if (COMPOUND_LITERAL_P (expr)
6845               && CONSTRUCTOR_IS_DEPENDENT (expr)
6846               && MAYBE_CLASS_TYPE_P (expr_type)
6847               && TYPE_HAS_CONVERSION (expr_type))
6848             {
6849               expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
6850               IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
6851               return expr;
6852             }
6853           /* C++17: A template-argument for a non-type template-parameter shall
6854              be a converted constant expression (8.20) of the type of the
6855              template-parameter.  */
6856           expr = build_converted_constant_expr (type, expr, complain);
6857           if (expr == error_mark_node)
6858             /* Make sure we return NULL_TREE only if we have really issued
6859                an error, as described above.  */
6860             return (complain & tf_error) ? NULL_TREE : error_mark_node;
6861           expr = maybe_constant_value (expr, NULL_TREE,
6862                                        /*manifestly_const_eval=*/true);
6863           expr = convert_from_reference (expr);
6864         }
6865       else if (TYPE_PTR_OR_PTRMEM_P (type))
6866         {
6867           tree folded = maybe_constant_value (expr, NULL_TREE,
6868                                               /*manifestly_const_eval=*/true);
6869           if (TYPE_PTR_P (type) ? integer_zerop (folded)
6870               : null_member_pointer_value_p (folded))
6871             expr = folded;
6872         }
6873     }
6874
6875   if (TYPE_REF_P (type))
6876     expr = mark_lvalue_use (expr);
6877   else
6878     expr = mark_rvalue_use (expr);
6879
6880   /* HACK: Due to double coercion, we can get a
6881      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6882      which is the tree that we built on the first call (see
6883      below when coercing to reference to object or to reference to
6884      function). We just strip everything and get to the arg.
6885      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6886      for examples.  */
6887   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6888     {
6889       tree probe_type, probe = expr;
6890       if (REFERENCE_REF_P (probe))
6891         probe = TREE_OPERAND (probe, 0);
6892       probe_type = TREE_TYPE (probe);
6893       if (TREE_CODE (probe) == NOP_EXPR)
6894         {
6895           /* ??? Maybe we could use convert_from_reference here, but we
6896              would need to relax its constraints because the NOP_EXPR
6897              could actually change the type to something more cv-qualified,
6898              and this is not folded by convert_from_reference.  */
6899           tree addr = TREE_OPERAND (probe, 0);
6900           if (TYPE_REF_P (probe_type)
6901               && TREE_CODE (addr) == ADDR_EXPR
6902               && TYPE_PTR_P (TREE_TYPE (addr))
6903               && (same_type_ignoring_top_level_qualifiers_p
6904                   (TREE_TYPE (probe_type),
6905                    TREE_TYPE (TREE_TYPE (addr)))))
6906             {
6907               expr = TREE_OPERAND (addr, 0);
6908               expr_type = TREE_TYPE (probe_type);
6909             }
6910         }
6911     }
6912
6913   /* [temp.arg.nontype]/5, bullet 1
6914
6915      For a non-type template-parameter of integral or enumeration type,
6916      integral promotions (_conv.prom_) and integral conversions
6917      (_conv.integral_) are applied.  */
6918   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6919     {
6920       if (cxx_dialect < cxx11)
6921         {
6922           tree t = build_converted_constant_expr (type, expr, complain);
6923           t = maybe_constant_value (t);
6924           if (t != error_mark_node)
6925             expr = t;
6926         }
6927
6928       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6929         return error_mark_node;
6930
6931       /* Notice that there are constant expressions like '4 % 0' which
6932          do not fold into integer constants.  */
6933       if (TREE_CODE (expr) != INTEGER_CST
6934           && !value_dependent_expression_p (expr))
6935         {
6936           if (complain & tf_error)
6937             {
6938               int errs = errorcount, warns = warningcount + werrorcount;
6939               if (!require_potential_constant_expression (expr))
6940                 expr = error_mark_node;
6941               else
6942                 expr = cxx_constant_value (expr);
6943               if (errorcount > errs || warningcount + werrorcount > warns)
6944                 inform (loc, "in template argument for type %qT", type);
6945               if (expr == error_mark_node)
6946                 return NULL_TREE;
6947               /* else cxx_constant_value complained but gave us
6948                  a real constant, so go ahead.  */
6949               if (TREE_CODE (expr) != INTEGER_CST)
6950                 {
6951                   /* Some assemble time constant expressions like
6952                      (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6953                      4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6954                      as we can emit them into .rodata initializers of
6955                      variables, yet they can't fold into an INTEGER_CST at
6956                      compile time.  Refuse them here.  */
6957                   gcc_checking_assert (reduced_constant_expression_p (expr));
6958                   error_at (loc, "template argument %qE for type %qT not "
6959                                  "a constant integer", expr, type);
6960                   return NULL_TREE;
6961                 }
6962             }
6963           else
6964             return NULL_TREE;
6965         }
6966
6967       /* Avoid typedef problems.  */
6968       if (TREE_TYPE (expr) != type)
6969         expr = fold_convert (type, expr);
6970     }
6971   /* [temp.arg.nontype]/5, bullet 2
6972
6973      For a non-type template-parameter of type pointer to object,
6974      qualification conversions (_conv.qual_) and the array-to-pointer
6975      conversion (_conv.array_) are applied.  */
6976   else if (TYPE_PTROBV_P (type))
6977     {
6978       tree decayed = expr;
6979
6980       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6981          decay_conversion or an explicit cast.  If it's a problematic cast,
6982          we'll complain about it below.  */
6983       if (TREE_CODE (expr) == NOP_EXPR)
6984         {
6985           tree probe = expr;
6986           STRIP_NOPS (probe);
6987           if (TREE_CODE (probe) == ADDR_EXPR
6988               && TYPE_PTR_P (TREE_TYPE (probe)))
6989             {
6990               expr = probe;
6991               expr_type = TREE_TYPE (expr);
6992             }
6993         }
6994
6995       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6996
6997          A template-argument for a non-type, non-template template-parameter
6998          shall be one of: [...]
6999
7000          -- the name of a non-type template-parameter;
7001          -- the address of an object or function with external linkage, [...]
7002             expressed as "& id-expression" where the & is optional if the name
7003             refers to a function or array, or if the corresponding
7004             template-parameter is a reference.
7005
7006         Here, we do not care about functions, as they are invalid anyway
7007         for a parameter of type pointer-to-object.  */
7008
7009       if (value_dependent_expression_p (expr))
7010         /* Non-type template parameters are OK.  */
7011         ;
7012       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7013         /* Null pointer values are OK in C++11.  */;
7014       else if (TREE_CODE (expr) != ADDR_EXPR
7015                && !INDIRECT_TYPE_P (expr_type))
7016         /* Other values, like integer constants, might be valid
7017            non-type arguments of some other type.  */
7018         return error_mark_node;
7019       else if (invalid_tparm_referent_p (type, expr, complain))
7020         return NULL_TREE;
7021
7022       expr = decayed;
7023
7024       expr = perform_qualification_conversions (type, expr);
7025       if (expr == error_mark_node)
7026         return error_mark_node;
7027     }
7028   /* [temp.arg.nontype]/5, bullet 3
7029
7030      For a non-type template-parameter of type reference to object, no
7031      conversions apply. The type referred to by the reference may be more
7032      cv-qualified than the (otherwise identical) type of the
7033      template-argument. The template-parameter is bound directly to the
7034      template-argument, which must be an lvalue.  */
7035   else if (TYPE_REF_OBJ_P (type))
7036     {
7037       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7038                                                       expr_type))
7039         return error_mark_node;
7040
7041       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7042         {
7043           if (complain & tf_error)
7044             error ("%qE is not a valid template argument for type %qT "
7045                    "because of conflicts in cv-qualification", expr, type);
7046           return NULL_TREE;
7047         }
7048
7049       if (!lvalue_p (expr))
7050         {
7051           if (complain & tf_error)
7052             error ("%qE is not a valid template argument for type %qT "
7053                    "because it is not an lvalue", expr, type);
7054           return NULL_TREE;
7055         }
7056
7057       /* [temp.arg.nontype]/1
7058
7059          A template-argument for a non-type, non-template template-parameter
7060          shall be one of: [...]
7061
7062          -- the address of an object or function with external linkage.  */
7063       if (INDIRECT_REF_P (expr)
7064           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7065         {
7066           expr = TREE_OPERAND (expr, 0);
7067           if (DECL_P (expr))
7068             {
7069               if (complain & tf_error)
7070                 error ("%q#D is not a valid template argument for type %qT "
7071                        "because a reference variable does not have a constant "
7072                        "address", expr, type);
7073               return NULL_TREE;
7074             }
7075         }
7076
7077       if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
7078           && value_dependent_expression_p (expr))
7079         /* OK, dependent reference.  We don't want to ask whether a DECL is
7080            itself value-dependent, since what we want here is its address.  */;
7081       else
7082         {
7083           expr = build_address (expr);
7084
7085           if (invalid_tparm_referent_p (type, expr, complain))
7086             return NULL_TREE;
7087         }
7088
7089       if (!same_type_p (type, TREE_TYPE (expr)))
7090         expr = build_nop (type, expr);
7091     }
7092   /* [temp.arg.nontype]/5, bullet 4
7093
7094      For a non-type template-parameter of type pointer to function, only
7095      the function-to-pointer conversion (_conv.func_) is applied. If the
7096      template-argument represents a set of overloaded functions (or a
7097      pointer to such), the matching function is selected from the set
7098      (_over.over_).  */
7099   else if (TYPE_PTRFN_P (type))
7100     {
7101       /* If the argument is a template-id, we might not have enough
7102          context information to decay the pointer.  */
7103       if (!type_unknown_p (expr_type))
7104         {
7105           expr = decay_conversion (expr, complain);
7106           if (expr == error_mark_node)
7107             return error_mark_node;
7108         }
7109
7110       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7111         /* Null pointer values are OK in C++11.  */
7112         return perform_qualification_conversions (type, expr);
7113
7114       expr = convert_nontype_argument_function (type, expr, complain);
7115       if (!expr || expr == error_mark_node)
7116         return expr;
7117     }
7118   /* [temp.arg.nontype]/5, bullet 5
7119
7120      For a non-type template-parameter of type reference to function, no
7121      conversions apply. If the template-argument represents a set of
7122      overloaded functions, the matching function is selected from the set
7123      (_over.over_).  */
7124   else if (TYPE_REFFN_P (type))
7125     {
7126       if (TREE_CODE (expr) == ADDR_EXPR)
7127         {
7128           if (complain & tf_error)
7129             {
7130               error ("%qE is not a valid template argument for type %qT "
7131                      "because it is a pointer", expr, type);
7132               inform (input_location, "try using %qE instead",
7133                       TREE_OPERAND (expr, 0));
7134             }
7135           return NULL_TREE;
7136         }
7137
7138       expr = convert_nontype_argument_function (type, expr, complain);
7139       if (!expr || expr == error_mark_node)
7140         return expr;
7141     }
7142   /* [temp.arg.nontype]/5, bullet 6
7143
7144      For a non-type template-parameter of type pointer to member function,
7145      no conversions apply. If the template-argument represents a set of
7146      overloaded member functions, the matching member function is selected
7147      from the set (_over.over_).  */
7148   else if (TYPE_PTRMEMFUNC_P (type))
7149     {
7150       expr = instantiate_type (type, expr, tf_none);
7151       if (expr == error_mark_node)
7152         return error_mark_node;
7153
7154       /* [temp.arg.nontype] bullet 1 says the pointer to member
7155          expression must be a pointer-to-member constant.  */
7156       if (!value_dependent_expression_p (expr)
7157           && !check_valid_ptrmem_cst_expr (type, expr, complain))
7158         return NULL_TREE;
7159
7160       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7161          into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7162       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7163         expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7164     }
7165   /* [temp.arg.nontype]/5, bullet 7
7166
7167      For a non-type template-parameter of type pointer to data member,
7168      qualification conversions (_conv.qual_) are applied.  */
7169   else if (TYPE_PTRDATAMEM_P (type))
7170     {
7171       /* [temp.arg.nontype] bullet 1 says the pointer to member
7172          expression must be a pointer-to-member constant.  */
7173       if (!value_dependent_expression_p (expr)
7174           && !check_valid_ptrmem_cst_expr (type, expr, complain))
7175         return NULL_TREE;
7176
7177       expr = perform_qualification_conversions (type, expr);
7178       if (expr == error_mark_node)
7179         return expr;
7180     }
7181   else if (NULLPTR_TYPE_P (type))
7182     {
7183       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7184         {
7185           if (complain & tf_error)
7186             error ("%qE is not a valid template argument for type %qT "
7187                    "because it is of type %qT", expr, type, TREE_TYPE (expr));
7188           return NULL_TREE;
7189         }
7190       return expr;
7191     }
7192   else if (CLASS_TYPE_P (type))
7193     {
7194       /* Replace the argument with a reference to the corresponding template
7195          parameter object.  */
7196       if (!value_dependent_expression_p (expr))
7197         expr = get_template_parm_object (expr, complain);
7198       if (expr == error_mark_node)
7199         return NULL_TREE;
7200     }
7201   /* A template non-type parameter must be one of the above.  */
7202   else
7203     gcc_unreachable ();
7204
7205   /* Sanity check: did we actually convert the argument to the
7206      right type?  */
7207   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7208               (type, TREE_TYPE (expr)));
7209   return convert_from_reference (expr);
7210 }
7211
7212 /* Subroutine of coerce_template_template_parms, which returns 1 if
7213    PARM_PARM and ARG_PARM match using the rule for the template
7214    parameters of template template parameters. Both PARM and ARG are
7215    template parameters; the rest of the arguments are the same as for
7216    coerce_template_template_parms.
7217  */
7218 static int
7219 coerce_template_template_parm (tree parm,
7220                               tree arg,
7221                               tsubst_flags_t complain,
7222                               tree in_decl,
7223                               tree outer_args)
7224 {
7225   if (arg == NULL_TREE || error_operand_p (arg)
7226       || parm == NULL_TREE || error_operand_p (parm))
7227     return 0;
7228
7229   if (TREE_CODE (arg) != TREE_CODE (parm))
7230     return 0;
7231
7232   switch (TREE_CODE (parm))
7233     {
7234     case TEMPLATE_DECL:
7235       /* We encounter instantiations of templates like
7236          template <template <template <class> class> class TT>
7237          class C;  */
7238       {
7239         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7240         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7241
7242         if (!coerce_template_template_parms
7243             (parmparm, argparm, complain, in_decl, outer_args))
7244           return 0;
7245       }
7246       /* Fall through.  */
7247
7248     case TYPE_DECL:
7249       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7250           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7251         /* Argument is a parameter pack but parameter is not.  */
7252         return 0;
7253       break;
7254
7255     case PARM_DECL:
7256       /* The tsubst call is used to handle cases such as
7257
7258            template <int> class C {};
7259            template <class T, template <T> class TT> class D {};
7260            D<int, C> d;
7261
7262          i.e. the parameter list of TT depends on earlier parameters.  */
7263       if (!uses_template_parms (TREE_TYPE (arg)))
7264         {
7265           tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7266           if (!uses_template_parms (t)
7267               && !same_type_p (t, TREE_TYPE (arg)))
7268             return 0;
7269         }
7270
7271       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7272           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7273         /* Argument is a parameter pack but parameter is not.  */
7274         return 0;
7275
7276       break;
7277
7278     default:
7279       gcc_unreachable ();
7280     }
7281
7282   return 1;
7283 }
7284
7285 /* Coerce template argument list ARGLIST for use with template
7286    template-parameter TEMPL.  */
7287
7288 static tree
7289 coerce_template_args_for_ttp (tree templ, tree arglist,
7290                               tsubst_flags_t complain)
7291 {
7292   /* Consider an example where a template template parameter declared as
7293
7294      template <class T, class U = std::allocator<T> > class TT
7295
7296      The template parameter level of T and U are one level larger than
7297      of TT.  To proper process the default argument of U, say when an
7298      instantiation `TT<int>' is seen, we need to build the full
7299      arguments containing {int} as the innermost level.  Outer levels,
7300      available when not appearing as default template argument, can be
7301      obtained from the arguments of the enclosing template.
7302
7303      Suppose that TT is later substituted with std::vector.  The above
7304      instantiation is `TT<int, std::allocator<T> >' with TT at
7305      level 1, and T at level 2, while the template arguments at level 1
7306      becomes {std::vector} and the inner level 2 is {int}.  */
7307
7308   tree outer = DECL_CONTEXT (templ);
7309   if (outer)
7310     {
7311       if (DECL_TEMPLATE_SPECIALIZATION (outer))
7312         /* We want arguments for the partial specialization, not arguments for
7313            the primary template.  */
7314         outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7315       else
7316         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7317     }
7318   else if (current_template_parms)
7319     {
7320       /* This is an argument of the current template, so we haven't set
7321          DECL_CONTEXT yet.  */
7322       tree relevant_template_parms;
7323
7324       /* Parameter levels that are greater than the level of the given
7325          template template parm are irrelevant.  */
7326       relevant_template_parms = current_template_parms;
7327       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7328              != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7329         relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7330
7331       outer = template_parms_to_args (relevant_template_parms);
7332     }
7333
7334   if (outer)
7335     arglist = add_to_template_args (outer, arglist);
7336
7337   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7338   return coerce_template_parms (parmlist, arglist, templ,
7339                                 complain,
7340                                 /*require_all_args=*/true,
7341                                 /*use_default_args=*/true);
7342 }
7343
7344 /* A cache of template template parameters with match-all default
7345    arguments.  */
7346 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7347 static void
7348 store_defaulted_ttp (tree v, tree t)
7349 {
7350   if (!defaulted_ttp_cache)
7351     defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7352   defaulted_ttp_cache->put (v, t);
7353 }
7354 static tree
7355 lookup_defaulted_ttp (tree v)
7356 {
7357   if (defaulted_ttp_cache)
7358     if (tree *p = defaulted_ttp_cache->get (v))
7359       return *p;
7360   return NULL_TREE;
7361 }
7362
7363 /* T is a bound template template-parameter.  Copy its arguments into default
7364    arguments of the template template-parameter's template parameters.  */
7365
7366 static tree
7367 add_defaults_to_ttp (tree otmpl)
7368 {
7369   if (tree c = lookup_defaulted_ttp (otmpl))
7370     return c;
7371
7372   tree ntmpl = copy_node (otmpl);
7373
7374   tree ntype = copy_node (TREE_TYPE (otmpl));
7375   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7376   TYPE_MAIN_VARIANT (ntype) = ntype;
7377   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7378   TYPE_NAME (ntype) = ntmpl;
7379   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7380
7381   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7382     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7383   TEMPLATE_PARM_DECL (idx) = ntmpl;
7384   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7385
7386   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7387   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7388   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7389   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7390   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7391     {
7392       tree o = TREE_VEC_ELT (vec, i);
7393       if (!template_parameter_pack_p (TREE_VALUE (o)))
7394         {
7395           tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7396           TREE_PURPOSE (n) = any_targ_node;
7397         }
7398     }
7399
7400   store_defaulted_ttp (otmpl, ntmpl);
7401   return ntmpl;
7402 }
7403
7404 /* ARG is a bound potential template template-argument, and PARGS is a list
7405    of arguments for the corresponding template template-parameter.  Adjust
7406    PARGS as appropriate for application to ARG's template, and if ARG is a
7407    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7408    arguments to the template template parameter.  */
7409
7410 static tree
7411 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7412 {
7413   ++processing_template_decl;
7414   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7415   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7416     {
7417       /* When comparing two template template-parameters in partial ordering,
7418          rewrite the one currently being used as an argument to have default
7419          arguments for all parameters.  */
7420       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7421       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7422       if (pargs != error_mark_node)
7423         arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7424                                            TYPE_TI_ARGS (arg));
7425     }
7426   else
7427     {
7428       tree aparms
7429         = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7430       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7431                                        /*require_all*/true,
7432                                        /*use_default*/true);
7433     }
7434   --processing_template_decl;
7435   return pargs;
7436 }
7437
7438 /* Subroutine of unify for the case when PARM is a
7439    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7440
7441 static int
7442 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7443                       bool explain_p)
7444 {
7445   tree parmvec = TYPE_TI_ARGS (parm);
7446   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7447
7448   /* The template template parm might be variadic and the argument
7449      not, so flatten both argument lists.  */
7450   parmvec = expand_template_argument_pack (parmvec);
7451   argvec = expand_template_argument_pack (argvec);
7452
7453   if (flag_new_ttp)
7454     {
7455       /* In keeping with P0522R0, adjust P's template arguments
7456          to apply to A's template; then flatten it again.  */
7457       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7458       nparmvec = expand_template_argument_pack (nparmvec);
7459
7460       if (unify (tparms, targs, nparmvec, argvec,
7461                  UNIFY_ALLOW_NONE, explain_p))
7462         return 1;
7463
7464       /* If the P0522 adjustment eliminated a pack expansion, deduce
7465          empty packs.  */
7466       if (flag_new_ttp
7467           && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7468           && unify_pack_expansion (tparms, targs, parmvec, argvec,
7469                                    DEDUCE_EXACT, /*sub*/true, explain_p))
7470         return 1;
7471     }
7472   else
7473     {
7474       /* Deduce arguments T, i from TT<T> or TT<i>.
7475          We check each element of PARMVEC and ARGVEC individually
7476          rather than the whole TREE_VEC since they can have
7477          different number of elements, which is allowed under N2555.  */
7478
7479       int len = TREE_VEC_LENGTH (parmvec);
7480
7481       /* Check if the parameters end in a pack, making them
7482          variadic.  */
7483       int parm_variadic_p = 0;
7484       if (len > 0
7485           && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7486         parm_variadic_p = 1;
7487
7488       for (int i = 0; i < len - parm_variadic_p; ++i)
7489         /* If the template argument list of P contains a pack
7490            expansion that is not the last template argument, the
7491            entire template argument list is a non-deduced
7492            context.  */
7493         if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7494           return unify_success (explain_p);
7495
7496       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7497         return unify_too_few_arguments (explain_p,
7498                                         TREE_VEC_LENGTH (argvec), len);
7499
7500       for (int i = 0; i < len - parm_variadic_p; ++i)
7501         if (unify (tparms, targs,
7502                    TREE_VEC_ELT (parmvec, i),
7503                    TREE_VEC_ELT (argvec, i),
7504                    UNIFY_ALLOW_NONE, explain_p))
7505           return 1;
7506
7507       if (parm_variadic_p
7508           && unify_pack_expansion (tparms, targs,
7509                                    parmvec, argvec,
7510                                    DEDUCE_EXACT,
7511                                    /*subr=*/true, explain_p))
7512         return 1;
7513     }
7514
7515   return 0;
7516 }
7517
7518 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7519    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7520    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7521    or PARM_DECL.
7522
7523    Consider the example:
7524      template <class T> class A;
7525      template<template <class U> class TT> class B;
7526
7527    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7528    the parameters to A, and OUTER_ARGS contains A.  */
7529
7530 static int
7531 coerce_template_template_parms (tree parm_parms,
7532                                 tree arg_parms,
7533                                 tsubst_flags_t complain,
7534                                 tree in_decl,
7535                                 tree outer_args)
7536 {
7537   int nparms, nargs, i;
7538   tree parm, arg;
7539   int variadic_p = 0;
7540
7541   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7542   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7543
7544   nparms = TREE_VEC_LENGTH (parm_parms);
7545   nargs = TREE_VEC_LENGTH (arg_parms);
7546
7547   if (flag_new_ttp)
7548     {
7549       /* P0522R0: A template template-parameter P is at least as specialized as
7550          a template template-argument A if, given the following rewrite to two
7551          function templates, the function template corresponding to P is at
7552          least as specialized as the function template corresponding to A
7553          according to the partial ordering rules for function templates
7554          ([temp.func.order]). Given an invented class template X with the
7555          template parameter list of A (including default arguments):
7556
7557          * Each of the two function templates has the same template parameters,
7558          respectively, as P or A.
7559
7560          * Each function template has a single function parameter whose type is
7561          a specialization of X with template arguments corresponding to the
7562          template parameters from the respective function template where, for
7563          each template parameter PP in the template parameter list of the
7564          function template, a corresponding template argument AA is formed. If
7565          PP declares a parameter pack, then AA is the pack expansion
7566          PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7567
7568          If the rewrite produces an invalid type, then P is not at least as
7569          specialized as A.  */
7570
7571       /* So coerce P's args to apply to A's parms, and then deduce between A's
7572          args and the converted args.  If that succeeds, A is at least as
7573          specialized as P, so they match.*/
7574       tree pargs = template_parms_level_to_args (parm_parms);
7575       pargs = add_outermost_template_args (outer_args, pargs);
7576       ++processing_template_decl;
7577       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7578                                      /*require_all*/true, /*use_default*/true);
7579       --processing_template_decl;
7580       if (pargs != error_mark_node)
7581         {
7582           tree targs = make_tree_vec (nargs);
7583           tree aargs = template_parms_level_to_args (arg_parms);
7584           if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7585                       /*explain*/false))
7586             return 1;
7587         }
7588     }
7589
7590   /* Determine whether we have a parameter pack at the end of the
7591      template template parameter's template parameter list.  */
7592   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7593     {
7594       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7595
7596       if (error_operand_p (parm))
7597         return 0;
7598
7599       switch (TREE_CODE (parm))
7600         {
7601         case TEMPLATE_DECL:
7602         case TYPE_DECL:
7603           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7604             variadic_p = 1;
7605           break;
7606
7607         case PARM_DECL:
7608           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7609             variadic_p = 1;
7610           break;
7611
7612         default:
7613           gcc_unreachable ();
7614         }
7615     }
7616
7617   if (nargs != nparms
7618       && !(variadic_p && nargs >= nparms - 1))
7619     return 0;
7620
7621   /* Check all of the template parameters except the parameter pack at
7622      the end (if any).  */
7623   for (i = 0; i < nparms - variadic_p; ++i)
7624     {
7625       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7626           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7627         continue;
7628
7629       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7630       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7631
7632       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7633                                           outer_args))
7634         return 0;
7635
7636     }
7637
7638   if (variadic_p)
7639     {
7640       /* Check each of the template parameters in the template
7641          argument against the template parameter pack at the end of
7642          the template template parameter.  */
7643       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7644         return 0;
7645
7646       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7647
7648       for (; i < nargs; ++i)
7649         {
7650           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7651             continue;
7652
7653           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7654
7655           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7656                                               outer_args))
7657             return 0;
7658         }
7659     }
7660
7661   return 1;
7662 }
7663
7664 /* Verifies that the deduced template arguments (in TARGS) for the
7665    template template parameters (in TPARMS) represent valid bindings,
7666    by comparing the template parameter list of each template argument
7667    to the template parameter list of its corresponding template
7668    template parameter, in accordance with DR150. This
7669    routine can only be called after all template arguments have been
7670    deduced. It will return TRUE if all of the template template
7671    parameter bindings are okay, FALSE otherwise.  */
7672 bool
7673 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7674 {
7675   int i, ntparms = TREE_VEC_LENGTH (tparms);
7676   bool ret = true;
7677
7678   /* We're dealing with template parms in this process.  */
7679   ++processing_template_decl;
7680
7681   targs = INNERMOST_TEMPLATE_ARGS (targs);
7682
7683   for (i = 0; i < ntparms; ++i)
7684     {
7685       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7686       tree targ = TREE_VEC_ELT (targs, i);
7687
7688       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7689         {
7690           tree packed_args = NULL_TREE;
7691           int idx, len = 1;
7692
7693           if (ARGUMENT_PACK_P (targ))
7694             {
7695               /* Look inside the argument pack.  */
7696               packed_args = ARGUMENT_PACK_ARGS (targ);
7697               len = TREE_VEC_LENGTH (packed_args);
7698             }
7699
7700           for (idx = 0; idx < len; ++idx)
7701             {
7702               tree targ_parms = NULL_TREE;
7703
7704               if (packed_args)
7705                 /* Extract the next argument from the argument
7706                    pack.  */
7707                 targ = TREE_VEC_ELT (packed_args, idx);
7708
7709               if (PACK_EXPANSION_P (targ))
7710                 /* Look at the pattern of the pack expansion.  */
7711                 targ = PACK_EXPANSION_PATTERN (targ);
7712
7713               /* Extract the template parameters from the template
7714                  argument.  */
7715               if (TREE_CODE (targ) == TEMPLATE_DECL)
7716                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7717               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7718                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7719
7720               /* Verify that we can coerce the template template
7721                  parameters from the template argument to the template
7722                  parameter.  This requires an exact match.  */
7723               if (targ_parms
7724                   && !coerce_template_template_parms
7725                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7726                         targ_parms,
7727                         tf_none,
7728                         tparm,
7729                         targs))
7730                 {
7731                   ret = false;
7732                   goto out;
7733                 }
7734             }
7735         }
7736     }
7737
7738  out:
7739
7740   --processing_template_decl;
7741   return ret;
7742 }
7743
7744 /* Since type attributes aren't mangled, we need to strip them from
7745    template type arguments.  */
7746
7747 static tree
7748 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7749 {
7750   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7751     return arg;
7752   bool removed_attributes = false;
7753   tree canon = strip_typedefs (arg, &removed_attributes);
7754   if (removed_attributes
7755       && (complain & tf_warning))
7756     warning (OPT_Wignored_attributes,
7757              "ignoring attributes on template argument %qT", arg);
7758   return canon;
7759 }
7760
7761 /* And from inside dependent non-type arguments like sizeof(Type).  */
7762
7763 static tree
7764 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7765 {
7766   if (!arg || arg == error_mark_node)
7767     return arg;
7768   bool removed_attributes = false;
7769   tree canon = strip_typedefs_expr (arg, &removed_attributes);
7770   if (removed_attributes
7771       && (complain & tf_warning))
7772     warning (OPT_Wignored_attributes,
7773              "ignoring attributes in template argument %qE", arg);
7774   return canon;
7775 }
7776
7777 // A template declaration can be substituted for a constrained
7778 // template template parameter only when the argument is more
7779 // constrained than the parameter.
7780 static bool
7781 is_compatible_template_arg (tree parm, tree arg)
7782 {
7783   tree parm_cons = get_constraints (parm);
7784
7785   /* For now, allow constrained template template arguments
7786      and unconstrained template template parameters.  */
7787   if (parm_cons == NULL_TREE)
7788     return true;
7789
7790   tree arg_cons = get_constraints (arg);
7791
7792   // If the template parameter is constrained, we need to rewrite its
7793   // constraints in terms of the ARG's template parameters. This ensures
7794   // that all of the template parameter types will have the same depth.
7795   //
7796   // Note that this is only valid when coerce_template_template_parm is
7797   // true for the innermost template parameters of PARM and ARG. In other
7798   // words, because coercion is successful, this conversion will be valid.
7799   if (parm_cons)
7800     {
7801       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7802       parm_cons = tsubst_constraint_info (parm_cons,
7803                                           INNERMOST_TEMPLATE_ARGS (args),
7804                                           tf_none, NULL_TREE);
7805       if (parm_cons == error_mark_node)
7806         return false;
7807     }
7808
7809   return subsumes (parm_cons, arg_cons);
7810 }
7811
7812 // Convert a placeholder argument into a binding to the original
7813 // parameter. The original parameter is saved as the TREE_TYPE of
7814 // ARG.
7815 static inline tree
7816 convert_wildcard_argument (tree parm, tree arg)
7817 {
7818   TREE_TYPE (arg) = parm;
7819   return arg;
7820 }
7821
7822 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7823    because one of them is dependent.  But we need to represent the
7824    conversion for the benefit of cp_tree_equal.  */
7825
7826 static tree
7827 maybe_convert_nontype_argument (tree type, tree arg)
7828 {
7829   /* Auto parms get no conversion.  */
7830   if (type_uses_auto (type))
7831     return arg;
7832   /* We don't need or want to add this conversion now if we're going to use the
7833      argument for deduction.  */
7834   if (value_dependent_expression_p (arg))
7835     return arg;
7836
7837   type = cv_unqualified (type);
7838   tree argtype = TREE_TYPE (arg);
7839   if (same_type_p (type, argtype))
7840     return arg;
7841
7842   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7843   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7844   return arg;
7845 }
7846
7847 /* Convert the indicated template ARG as necessary to match the
7848    indicated template PARM.  Returns the converted ARG, or
7849    error_mark_node if the conversion was unsuccessful.  Error and
7850    warning messages are issued under control of COMPLAIN.  This
7851    conversion is for the Ith parameter in the parameter list.  ARGS is
7852    the full set of template arguments deduced so far.  */
7853
7854 static tree
7855 convert_template_argument (tree parm,
7856                            tree arg,
7857                            tree args,
7858                            tsubst_flags_t complain,
7859                            int i,
7860                            tree in_decl)
7861 {
7862   tree orig_arg;
7863   tree val;
7864   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7865
7866   if (parm == error_mark_node || error_operand_p (arg))
7867     return error_mark_node;
7868
7869   /* Trivially convert placeholders. */
7870   if (TREE_CODE (arg) == WILDCARD_DECL)
7871     return convert_wildcard_argument (parm, arg);
7872
7873   if (arg == any_targ_node)
7874     return arg;
7875
7876   if (TREE_CODE (arg) == TREE_LIST
7877       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7878     {
7879       /* The template argument was the name of some
7880          member function.  That's usually
7881          invalid, but static members are OK.  In any
7882          case, grab the underlying fields/functions
7883          and issue an error later if required.  */
7884       TREE_TYPE (arg) = unknown_type_node;
7885     }
7886
7887   orig_arg = arg;
7888
7889   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7890   requires_type = (TREE_CODE (parm) == TYPE_DECL
7891                    || requires_tmpl_type);
7892
7893   /* When determining whether an argument pack expansion is a template,
7894      look at the pattern.  */
7895   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7896     arg = PACK_EXPANSION_PATTERN (arg);
7897
7898   /* Deal with an injected-class-name used as a template template arg.  */
7899   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7900     {
7901       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7902       if (TREE_CODE (t) == TEMPLATE_DECL)
7903         {
7904           if (cxx_dialect >= cxx11)
7905             /* OK under DR 1004.  */;
7906           else if (complain & tf_warning_or_error)
7907             pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7908                      " used as template template argument", TYPE_NAME (arg));
7909           else if (flag_pedantic_errors)
7910             t = arg;
7911
7912           arg = t;
7913         }
7914     }
7915
7916   is_tmpl_type =
7917     ((TREE_CODE (arg) == TEMPLATE_DECL
7918       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7919      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7920      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7921      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7922
7923   if (is_tmpl_type
7924       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7925           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7926     arg = TYPE_STUB_DECL (arg);
7927
7928   is_type = TYPE_P (arg) || is_tmpl_type;
7929
7930   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7931       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7932     {
7933       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7934         {
7935           if (complain & tf_error)
7936             error ("invalid use of destructor %qE as a type", orig_arg);
7937           return error_mark_node;
7938         }
7939
7940       permerror (input_location,
7941                  "to refer to a type member of a template parameter, "
7942                  "use %<typename %E%>", orig_arg);
7943
7944       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7945                                      TREE_OPERAND (arg, 1),
7946                                      typename_type,
7947                                      complain);
7948       arg = orig_arg;
7949       is_type = 1;
7950     }
7951   if (is_type != requires_type)
7952     {
7953       if (in_decl)
7954         {
7955           if (complain & tf_error)
7956             {
7957               error ("type/value mismatch at argument %d in template "
7958                      "parameter list for %qD",
7959                      i + 1, in_decl);
7960               if (is_type)
7961                 {
7962                   /* The template argument is a type, but we're expecting
7963                      an expression.  */
7964                   inform (input_location,
7965                           "  expected a constant of type %qT, got %qT",
7966                           TREE_TYPE (parm),
7967                           (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7968                   /* [temp.arg]/2: "In a template-argument, an ambiguity
7969                      between a type-id and an expression is resolved to a
7970                      type-id, regardless of the form of the corresponding
7971                      template-parameter."  So give the user a clue.  */
7972                   if (TREE_CODE (arg) == FUNCTION_TYPE)
7973                     inform (input_location, "  ambiguous template argument "
7974                             "for non-type template parameter is treated as "
7975                             "function type");
7976                 }
7977               else if (requires_tmpl_type)
7978                 inform (input_location,
7979                         "  expected a class template, got %qE", orig_arg);
7980               else
7981                 inform (input_location,
7982                         "  expected a type, got %qE", orig_arg);
7983             }
7984         }
7985       return error_mark_node;
7986     }
7987   if (is_tmpl_type ^ requires_tmpl_type)
7988     {
7989       if (in_decl && (complain & tf_error))
7990         {
7991           error ("type/value mismatch at argument %d in template "
7992                  "parameter list for %qD",
7993                  i + 1, in_decl);
7994           if (is_tmpl_type)
7995             inform (input_location,
7996                     "  expected a type, got %qT", DECL_NAME (arg));
7997           else
7998             inform (input_location,
7999                     "  expected a class template, got %qT", orig_arg);
8000         }
8001       return error_mark_node;
8002     }
8003
8004   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8005     /* We already did the appropriate conversion when packing args.  */
8006     val = orig_arg;
8007   else if (is_type)
8008     {
8009       if (requires_tmpl_type)
8010         {
8011           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8012             /* The number of argument required is not known yet.
8013                Just accept it for now.  */
8014             val = orig_arg;
8015           else
8016             {
8017               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8018               tree argparm;
8019
8020               /* Strip alias templates that are equivalent to another
8021                  template.  */
8022               arg = get_underlying_template (arg);
8023               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8024
8025               if (coerce_template_template_parms (parmparm, argparm,
8026                                                   complain, in_decl,
8027                                                   args))
8028                 {
8029                   val = arg;
8030
8031                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
8032                      TEMPLATE_DECL.  */
8033                   if (val != error_mark_node)
8034                     {
8035                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8036                         val = TREE_TYPE (val);
8037                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8038                         val = make_pack_expansion (val, complain);
8039                     }
8040                 }
8041               else
8042                 {
8043                   if (in_decl && (complain & tf_error))
8044                     {
8045                       error ("type/value mismatch at argument %d in "
8046                              "template parameter list for %qD",
8047                              i + 1, in_decl);
8048                       inform (input_location,
8049                               "  expected a template of type %qD, got %qT",
8050                               parm, orig_arg);
8051                     }
8052
8053                   val = error_mark_node;
8054                 }
8055
8056               // Check that the constraints are compatible before allowing the
8057               // substitution.
8058               if (val != error_mark_node)
8059                 if (!is_compatible_template_arg (parm, arg))
8060                   {
8061                     if (in_decl && (complain & tf_error))
8062                       {
8063                         error ("constraint mismatch at argument %d in "
8064                                "template parameter list for %qD",
8065                                i + 1, in_decl);
8066                         inform (input_location, "  expected %qD but got %qD",
8067                                 parm, arg);
8068                       }
8069                     val = error_mark_node;
8070                   }
8071             }
8072         }
8073       else
8074         val = orig_arg;
8075       /* We only form one instance of each template specialization.
8076          Therefore, if we use a non-canonical variant (i.e., a
8077          typedef), any future messages referring to the type will use
8078          the typedef, which is confusing if those future uses do not
8079          themselves also use the typedef.  */
8080       if (TYPE_P (val))
8081         val = canonicalize_type_argument (val, complain);
8082     }
8083   else
8084     {
8085       tree t = TREE_TYPE (parm);
8086
8087       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8088           > TMPL_ARGS_DEPTH (args))
8089         /* We don't have enough levels of args to do any substitution.  This
8090            can happen in the context of -fnew-ttp-matching.  */;
8091       else if (tree a = type_uses_auto (t))
8092         {
8093           t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8094           if (t == error_mark_node)
8095             return error_mark_node;
8096         }
8097       else
8098         t = tsubst (t, args, complain, in_decl);
8099
8100       if (invalid_nontype_parm_type_p (t, complain))
8101         return error_mark_node;
8102
8103       if (t != TREE_TYPE (parm))
8104         t = canonicalize_type_argument (t, complain);
8105
8106       if (!type_dependent_expression_p (orig_arg)
8107           && !uses_template_parms (t))
8108         /* We used to call digest_init here.  However, digest_init
8109            will report errors, which we don't want when complain
8110            is zero.  More importantly, digest_init will try too
8111            hard to convert things: for example, `0' should not be
8112            converted to pointer type at this point according to
8113            the standard.  Accepting this is not merely an
8114            extension, since deciding whether or not these
8115            conversions can occur is part of determining which
8116            function template to call, or whether a given explicit
8117            argument specification is valid.  */
8118         val = convert_nontype_argument (t, orig_arg, complain);
8119       else
8120         {
8121           val = canonicalize_expr_argument (orig_arg, complain);
8122           val = maybe_convert_nontype_argument (t, val);
8123         }
8124
8125
8126       if (val == NULL_TREE)
8127         val = error_mark_node;
8128       else if (val == error_mark_node && (complain & tf_error))
8129         error ("could not convert template argument %qE from %qT to %qT",
8130                orig_arg, TREE_TYPE (orig_arg), t);
8131
8132       if (INDIRECT_REF_P (val))
8133         {
8134           /* Reject template arguments that are references to built-in
8135              functions with no library fallbacks.  */
8136           const_tree inner = TREE_OPERAND (val, 0);
8137           const_tree innertype = TREE_TYPE (inner);
8138           if (innertype
8139               && TYPE_REF_P (innertype)
8140               && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8141               && TREE_OPERAND_LENGTH (inner) > 0
8142               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8143               return error_mark_node;
8144         }
8145
8146       if (TREE_CODE (val) == SCOPE_REF)
8147         {
8148           /* Strip typedefs from the SCOPE_REF.  */
8149           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8150           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8151                                                    complain);
8152           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8153                                       QUALIFIED_NAME_IS_TEMPLATE (val));
8154         }
8155     }
8156
8157   return val;
8158 }
8159
8160 /* Coerces the remaining template arguments in INNER_ARGS (from
8161    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8162    Returns the coerced argument pack. PARM_IDX is the position of this
8163    parameter in the template parameter list. ARGS is the original
8164    template argument list.  */
8165 static tree
8166 coerce_template_parameter_pack (tree parms,
8167                                 int parm_idx,
8168                                 tree args,
8169                                 tree inner_args,
8170                                 int arg_idx,
8171                                 tree new_args,
8172                                 int* lost,
8173                                 tree in_decl,
8174                                 tsubst_flags_t complain)
8175 {
8176   tree parm = TREE_VEC_ELT (parms, parm_idx);
8177   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8178   tree packed_args;
8179   tree argument_pack;
8180   tree packed_parms = NULL_TREE;
8181
8182   if (arg_idx > nargs)
8183     arg_idx = nargs;
8184
8185   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8186     {
8187       /* When the template parameter is a non-type template parameter pack
8188          or template template parameter pack whose type or template
8189          parameters use parameter packs, we know exactly how many arguments
8190          we are looking for.  Build a vector of the instantiated decls for
8191          these template parameters in PACKED_PARMS.  */
8192       /* We can't use make_pack_expansion here because it would interpret a
8193          _DECL as a use rather than a declaration.  */
8194       tree decl = TREE_VALUE (parm);
8195       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8196       SET_PACK_EXPANSION_PATTERN (exp, decl);
8197       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8198       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8199
8200       TREE_VEC_LENGTH (args)--;
8201       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8202       TREE_VEC_LENGTH (args)++;
8203
8204       if (packed_parms == error_mark_node)
8205         return error_mark_node;
8206
8207       /* If we're doing a partial instantiation of a member template,
8208          verify that all of the types used for the non-type
8209          template parameter pack are, in fact, valid for non-type
8210          template parameters.  */
8211       if (arg_idx < nargs
8212           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8213         {
8214           int j, len = TREE_VEC_LENGTH (packed_parms);
8215           for (j = 0; j < len; ++j)
8216             {
8217               tree t = TREE_VEC_ELT (packed_parms, j);
8218               if (TREE_CODE (t) == PARM_DECL
8219                   && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8220                 return error_mark_node;
8221             }
8222           /* We don't know how many args we have yet, just
8223              use the unconverted ones for now.  */
8224           return NULL_TREE;
8225         }
8226
8227       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8228     }
8229   /* Check if we have a placeholder pack, which indicates we're
8230      in the context of a introduction list.  In that case we want
8231      to match this pack to the single placeholder.  */
8232   else if (arg_idx < nargs
8233            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8234            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8235     {
8236       nargs = arg_idx + 1;
8237       packed_args = make_tree_vec (1);
8238     }
8239   else
8240     packed_args = make_tree_vec (nargs - arg_idx);
8241
8242   /* Convert the remaining arguments, which will be a part of the
8243      parameter pack "parm".  */
8244   int first_pack_arg = arg_idx;
8245   for (; arg_idx < nargs; ++arg_idx)
8246     {
8247       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8248       tree actual_parm = TREE_VALUE (parm);
8249       int pack_idx = arg_idx - first_pack_arg;
8250
8251       if (packed_parms)
8252         {
8253           /* Once we've packed as many args as we have types, stop.  */
8254           if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8255             break;
8256           else if (PACK_EXPANSION_P (arg))
8257             /* We don't know how many args we have yet, just
8258                use the unconverted ones for now.  */
8259             return NULL_TREE;
8260           else
8261             actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8262         }
8263
8264       if (arg == error_mark_node)
8265         {
8266           if (complain & tf_error)
8267             error ("template argument %d is invalid", arg_idx + 1);
8268         }
8269       else
8270         arg = convert_template_argument (actual_parm,
8271                                          arg, new_args, complain, parm_idx,
8272                                          in_decl);
8273       if (arg == error_mark_node)
8274         (*lost)++;
8275       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8276     }
8277
8278   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8279       && TREE_VEC_LENGTH (packed_args) > 0)
8280     {
8281       if (complain & tf_error)
8282         error ("wrong number of template arguments (%d, should be %d)",
8283                arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8284       return error_mark_node;
8285     }
8286
8287   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8288       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8289     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8290   else
8291     {
8292       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8293       TREE_CONSTANT (argument_pack) = 1;
8294     }
8295
8296   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8297   if (CHECKING_P)
8298     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8299                                          TREE_VEC_LENGTH (packed_args));
8300   return argument_pack;
8301 }
8302
8303 /* Returns the number of pack expansions in the template argument vector
8304    ARGS.  */
8305
8306 static int
8307 pack_expansion_args_count (tree args)
8308 {
8309   int i;
8310   int count = 0;
8311   if (args)
8312     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8313       {
8314         tree elt = TREE_VEC_ELT (args, i);
8315         if (elt && PACK_EXPANSION_P (elt))
8316           ++count;
8317       }
8318   return count;
8319 }
8320
8321 /* Convert all template arguments to their appropriate types, and
8322    return a vector containing the innermost resulting template
8323    arguments.  If any error occurs, return error_mark_node. Error and
8324    warning messages are issued under control of COMPLAIN.
8325
8326    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8327    for arguments not specified in ARGS.  Otherwise, if
8328    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8329    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8330    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8331    ARGS.  */
8332
8333 static tree
8334 coerce_template_parms (tree parms,
8335                        tree args,
8336                        tree in_decl,
8337                        tsubst_flags_t complain,
8338                        bool require_all_args,
8339                        bool use_default_args)
8340 {
8341   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8342   tree orig_inner_args;
8343   tree inner_args;
8344   tree new_args;
8345   tree new_inner_args;
8346
8347   /* When used as a boolean value, indicates whether this is a
8348      variadic template parameter list. Since it's an int, we can also
8349      subtract it from nparms to get the number of non-variadic
8350      parameters.  */
8351   int variadic_p = 0;
8352   int variadic_args_p = 0;
8353   int post_variadic_parms = 0;
8354
8355   /* Adjustment to nparms for fixed parameter packs.  */
8356   int fixed_pack_adjust = 0;
8357   int fixed_packs = 0;
8358   int missing = 0;
8359
8360   /* Likewise for parameters with default arguments.  */
8361   int default_p = 0;
8362
8363   if (args == error_mark_node)
8364     return error_mark_node;
8365
8366   nparms = TREE_VEC_LENGTH (parms);
8367
8368   /* Determine if there are any parameter packs or default arguments.  */
8369   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8370     {
8371       tree parm = TREE_VEC_ELT (parms, parm_idx);
8372       if (variadic_p)
8373         ++post_variadic_parms;
8374       if (template_parameter_pack_p (TREE_VALUE (parm)))
8375         ++variadic_p;
8376       if (TREE_PURPOSE (parm))
8377         ++default_p;
8378     }
8379
8380   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8381   /* If there are no parameters that follow a parameter pack, we need to
8382      expand any argument packs so that we can deduce a parameter pack from
8383      some non-packed args followed by an argument pack, as in variadic85.C.
8384      If there are such parameters, we need to leave argument packs intact
8385      so the arguments are assigned properly.  This can happen when dealing
8386      with a nested class inside a partial specialization of a class
8387      template, as in variadic92.C, or when deducing a template parameter pack
8388      from a sub-declarator, as in variadic114.C.  */
8389   if (!post_variadic_parms)
8390     inner_args = expand_template_argument_pack (inner_args);
8391
8392   /* Count any pack expansion args.  */
8393   variadic_args_p = pack_expansion_args_count (inner_args);
8394
8395   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8396   if ((nargs - variadic_args_p > nparms && !variadic_p)
8397       || (nargs < nparms - variadic_p
8398           && require_all_args
8399           && !variadic_args_p
8400           && (!use_default_args
8401               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8402                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8403     {
8404     bad_nargs:
8405       if (complain & tf_error)
8406         {
8407           if (variadic_p || default_p)
8408             {
8409               nparms -= variadic_p + default_p;
8410               error ("wrong number of template arguments "
8411                      "(%d, should be at least %d)", nargs, nparms);
8412             }
8413           else
8414              error ("wrong number of template arguments "
8415                     "(%d, should be %d)", nargs, nparms);
8416
8417           if (in_decl)
8418             inform (DECL_SOURCE_LOCATION (in_decl),
8419                     "provided for %qD", in_decl);
8420         }
8421
8422       return error_mark_node;
8423     }
8424   /* We can't pass a pack expansion to a non-pack parameter of an alias
8425      template (DR 1430).  */
8426   else if (in_decl
8427            && (DECL_ALIAS_TEMPLATE_P (in_decl)
8428                || concept_template_p (in_decl))
8429            && variadic_args_p
8430            && nargs - variadic_args_p < nparms - variadic_p)
8431     {
8432       if (complain & tf_error)
8433         {
8434           for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8435             {
8436               tree arg = TREE_VEC_ELT (inner_args, i);
8437               tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8438
8439               if (PACK_EXPANSION_P (arg)
8440                   && !template_parameter_pack_p (parm))
8441                 {
8442                   if (DECL_ALIAS_TEMPLATE_P (in_decl))
8443                     error_at (location_of (arg),
8444                               "pack expansion argument for non-pack parameter "
8445                               "%qD of alias template %qD", parm, in_decl);
8446                   else
8447                     error_at (location_of (arg),
8448                               "pack expansion argument for non-pack parameter "
8449                               "%qD of concept %qD", parm, in_decl);
8450                   inform (DECL_SOURCE_LOCATION (parm), "declared here");
8451                   goto found;
8452                 }
8453             }
8454           gcc_unreachable ();
8455         found:;
8456         }
8457       return error_mark_node;
8458     }
8459
8460   /* We need to evaluate the template arguments, even though this
8461      template-id may be nested within a "sizeof".  */
8462   cp_evaluated ev;
8463
8464   new_inner_args = make_tree_vec (nparms);
8465   new_args = add_outermost_template_args (args, new_inner_args);
8466   int pack_adjust = 0;
8467   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8468     {
8469       tree arg;
8470       tree parm;
8471
8472       /* Get the Ith template parameter.  */
8473       parm = TREE_VEC_ELT (parms, parm_idx);
8474
8475       if (parm == error_mark_node)
8476         {
8477           TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8478           continue;
8479         }
8480
8481       /* Calculate the next argument.  */
8482       if (arg_idx < nargs)
8483         arg = TREE_VEC_ELT (inner_args, arg_idx);
8484       else
8485         arg = NULL_TREE;
8486
8487       if (template_parameter_pack_p (TREE_VALUE (parm))
8488           && (arg || require_all_args || !(complain & tf_partial))
8489           && !(arg && ARGUMENT_PACK_P (arg)))
8490         {
8491           /* Some arguments will be placed in the
8492              template parameter pack PARM.  */
8493           arg = coerce_template_parameter_pack (parms, parm_idx, args,
8494                                                 inner_args, arg_idx,
8495                                                 new_args, &lost,
8496                                                 in_decl, complain);
8497
8498           if (arg == NULL_TREE)
8499             {
8500               /* We don't know how many args we have yet, just use the
8501                  unconverted (and still packed) ones for now.  */
8502               new_inner_args = orig_inner_args;
8503               arg_idx = nargs;
8504               break;
8505             }
8506
8507           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8508
8509           /* Store this argument.  */
8510           if (arg == error_mark_node)
8511             {
8512               lost++;
8513               /* We are done with all of the arguments.  */
8514               arg_idx = nargs;
8515               break;
8516             }
8517           else
8518             {
8519               pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8520               arg_idx += pack_adjust;
8521               if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8522                 {
8523                   ++fixed_packs;
8524                   fixed_pack_adjust += pack_adjust;
8525                 }
8526             }
8527
8528           continue;
8529         }
8530       else if (arg)
8531         {
8532           if (PACK_EXPANSION_P (arg))
8533             {
8534               /* "If every valid specialization of a variadic template
8535                  requires an empty template parameter pack, the template is
8536                  ill-formed, no diagnostic required."  So check that the
8537                  pattern works with this parameter.  */
8538               tree pattern = PACK_EXPANSION_PATTERN (arg);
8539               tree conv = convert_template_argument (TREE_VALUE (parm),
8540                                                      pattern, new_args,
8541                                                      complain, parm_idx,
8542                                                      in_decl);
8543               if (conv == error_mark_node)
8544                 {
8545                   if (complain & tf_error)
8546                     inform (input_location, "so any instantiation with a "
8547                             "non-empty parameter pack would be ill-formed");
8548                   ++lost;
8549                 }
8550               else if (TYPE_P (conv) && !TYPE_P (pattern))
8551                 /* Recover from missing typename.  */
8552                 TREE_VEC_ELT (inner_args, arg_idx)
8553                   = make_pack_expansion (conv, complain);
8554
8555               /* We don't know how many args we have yet, just
8556                  use the unconverted ones for now.  */
8557               new_inner_args = inner_args;
8558               arg_idx = nargs;
8559               break;
8560             }
8561         }
8562       else if (require_all_args)
8563         {
8564           /* There must be a default arg in this case.  */
8565           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8566                                      complain, in_decl);
8567           /* The position of the first default template argument,
8568              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8569              Record that.  */
8570           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8571             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8572                                                  arg_idx - pack_adjust);
8573         }
8574       else
8575         break;
8576
8577       if (arg == error_mark_node)
8578         {
8579           if (complain & tf_error)
8580             error ("template argument %d is invalid", arg_idx + 1);
8581         }
8582       else if (!arg)
8583         {
8584           /* This can occur if there was an error in the template
8585              parameter list itself (which we would already have
8586              reported) that we are trying to recover from, e.g., a class
8587              template with a parameter list such as
8588              template<typename..., typename> (cpp0x/variadic150.C).  */
8589           ++lost;
8590
8591           /* This can also happen with a fixed parameter pack (71834).  */
8592           if (arg_idx >= nargs)
8593             ++missing;
8594         }
8595       else
8596         arg = convert_template_argument (TREE_VALUE (parm),
8597                                          arg, new_args, complain,
8598                                          parm_idx, in_decl);
8599
8600       if (arg == error_mark_node)
8601         lost++;
8602       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8603     }
8604
8605   if (missing || arg_idx < nargs - variadic_args_p)
8606     {
8607       /* If we had fixed parameter packs, we didn't know how many arguments we
8608          actually needed earlier; now we do.  */
8609       nparms += fixed_pack_adjust;
8610       variadic_p -= fixed_packs;
8611       goto bad_nargs;
8612     }
8613
8614   if (arg_idx < nargs)
8615     {
8616       /* We had some pack expansion arguments that will only work if the packs
8617          are empty, but wait until instantiation time to complain.
8618          See variadic-ttp3.C.  */
8619       int len = nparms + (nargs - arg_idx);
8620       tree args = make_tree_vec (len);
8621       int i = 0;
8622       for (; i < nparms; ++i)
8623         TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8624       for (; i < len; ++i, ++arg_idx)
8625         TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8626                                                arg_idx - pack_adjust);
8627       new_inner_args = args;
8628     }
8629
8630   if (lost)
8631     {
8632       gcc_assert (!(complain & tf_error) || seen_error ());
8633       return error_mark_node;
8634     }
8635
8636   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8637     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8638                                          TREE_VEC_LENGTH (new_inner_args));
8639
8640   return new_inner_args;
8641 }
8642
8643 /* Convert all template arguments to their appropriate types, and
8644    return a vector containing the innermost resulting template
8645    arguments.  If any error occurs, return error_mark_node. Error and
8646    warning messages are not issued.
8647
8648    Note that no function argument deduction is performed, and default
8649    arguments are used to fill in unspecified arguments. */
8650 tree
8651 coerce_template_parms (tree parms, tree args, tree in_decl)
8652 {
8653   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8654 }
8655
8656 /* Convert all template arguments to their appropriate type, and
8657    instantiate default arguments as needed. This returns a vector
8658    containing the innermost resulting template arguments, or
8659    error_mark_node if unsuccessful.  */
8660 tree
8661 coerce_template_parms (tree parms, tree args, tree in_decl,
8662                        tsubst_flags_t complain)
8663 {
8664   return coerce_template_parms (parms, args, in_decl, complain, true, true);
8665 }
8666
8667 /* Like coerce_template_parms.  If PARMS represents all template
8668    parameters levels, this function returns a vector of vectors
8669    representing all the resulting argument levels.  Note that in this
8670    case, only the innermost arguments are coerced because the
8671    outermost ones are supposed to have been coerced already.
8672
8673    Otherwise, if PARMS represents only (the innermost) vector of
8674    parameters, this function returns a vector containing just the
8675    innermost resulting arguments.  */
8676
8677 static tree
8678 coerce_innermost_template_parms (tree parms,
8679                                   tree args,
8680                                   tree in_decl,
8681                                   tsubst_flags_t complain,
8682                                   bool require_all_args,
8683                                   bool use_default_args)
8684 {
8685   int parms_depth = TMPL_PARMS_DEPTH (parms);
8686   int args_depth = TMPL_ARGS_DEPTH (args);
8687   tree coerced_args;
8688
8689   if (parms_depth > 1)
8690     {
8691       coerced_args = make_tree_vec (parms_depth);
8692       tree level;
8693       int cur_depth;
8694
8695       for (level = parms, cur_depth = parms_depth;
8696            parms_depth > 0 && level != NULL_TREE;
8697            level = TREE_CHAIN (level), --cur_depth)
8698         {
8699           tree l;
8700           if (cur_depth == args_depth)
8701             l = coerce_template_parms (TREE_VALUE (level),
8702                                        args, in_decl, complain,
8703                                        require_all_args,
8704                                        use_default_args);
8705           else
8706             l = TMPL_ARGS_LEVEL (args, cur_depth);
8707
8708           if (l == error_mark_node)
8709             return error_mark_node;
8710
8711           SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8712         }
8713     }
8714   else
8715     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8716                                           args, in_decl, complain,
8717                                           require_all_args,
8718                                           use_default_args);
8719   return coerced_args;
8720 }
8721
8722 /* Returns 1 if template args OT and NT are equivalent.  */
8723
8724 int
8725 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8726 {
8727   if (nt == ot)
8728     return 1;
8729   if (nt == NULL_TREE || ot == NULL_TREE)
8730     return false;
8731   if (nt == any_targ_node || ot == any_targ_node)
8732     return true;
8733
8734   if (TREE_CODE (nt) == TREE_VEC)
8735     /* For member templates */
8736     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8737   else if (PACK_EXPANSION_P (ot))
8738     return (PACK_EXPANSION_P (nt)
8739             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8740                                     PACK_EXPANSION_PATTERN (nt))
8741             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8742                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
8743   else if (ARGUMENT_PACK_P (ot))
8744     {
8745       int i, len;
8746       tree opack, npack;
8747
8748       if (!ARGUMENT_PACK_P (nt))
8749         return 0;
8750
8751       opack = ARGUMENT_PACK_ARGS (ot);
8752       npack = ARGUMENT_PACK_ARGS (nt);
8753       len = TREE_VEC_LENGTH (opack);
8754       if (TREE_VEC_LENGTH (npack) != len)
8755         return 0;
8756       for (i = 0; i < len; ++i)
8757         if (!template_args_equal (TREE_VEC_ELT (opack, i),
8758                                   TREE_VEC_ELT (npack, i)))
8759           return 0;
8760       return 1;
8761     }
8762   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8763     gcc_unreachable ();
8764   else if (TYPE_P (nt))
8765     {
8766       if (!TYPE_P (ot))
8767         return false;
8768       /* Don't treat an alias template specialization with dependent
8769          arguments as equivalent to its underlying type when used as a
8770          template argument; we need them to be distinct so that we
8771          substitute into the specialization arguments at instantiation
8772          time.  And aliases can't be equivalent without being ==, so
8773          we don't need to look any deeper.
8774
8775          During partial ordering, however, we need to treat them normally so
8776          that we can order uses of the same alias with different
8777          cv-qualification (79960).  */
8778       if (!partial_order
8779           && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8780         return false;
8781       else
8782         return same_type_p (ot, nt);
8783     }
8784   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8785     return 0;
8786   else
8787     {
8788       /* Try to treat a template non-type argument that has been converted
8789          to the parameter type as equivalent to one that hasn't yet.  */
8790       for (enum tree_code code1 = TREE_CODE (ot);
8791            CONVERT_EXPR_CODE_P (code1)
8792              || code1 == NON_LVALUE_EXPR;
8793            code1 = TREE_CODE (ot))
8794         ot = TREE_OPERAND (ot, 0);
8795       for (enum tree_code code2 = TREE_CODE (nt);
8796            CONVERT_EXPR_CODE_P (code2)
8797              || code2 == NON_LVALUE_EXPR;
8798            code2 = TREE_CODE (nt))
8799         nt = TREE_OPERAND (nt, 0);
8800
8801       return cp_tree_equal (ot, nt);
8802     }
8803 }
8804
8805 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8806    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
8807    NEWARG_PTR with the offending arguments if they are non-NULL.  */
8808
8809 int
8810 comp_template_args (tree oldargs, tree newargs,
8811                     tree *oldarg_ptr, tree *newarg_ptr,
8812                     bool partial_order)
8813 {
8814   int i;
8815
8816   if (oldargs == newargs)
8817     return 1;
8818
8819   if (!oldargs || !newargs)
8820     return 0;
8821
8822   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8823     return 0;
8824
8825   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8826     {
8827       tree nt = TREE_VEC_ELT (newargs, i);
8828       tree ot = TREE_VEC_ELT (oldargs, i);
8829
8830       if (! template_args_equal (ot, nt, partial_order))
8831         {
8832           if (oldarg_ptr != NULL)
8833             *oldarg_ptr = ot;
8834           if (newarg_ptr != NULL)
8835             *newarg_ptr = nt;
8836           return 0;
8837         }
8838     }
8839   return 1;
8840 }
8841
8842 inline bool
8843 comp_template_args_porder (tree oargs, tree nargs)
8844 {
8845   return comp_template_args (oargs, nargs, NULL, NULL, true);
8846 }
8847
8848 /* Implement a freelist interface for objects of type T.
8849
8850    Head is a separate object, rather than a regular member, so that we
8851    can define it as a GTY deletable pointer, which is highly
8852    desirable.  A data member could be declared that way, but then the
8853    containing object would implicitly get GTY((user)), which would
8854    prevent us from instantiating freelists as global objects.
8855    Although this way we can create freelist global objects, they're
8856    such thin wrappers that instantiating temporaries at every use
8857    loses nothing and saves permanent storage for the freelist object.
8858
8859    Member functions next, anew, poison and reinit have default
8860    implementations that work for most of the types we're interested
8861    in, but if they don't work for some type, they should be explicitly
8862    specialized.  See the comments before them for requirements, and
8863    the example specializations for the tree_list_freelist.  */
8864 template <typename T>
8865 class freelist
8866 {
8867   /* Return the next object in a chain.  We could just do type
8868      punning, but if we access the object with its underlying type, we
8869      avoid strict-aliasing trouble.  This needs only work between
8870      poison and reinit.  */
8871   static T *&next (T *obj) { return obj->next; }
8872
8873   /* Return a newly allocated, uninitialized or minimally-initialized
8874      object of type T.  Any initialization performed by anew should
8875      either remain across the life of the object and the execution of
8876      poison, or be redone by reinit.  */
8877   static T *anew () { return ggc_alloc<T> (); }
8878
8879   /* Optionally scribble all over the bits holding the object, so that
8880      they become (mostly?) uninitialized memory.  This is called while
8881      preparing to make the object part of the free list.  */
8882   static void poison (T *obj) {
8883     T *p ATTRIBUTE_UNUSED = obj;
8884     T **q ATTRIBUTE_UNUSED = &next (obj);
8885
8886 #ifdef ENABLE_GC_CHECKING
8887     /* Poison the data, to indicate the data is garbage.  */
8888     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
8889     memset (p, 0xa5, sizeof (*p));
8890 #endif
8891     /* Let valgrind know the object is free.  */
8892     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
8893
8894     /* Let valgrind know the next portion of the object is available,
8895        but uninitialized.  */
8896     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8897   }
8898
8899   /* Bring an object that underwent at least one lifecycle after anew
8900      and before the most recent free and poison, back to a usable
8901      state, reinitializing whatever is needed for it to be
8902      functionally equivalent to an object just allocated and returned
8903      by anew.  This may poison or clear the next field, used by
8904      freelist housekeeping after poison was called.  */
8905   static void reinit (T *obj) {
8906     T **q ATTRIBUTE_UNUSED = &next (obj);
8907
8908 #ifdef ENABLE_GC_CHECKING
8909     memset (q, 0xa5, sizeof (*q));
8910 #endif
8911     /* Let valgrind know the entire object is available, but
8912        uninitialized.  */
8913     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
8914   }
8915
8916   /* Reference a GTY-deletable pointer that points to the first object
8917      in the free list proper.  */
8918   T *&head;
8919 public:
8920   /* Construct a freelist object chaining objects off of HEAD.  */
8921   freelist (T *&head) : head(head) {}
8922
8923   /* Add OBJ to the free object list.  The former head becomes OBJ's
8924      successor.  */
8925   void free (T *obj)
8926   {
8927     poison (obj);
8928     next (obj) = head;
8929     head = obj;
8930   }
8931
8932   /* Take an object from the free list, if one is available, or
8933      allocate a new one.  Objects taken from the free list should be
8934      regarded as filled with garbage, except for bits that are
8935      configured to be preserved across free and alloc.  */
8936   T *alloc ()
8937   {
8938     if (head)
8939       {
8940         T *obj = head;
8941         head = next (head);
8942         reinit (obj);
8943         return obj;
8944       }
8945     else
8946       return anew ();
8947   }
8948 };
8949
8950 /* Explicitly specialize the interfaces for freelist<tree_node>: we
8951    want to allocate a TREE_LIST using the usual interface, and ensure
8952    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
8953    build_tree_list logic in reinit, so this could go out of sync.  */
8954 template <>
8955 inline tree &
8956 freelist<tree_node>::next (tree obj)
8957 {
8958   return TREE_CHAIN (obj);
8959 }
8960 template <>
8961 inline tree
8962 freelist<tree_node>::anew ()
8963 {
8964   return build_tree_list (NULL, NULL);
8965 }
8966 template <>
8967 inline void
8968 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
8969 {
8970   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
8971   tree p ATTRIBUTE_UNUSED = obj;
8972   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8973   tree *q ATTRIBUTE_UNUSED = &next (obj);
8974
8975 #ifdef ENABLE_GC_CHECKING
8976   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8977
8978   /* Poison the data, to indicate the data is garbage.  */
8979   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
8980   memset (p, 0xa5, size);
8981 #endif
8982   /* Let valgrind know the object is free.  */
8983   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
8984   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
8985   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8986   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8987
8988 #ifdef ENABLE_GC_CHECKING
8989   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
8990   /* Keep TREE_CHAIN functional.  */
8991   TREE_SET_CODE (obj, TREE_LIST);
8992 #else
8993   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8994 #endif
8995 }
8996 template <>
8997 inline void
8998 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
8999 {
9000   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9001
9002 #ifdef ENABLE_GC_CHECKING
9003   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9004   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9005   memset (obj, 0, sizeof (tree_list));
9006 #endif
9007
9008   /* Let valgrind know the entire object is available, but
9009      uninitialized.  */
9010   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9011
9012 #ifdef ENABLE_GC_CHECKING
9013   TREE_SET_CODE (obj, TREE_LIST);
9014 #else
9015   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9016 #endif
9017 }
9018
9019 /* Point to the first object in the TREE_LIST freelist.  */
9020 static GTY((deletable)) tree tree_list_freelist_head;
9021 /* Return the/an actual TREE_LIST freelist.  */
9022 static inline freelist<tree_node>
9023 tree_list_freelist ()
9024 {
9025   return tree_list_freelist_head;
9026 }
9027
9028 /* Point to the first object in the tinst_level freelist.  */
9029 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9030 /* Return the/an actual tinst_level freelist.  */
9031 static inline freelist<tinst_level>
9032 tinst_level_freelist ()
9033 {
9034   return tinst_level_freelist_head;
9035 }
9036
9037 /* Point to the first object in the pending_template freelist.  */
9038 static GTY((deletable)) pending_template *pending_template_freelist_head;
9039 /* Return the/an actual pending_template freelist.  */
9040 static inline freelist<pending_template>
9041 pending_template_freelist ()
9042 {
9043   return pending_template_freelist_head;
9044 }
9045
9046 /* Build the TREE_LIST object out of a split list, store it
9047    permanently, and return it.  */
9048 tree
9049 tinst_level::to_list ()
9050 {
9051   gcc_assert (split_list_p ());
9052   tree ret = tree_list_freelist ().alloc ();
9053   TREE_PURPOSE (ret) = tldcl;
9054   TREE_VALUE (ret) = targs;
9055   tldcl = ret;
9056   targs = NULL;
9057   gcc_assert (tree_list_p ());
9058   return ret;
9059 }
9060
9061 const unsigned short tinst_level::refcount_infinity;
9062
9063 /* Increment OBJ's refcount unless it is already infinite.  */
9064 static tinst_level *
9065 inc_refcount_use (tinst_level *obj)
9066 {
9067   if (obj && obj->refcount != tinst_level::refcount_infinity)
9068     ++obj->refcount;
9069   return obj;
9070 }
9071
9072 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9073 void
9074 tinst_level::free (tinst_level *obj)
9075 {
9076   if (obj->tree_list_p ())
9077     tree_list_freelist ().free (obj->get_node ());
9078   tinst_level_freelist ().free (obj);
9079 }
9080
9081 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9082    OBJ's DECL and OBJ, and start over with the tinst_level object that
9083    used to be referenced by OBJ's NEXT.  */
9084 static void
9085 dec_refcount_use (tinst_level *obj)
9086 {
9087   while (obj
9088          && obj->refcount != tinst_level::refcount_infinity
9089          && !--obj->refcount)
9090     {
9091       tinst_level *next = obj->next;
9092       tinst_level::free (obj);
9093       obj = next;
9094     }
9095 }
9096
9097 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9098    and of the former PTR.  Omitting the second argument is equivalent
9099    to passing (T*)NULL; this is allowed because passing the
9100    zero-valued integral constant NULL confuses type deduction and/or
9101    overload resolution.  */
9102 template <typename T>
9103 static void
9104 set_refcount_ptr (T *& ptr, T *obj = NULL)
9105 {
9106   T *save = ptr;
9107   ptr = inc_refcount_use (obj);
9108   dec_refcount_use (save);
9109 }
9110
9111 static void
9112 add_pending_template (tree d)
9113 {
9114   tree ti = (TYPE_P (d)
9115              ? CLASSTYPE_TEMPLATE_INFO (d)
9116              : DECL_TEMPLATE_INFO (d));
9117   struct pending_template *pt;
9118   int level;
9119
9120   if (TI_PENDING_TEMPLATE_FLAG (ti))
9121     return;
9122
9123   /* We are called both from instantiate_decl, where we've already had a
9124      tinst_level pushed, and instantiate_template, where we haven't.
9125      Compensate.  */
9126   gcc_assert (TREE_CODE (d) != TREE_LIST);
9127   level = !current_tinst_level
9128     || current_tinst_level->maybe_get_node () != d;
9129
9130   if (level)
9131     push_tinst_level (d);
9132
9133   pt = pending_template_freelist ().alloc ();
9134   pt->next = NULL;
9135   pt->tinst = NULL;
9136   set_refcount_ptr (pt->tinst, current_tinst_level);
9137   if (last_pending_template)
9138     last_pending_template->next = pt;
9139   else
9140     pending_templates = pt;
9141
9142   last_pending_template = pt;
9143
9144   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9145
9146   if (level)
9147     pop_tinst_level ();
9148 }
9149
9150
9151 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9152    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9153    documentation for TEMPLATE_ID_EXPR.  */
9154
9155 tree
9156 lookup_template_function (tree fns, tree arglist)
9157 {
9158   if (fns == error_mark_node || arglist == error_mark_node)
9159     return error_mark_node;
9160
9161   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9162
9163   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9164     {
9165       error ("%q#D is not a function template", fns);
9166       return error_mark_node;
9167     }
9168
9169   if (BASELINK_P (fns))
9170     {
9171       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9172                                          unknown_type_node,
9173                                          BASELINK_FUNCTIONS (fns),
9174                                          arglist);
9175       return fns;
9176     }
9177
9178   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9179 }
9180
9181 /* Within the scope of a template class S<T>, the name S gets bound
9182    (in build_self_reference) to a TYPE_DECL for the class, not a
9183    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9184    or one of its enclosing classes, and that type is a template,
9185    return the associated TEMPLATE_DECL.  Otherwise, the original
9186    DECL is returned.
9187
9188    Also handle the case when DECL is a TREE_LIST of ambiguous
9189    injected-class-names from different bases.  */
9190
9191 tree
9192 maybe_get_template_decl_from_type_decl (tree decl)
9193 {
9194   if (decl == NULL_TREE)
9195     return decl;
9196
9197   /* DR 176: A lookup that finds an injected-class-name (10.2
9198      [class.member.lookup]) can result in an ambiguity in certain cases
9199      (for example, if it is found in more than one base class). If all of
9200      the injected-class-names that are found refer to specializations of
9201      the same class template, and if the name is followed by a
9202      template-argument-list, the reference refers to the class template
9203      itself and not a specialization thereof, and is not ambiguous.  */
9204   if (TREE_CODE (decl) == TREE_LIST)
9205     {
9206       tree t, tmpl = NULL_TREE;
9207       for (t = decl; t; t = TREE_CHAIN (t))
9208         {
9209           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9210           if (!tmpl)
9211             tmpl = elt;
9212           else if (tmpl != elt)
9213             break;
9214         }
9215       if (tmpl && t == NULL_TREE)
9216         return tmpl;
9217       else
9218         return decl;
9219     }
9220
9221   return (decl != NULL_TREE
9222           && DECL_SELF_REFERENCE_P (decl)
9223           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9224     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9225 }
9226
9227 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9228    parameters, find the desired type.
9229
9230    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9231
9232    IN_DECL, if non-NULL, is the template declaration we are trying to
9233    instantiate.
9234
9235    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9236    the class we are looking up.
9237
9238    Issue error and warning messages under control of COMPLAIN.
9239
9240    If the template class is really a local class in a template
9241    function, then the FUNCTION_CONTEXT is the function in which it is
9242    being instantiated.
9243
9244    ??? Note that this function is currently called *twice* for each
9245    template-id: the first time from the parser, while creating the
9246    incomplete type (finish_template_type), and the second type during the
9247    real instantiation (instantiate_template_class). This is surely something
9248    that we want to avoid. It also causes some problems with argument
9249    coercion (see convert_nontype_argument for more information on this).  */
9250
9251 static tree
9252 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9253                          int entering_scope, tsubst_flags_t complain)
9254 {
9255   tree templ = NULL_TREE, parmlist;
9256   tree t;
9257   spec_entry **slot;
9258   spec_entry *entry;
9259   spec_entry elt;
9260   hashval_t hash;
9261
9262   if (identifier_p (d1))
9263     {
9264       tree value = innermost_non_namespace_value (d1);
9265       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9266         templ = value;
9267       else
9268         {
9269           if (context)
9270             push_decl_namespace (context);
9271           templ = lookup_name (d1);
9272           templ = maybe_get_template_decl_from_type_decl (templ);
9273           if (context)
9274             pop_decl_namespace ();
9275         }
9276       if (templ)
9277         context = DECL_CONTEXT (templ);
9278     }
9279   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9280     {
9281       tree type = TREE_TYPE (d1);
9282
9283       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9284          an implicit typename for the second A.  Deal with it.  */
9285       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9286         type = TREE_TYPE (type);
9287
9288       if (CLASSTYPE_TEMPLATE_INFO (type))
9289         {
9290           templ = CLASSTYPE_TI_TEMPLATE (type);
9291           d1 = DECL_NAME (templ);
9292         }
9293     }
9294   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9295            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9296     {
9297       templ = TYPE_TI_TEMPLATE (d1);
9298       d1 = DECL_NAME (templ);
9299     }
9300   else if (DECL_TYPE_TEMPLATE_P (d1))
9301     {
9302       templ = d1;
9303       d1 = DECL_NAME (templ);
9304       context = DECL_CONTEXT (templ);
9305     }
9306   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9307     {
9308       templ = d1;
9309       d1 = DECL_NAME (templ);
9310     }
9311
9312   /* Issue an error message if we didn't find a template.  */
9313   if (! templ)
9314     {
9315       if (complain & tf_error)
9316         error ("%qT is not a template", d1);
9317       return error_mark_node;
9318     }
9319
9320   if (TREE_CODE (templ) != TEMPLATE_DECL
9321          /* Make sure it's a user visible template, if it was named by
9322             the user.  */
9323       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9324           && !PRIMARY_TEMPLATE_P (templ)))
9325     {
9326       if (complain & tf_error)
9327         {
9328           error ("non-template type %qT used as a template", d1);
9329           if (in_decl)
9330             error ("for template declaration %q+D", in_decl);
9331         }
9332       return error_mark_node;
9333     }
9334
9335   complain &= ~tf_user;
9336
9337   /* An alias that just changes the name of a template is equivalent to the
9338      other template, so if any of the arguments are pack expansions, strip
9339      the alias to avoid problems with a pack expansion passed to a non-pack
9340      alias template parameter (DR 1430).  */
9341   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9342     templ = get_underlying_template (templ);
9343
9344   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9345     {
9346       tree parm;
9347       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9348       if (arglist2 == error_mark_node
9349           || (!uses_template_parms (arglist2)
9350               && check_instantiated_args (templ, arglist2, complain)))
9351         return error_mark_node;
9352
9353       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9354       return parm;
9355     }
9356   else
9357     {
9358       tree template_type = TREE_TYPE (templ);
9359       tree gen_tmpl;
9360       tree type_decl;
9361       tree found = NULL_TREE;
9362       int arg_depth;
9363       int parm_depth;
9364       int is_dependent_type;
9365       int use_partial_inst_tmpl = false;
9366
9367       if (template_type == error_mark_node)
9368         /* An error occurred while building the template TEMPL, and a
9369            diagnostic has most certainly been emitted for that
9370            already.  Let's propagate that error.  */
9371         return error_mark_node;
9372
9373       gen_tmpl = most_general_template (templ);
9374       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9375       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9376       arg_depth = TMPL_ARGS_DEPTH (arglist);
9377
9378       if (arg_depth == 1 && parm_depth > 1)
9379         {
9380           /* We've been given an incomplete set of template arguments.
9381              For example, given:
9382
9383                template <class T> struct S1 {
9384                  template <class U> struct S2 {};
9385                  template <class U> struct S2<U*> {};
9386                 };
9387
9388              we will be called with an ARGLIST of `U*', but the
9389              TEMPLATE will be `template <class T> template
9390              <class U> struct S1<T>::S2'.  We must fill in the missing
9391              arguments.  */
9392           tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9393           arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9394           arg_depth = TMPL_ARGS_DEPTH (arglist);
9395         }
9396
9397       /* Now we should have enough arguments.  */
9398       gcc_assert (parm_depth == arg_depth);
9399
9400       /* From here on, we're only interested in the most general
9401          template.  */
9402
9403       /* Calculate the BOUND_ARGS.  These will be the args that are
9404          actually tsubst'd into the definition to create the
9405          instantiation.  */
9406       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9407                                                  complain,
9408                                                  /*require_all_args=*/true,
9409                                                  /*use_default_args=*/true);
9410
9411       if (arglist == error_mark_node)
9412         /* We were unable to bind the arguments.  */
9413         return error_mark_node;
9414
9415       /* In the scope of a template class, explicit references to the
9416          template class refer to the type of the template, not any
9417          instantiation of it.  For example, in:
9418
9419            template <class T> class C { void f(C<T>); }
9420
9421          the `C<T>' is just the same as `C'.  Outside of the
9422          class, however, such a reference is an instantiation.  */
9423       if (entering_scope
9424           || !PRIMARY_TEMPLATE_P (gen_tmpl)
9425           || currently_open_class (template_type))
9426         {
9427           tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9428
9429           if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9430             return template_type;
9431         }
9432
9433       /* If we already have this specialization, return it.  */
9434       elt.tmpl = gen_tmpl;
9435       elt.args = arglist;
9436       elt.spec = NULL_TREE;
9437       hash = spec_hasher::hash (&elt);
9438       entry = type_specializations->find_with_hash (&elt, hash);
9439
9440       if (entry)
9441         return entry->spec;
9442
9443       /* If the the template's constraints are not satisfied,
9444          then we cannot form a valid type.
9445
9446          Note that the check is deferred until after the hash
9447          lookup. This prevents redundant checks on previously
9448          instantiated specializations. */
9449       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9450         {
9451           if (complain & tf_error)
9452             {
9453               auto_diagnostic_group d;
9454               error ("template constraint failure");
9455               diagnose_constraints (input_location, gen_tmpl, arglist);
9456             }
9457           return error_mark_node;
9458         }
9459
9460       is_dependent_type = uses_template_parms (arglist);
9461
9462       /* If the deduced arguments are invalid, then the binding
9463          failed.  */
9464       if (!is_dependent_type
9465           && check_instantiated_args (gen_tmpl,
9466                                       INNERMOST_TEMPLATE_ARGS (arglist),
9467                                       complain))
9468         return error_mark_node;
9469
9470       if (!is_dependent_type
9471           && !PRIMARY_TEMPLATE_P (gen_tmpl)
9472           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9473           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9474         {
9475           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9476                                       DECL_NAME (gen_tmpl),
9477                                       /*tag_scope=*/ts_global);
9478           return found;
9479         }
9480
9481       context = DECL_CONTEXT (gen_tmpl);
9482       if (context && TYPE_P (context))
9483         {
9484           context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9485           context = complete_type (context);
9486         }
9487       else
9488         context = tsubst (context, arglist, complain, in_decl);
9489
9490       if (context == error_mark_node)
9491         return error_mark_node;
9492
9493       if (!context)
9494         context = global_namespace;
9495
9496       /* Create the type.  */
9497       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9498         {
9499           /* The user referred to a specialization of an alias
9500             template represented by GEN_TMPL.
9501
9502             [temp.alias]/2 says:
9503
9504                 When a template-id refers to the specialization of an
9505                 alias template, it is equivalent to the associated
9506                 type obtained by substitution of its
9507                 template-arguments for the template-parameters in the
9508                 type-id of the alias template.  */
9509
9510           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9511           /* Note that the call above (by indirectly calling
9512              register_specialization in tsubst_decl) registers the
9513              TYPE_DECL representing the specialization of the alias
9514              template.  So next time someone substitutes ARGLIST for
9515              the template parms into the alias template (GEN_TMPL),
9516              she'll get that TYPE_DECL back.  */
9517
9518           if (t == error_mark_node)
9519             return t;
9520         }
9521       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9522         {
9523           if (!is_dependent_type)
9524             {
9525               set_current_access_from_decl (TYPE_NAME (template_type));
9526               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9527                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
9528                                       arglist, complain, in_decl),
9529                               tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9530                                                  arglist, complain, in_decl),
9531                               SCOPED_ENUM_P (template_type), NULL);
9532
9533               if (t == error_mark_node)
9534                 return t;
9535             }
9536           else
9537             {
9538               /* We don't want to call start_enum for this type, since
9539                  the values for the enumeration constants may involve
9540                  template parameters.  And, no one should be interested
9541                  in the enumeration constants for such a type.  */
9542               t = cxx_make_type (ENUMERAL_TYPE);
9543               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9544             }
9545           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9546           ENUM_FIXED_UNDERLYING_TYPE_P (t)
9547             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9548         }
9549       else if (CLASS_TYPE_P (template_type))
9550         {
9551           /* Lambda closures are regenerated in tsubst_lambda_expr, not
9552              instantiated here.  */
9553           gcc_assert (!LAMBDA_TYPE_P (template_type));
9554
9555           t = make_class_type (TREE_CODE (template_type));
9556           CLASSTYPE_DECLARED_CLASS (t)
9557             = CLASSTYPE_DECLARED_CLASS (template_type);
9558           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9559
9560           /* A local class.  Make sure the decl gets registered properly.  */
9561           if (context == current_function_decl)
9562             if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9563                 == error_mark_node)
9564               return error_mark_node;
9565
9566           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9567             /* This instantiation is another name for the primary
9568                template type. Set the TYPE_CANONICAL field
9569                appropriately. */
9570             TYPE_CANONICAL (t) = template_type;
9571           else if (any_template_arguments_need_structural_equality_p (arglist))
9572             /* Some of the template arguments require structural
9573                equality testing, so this template class requires
9574                structural equality testing. */
9575             SET_TYPE_STRUCTURAL_EQUALITY (t);
9576         }
9577       else
9578         gcc_unreachable ();
9579
9580       /* If we called start_enum or pushtag above, this information
9581          will already be set up.  */
9582       if (!TYPE_NAME (t))
9583         {
9584           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9585
9586           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9587           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9588           DECL_SOURCE_LOCATION (type_decl)
9589             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9590         }
9591       else
9592         type_decl = TYPE_NAME (t);
9593
9594       if (CLASS_TYPE_P (template_type))
9595         {
9596           TREE_PRIVATE (type_decl)
9597             = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9598           TREE_PROTECTED (type_decl)
9599             = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9600           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9601             {
9602               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9603               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9604             }
9605         }
9606
9607       if (OVERLOAD_TYPE_P (t)
9608           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9609         {
9610           static const char *tags[] = {"abi_tag", "may_alias"};
9611
9612           for (unsigned ix = 0; ix != 2; ix++)
9613             {
9614               tree attributes
9615                 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9616
9617               if (attributes)
9618                 TYPE_ATTRIBUTES (t)
9619                   = tree_cons (TREE_PURPOSE (attributes),
9620                                TREE_VALUE (attributes),
9621                                TYPE_ATTRIBUTES (t));
9622             }
9623         }
9624
9625       /* Let's consider the explicit specialization of a member
9626          of a class template specialization that is implicitly instantiated,
9627          e.g.:
9628              template<class T>
9629              struct S
9630              {
9631                template<class U> struct M {}; //#0
9632              };
9633
9634              template<>
9635              template<>
9636              struct S<int>::M<char> //#1
9637              {
9638                int i;
9639              };
9640         [temp.expl.spec]/4 says this is valid.
9641
9642         In this case, when we write:
9643         S<int>::M<char> m;
9644
9645         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9646         the one of #0.
9647
9648         When we encounter #1, we want to store the partial instantiation
9649         of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9650
9651         For all cases other than this "explicit specialization of member of a
9652         class template", we just want to store the most general template into
9653         the CLASSTYPE_TI_TEMPLATE of M.
9654
9655         This case of "explicit specialization of member of a class template"
9656         only happens when:
9657         1/ the enclosing class is an instantiation of, and therefore not
9658         the same as, the context of the most general template, and
9659         2/ we aren't looking at the partial instantiation itself, i.e.
9660         the innermost arguments are not the same as the innermost parms of
9661         the most general template.
9662
9663         So it's only when 1/ and 2/ happens that we want to use the partial
9664         instantiation of the member template in lieu of its most general
9665         template.  */
9666
9667       if (PRIMARY_TEMPLATE_P (gen_tmpl)
9668           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9669           /* the enclosing class must be an instantiation...  */
9670           && CLASS_TYPE_P (context)
9671           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9672         {
9673           TREE_VEC_LENGTH (arglist)--;
9674           ++processing_template_decl;
9675           tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9676           tree partial_inst_args =
9677             tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9678                     arglist, complain, NULL_TREE);
9679           --processing_template_decl;
9680           TREE_VEC_LENGTH (arglist)++;
9681           if (partial_inst_args == error_mark_node)
9682             return error_mark_node;
9683           use_partial_inst_tmpl =
9684             /*...and we must not be looking at the partial instantiation
9685              itself. */
9686             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9687                                  partial_inst_args);
9688         }
9689
9690       if (!use_partial_inst_tmpl)
9691         /* This case is easy; there are no member templates involved.  */
9692         found = gen_tmpl;
9693       else
9694         {
9695           /* This is a full instantiation of a member template.  Find
9696              the partial instantiation of which this is an instance.  */
9697
9698           /* Temporarily reduce by one the number of levels in the ARGLIST
9699              so as to avoid comparing the last set of arguments.  */
9700           TREE_VEC_LENGTH (arglist)--;
9701           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9702           TREE_VEC_LENGTH (arglist)++;
9703           /* FOUND is either a proper class type, or an alias
9704              template specialization.  In the later case, it's a
9705              TYPE_DECL, resulting from the substituting of arguments
9706              for parameters in the TYPE_DECL of the alias template
9707              done earlier.  So be careful while getting the template
9708              of FOUND.  */
9709           found = (TREE_CODE (found) == TEMPLATE_DECL
9710                    ? found
9711                    : (TREE_CODE (found) == TYPE_DECL
9712                       ? DECL_TI_TEMPLATE (found)
9713                       : CLASSTYPE_TI_TEMPLATE (found)));
9714
9715           if (DECL_CLASS_TEMPLATE_P (found)
9716               && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
9717             {
9718               /* If this partial instantiation is specialized, we want to
9719                  use it for hash table lookup.  */
9720               elt.tmpl = found;
9721               elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
9722               hash = spec_hasher::hash (&elt);
9723             }
9724         }
9725
9726       // Build template info for the new specialization.
9727       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9728
9729       elt.spec = t;
9730       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9731       gcc_checking_assert (*slot == NULL);
9732       entry = ggc_alloc<spec_entry> ();
9733       *entry = elt;
9734       *slot = entry;
9735
9736       /* Note this use of the partial instantiation so we can check it
9737          later in maybe_process_partial_specialization.  */
9738       DECL_TEMPLATE_INSTANTIATIONS (found)
9739         = tree_cons (arglist, t,
9740                      DECL_TEMPLATE_INSTANTIATIONS (found));
9741
9742       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9743           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9744         /* Now that the type has been registered on the instantiations
9745            list, we set up the enumerators.  Because the enumeration
9746            constants may involve the enumeration type itself, we make
9747            sure to register the type first, and then create the
9748            constants.  That way, doing tsubst_expr for the enumeration
9749            constants won't result in recursive calls here; we'll find
9750            the instantiation and exit above.  */
9751         tsubst_enum (template_type, t, arglist);
9752
9753       if (CLASS_TYPE_P (template_type) && is_dependent_type)
9754         /* If the type makes use of template parameters, the
9755            code that generates debugging information will crash.  */
9756         DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9757
9758       /* Possibly limit visibility based on template args.  */
9759       TREE_PUBLIC (type_decl) = 1;
9760       determine_visibility (type_decl);
9761
9762       inherit_targ_abi_tags (t);
9763
9764       return t;
9765     }
9766 }
9767
9768 /* Wrapper for lookup_template_class_1.  */
9769
9770 tree
9771 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9772                        int entering_scope, tsubst_flags_t complain)
9773 {
9774   tree ret;
9775   timevar_push (TV_TEMPLATE_INST);
9776   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9777                                  entering_scope, complain);
9778   timevar_pop (TV_TEMPLATE_INST);
9779   return ret;
9780 }
9781
9782 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
9783
9784 tree
9785 lookup_template_variable (tree templ, tree arglist)
9786 {
9787   /* The type of the expression is NULL_TREE since the template-id could refer
9788      to an explicit or partial specialization. */
9789   tree type = NULL_TREE;
9790   if (flag_concepts && variable_concept_p (templ))
9791     /* Except that concepts are always bool.  */
9792     type = boolean_type_node;
9793   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9794 }
9795
9796 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9797
9798 tree
9799 finish_template_variable (tree var, tsubst_flags_t complain)
9800 {
9801   tree templ = TREE_OPERAND (var, 0);
9802   tree arglist = TREE_OPERAND (var, 1);
9803
9804   /* We never want to return a VAR_DECL for a variable concept, since they
9805      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
9806   bool concept_p = flag_concepts && variable_concept_p (templ);
9807   if (concept_p && processing_template_decl)
9808     return var;
9809
9810   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9811   arglist = add_outermost_template_args (tmpl_args, arglist);
9812
9813   templ = most_general_template (templ);
9814   tree parms = DECL_TEMPLATE_PARMS (templ);
9815   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9816                                              /*req_all*/true,
9817                                              /*use_default*/true);
9818
9819   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9820     {
9821       if (complain & tf_error)
9822         {
9823           auto_diagnostic_group d;
9824           error ("use of invalid variable template %qE", var);
9825           diagnose_constraints (location_of (var), templ, arglist);
9826         }
9827       return error_mark_node;
9828     }
9829
9830   /* If a template-id refers to a specialization of a variable
9831      concept, then the expression is true if and only if the
9832      concept's constraints are satisfied by the given template
9833      arguments.
9834
9835      NOTE: This is an extension of Concepts Lite TS that
9836      allows constraints to be used in expressions. */
9837   if (concept_p)
9838     {
9839       tree decl = DECL_TEMPLATE_RESULT (templ);
9840       return evaluate_variable_concept (decl, arglist);
9841     }
9842
9843   return instantiate_template (templ, arglist, complain);
9844 }
9845
9846 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9847    TARGS template args, and instantiate it if it's not dependent.  */
9848
9849 tree
9850 lookup_and_finish_template_variable (tree templ, tree targs,
9851                                      tsubst_flags_t complain)
9852 {
9853   templ = lookup_template_variable (templ, targs);
9854   if (!any_dependent_template_arguments_p (targs))
9855     {
9856       templ = finish_template_variable (templ, complain);
9857       mark_used (templ);
9858     }
9859
9860   return convert_from_reference (templ);
9861 }
9862
9863 \f
9864 struct pair_fn_data
9865 {
9866   tree_fn_t fn;
9867   tree_fn_t any_fn;
9868   void *data;
9869   /* True when we should also visit template parameters that occur in
9870      non-deduced contexts.  */
9871   bool include_nondeduced_p;
9872   hash_set<tree> *visited;
9873 };
9874
9875 /* Called from for_each_template_parm via walk_tree.  */
9876
9877 static tree
9878 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9879 {
9880   tree t = *tp;
9881   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9882   tree_fn_t fn = pfd->fn;
9883   void *data = pfd->data;
9884   tree result = NULL_TREE;
9885
9886 #define WALK_SUBTREE(NODE)                                              \
9887   do                                                                    \
9888     {                                                                   \
9889       result = for_each_template_parm (NODE, fn, data, pfd->visited,    \
9890                                        pfd->include_nondeduced_p,       \
9891                                        pfd->any_fn);                    \
9892       if (result) goto out;                                             \
9893     }                                                                   \
9894   while (0)
9895
9896   if (pfd->any_fn && (*pfd->any_fn)(t, data))
9897     return t;
9898
9899   if (TYPE_P (t)
9900       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9901     WALK_SUBTREE (TYPE_CONTEXT (t));
9902
9903   switch (TREE_CODE (t))
9904     {
9905     case RECORD_TYPE:
9906       if (TYPE_PTRMEMFUNC_P (t))
9907         break;
9908       /* Fall through.  */
9909
9910     case UNION_TYPE:
9911     case ENUMERAL_TYPE:
9912       if (!TYPE_TEMPLATE_INFO (t))
9913         *walk_subtrees = 0;
9914       else
9915         WALK_SUBTREE (TYPE_TI_ARGS (t));
9916       break;
9917
9918     case INTEGER_TYPE:
9919       WALK_SUBTREE (TYPE_MIN_VALUE (t));
9920       WALK_SUBTREE (TYPE_MAX_VALUE (t));
9921       break;
9922
9923     case METHOD_TYPE:
9924       /* Since we're not going to walk subtrees, we have to do this
9925          explicitly here.  */
9926       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9927       /* Fall through.  */
9928
9929     case FUNCTION_TYPE:
9930       /* Check the return type.  */
9931       WALK_SUBTREE (TREE_TYPE (t));
9932
9933       /* Check the parameter types.  Since default arguments are not
9934          instantiated until they are needed, the TYPE_ARG_TYPES may
9935          contain expressions that involve template parameters.  But,
9936          no-one should be looking at them yet.  And, once they're
9937          instantiated, they don't contain template parameters, so
9938          there's no point in looking at them then, either.  */
9939       {
9940         tree parm;
9941
9942         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9943           WALK_SUBTREE (TREE_VALUE (parm));
9944
9945         /* Since we've already handled the TYPE_ARG_TYPES, we don't
9946            want walk_tree walking into them itself.  */
9947         *walk_subtrees = 0;
9948       }
9949
9950       if (flag_noexcept_type)
9951         {
9952           tree spec = TYPE_RAISES_EXCEPTIONS (t);
9953           if (spec)
9954             WALK_SUBTREE (TREE_PURPOSE (spec));
9955         }
9956       break;
9957
9958     case TYPEOF_TYPE:
9959     case DECLTYPE_TYPE:
9960     case UNDERLYING_TYPE:
9961       if (pfd->include_nondeduced_p
9962           && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9963                                      pfd->visited,
9964                                      pfd->include_nondeduced_p,
9965                                      pfd->any_fn))
9966         return error_mark_node;
9967       *walk_subtrees = false;
9968       break;
9969
9970     case FUNCTION_DECL:
9971     case VAR_DECL:
9972       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9973         WALK_SUBTREE (DECL_TI_ARGS (t));
9974       /* Fall through.  */
9975
9976     case PARM_DECL:
9977     case CONST_DECL:
9978       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9979         WALK_SUBTREE (DECL_INITIAL (t));
9980       if (DECL_CONTEXT (t)
9981           && pfd->include_nondeduced_p)
9982         WALK_SUBTREE (DECL_CONTEXT (t));
9983       break;
9984
9985     case BOUND_TEMPLATE_TEMPLATE_PARM:
9986       /* Record template parameters such as `T' inside `TT<T>'.  */
9987       WALK_SUBTREE (TYPE_TI_ARGS (t));
9988       /* Fall through.  */
9989
9990     case TEMPLATE_TEMPLATE_PARM:
9991     case TEMPLATE_TYPE_PARM:
9992     case TEMPLATE_PARM_INDEX:
9993       if (fn && (*fn)(t, data))
9994         return t;
9995       else if (!fn)
9996         return t;
9997       break;
9998
9999     case TEMPLATE_DECL:
10000       /* A template template parameter is encountered.  */
10001       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10002         WALK_SUBTREE (TREE_TYPE (t));
10003
10004       /* Already substituted template template parameter */
10005       *walk_subtrees = 0;
10006       break;
10007
10008     case TYPENAME_TYPE:
10009       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10010          partial instantiation.  */
10011       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10012       break;
10013
10014     case CONSTRUCTOR:
10015       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10016           && pfd->include_nondeduced_p)
10017         WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10018       break;
10019
10020     case INDIRECT_REF:
10021     case COMPONENT_REF:
10022       /* If there's no type, then this thing must be some expression
10023          involving template parameters.  */
10024       if (!fn && !TREE_TYPE (t))
10025         return error_mark_node;
10026       break;
10027
10028     case MODOP_EXPR:
10029     case CAST_EXPR:
10030     case IMPLICIT_CONV_EXPR:
10031     case REINTERPRET_CAST_EXPR:
10032     case CONST_CAST_EXPR:
10033     case STATIC_CAST_EXPR:
10034     case DYNAMIC_CAST_EXPR:
10035     case ARROW_EXPR:
10036     case DOTSTAR_EXPR:
10037     case TYPEID_EXPR:
10038     case PSEUDO_DTOR_EXPR:
10039       if (!fn)
10040         return error_mark_node;
10041       break;
10042
10043     default:
10044       break;
10045     }
10046
10047   #undef WALK_SUBTREE
10048
10049   /* We didn't find any template parameters we liked.  */
10050  out:
10051   return result;
10052 }
10053
10054 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10055    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10056    call FN with the parameter and the DATA.
10057    If FN returns nonzero, the iteration is terminated, and
10058    for_each_template_parm returns 1.  Otherwise, the iteration
10059    continues.  If FN never returns a nonzero value, the value
10060    returned by for_each_template_parm is 0.  If FN is NULL, it is
10061    considered to be the function which always returns 1.
10062
10063    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10064    parameters that occur in non-deduced contexts.  When false, only
10065    visits those template parameters that can be deduced.  */
10066
10067 static tree
10068 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10069                         hash_set<tree> *visited,
10070                         bool include_nondeduced_p,
10071                         tree_fn_t any_fn)
10072 {
10073   struct pair_fn_data pfd;
10074   tree result;
10075
10076   /* Set up.  */
10077   pfd.fn = fn;
10078   pfd.any_fn = any_fn;
10079   pfd.data = data;
10080   pfd.include_nondeduced_p = include_nondeduced_p;
10081
10082   /* Walk the tree.  (Conceptually, we would like to walk without
10083      duplicates, but for_each_template_parm_r recursively calls
10084      for_each_template_parm, so we would need to reorganize a fair
10085      bit to use walk_tree_without_duplicates, so we keep our own
10086      visited list.)  */
10087   if (visited)
10088     pfd.visited = visited;
10089   else
10090     pfd.visited = new hash_set<tree>;
10091   result = cp_walk_tree (&t,
10092                          for_each_template_parm_r,
10093                          &pfd,
10094                          pfd.visited);
10095
10096   /* Clean up.  */
10097   if (!visited)
10098     {
10099       delete pfd.visited;
10100       pfd.visited = 0;
10101     }
10102
10103   return result;
10104 }
10105
10106 /* Returns true if T depends on any template parameter.  */
10107
10108 int
10109 uses_template_parms (tree t)
10110 {
10111   if (t == NULL_TREE)
10112     return false;
10113
10114   bool dependent_p;
10115   int saved_processing_template_decl;
10116
10117   saved_processing_template_decl = processing_template_decl;
10118   if (!saved_processing_template_decl)
10119     processing_template_decl = 1;
10120   if (TYPE_P (t))
10121     dependent_p = dependent_type_p (t);
10122   else if (TREE_CODE (t) == TREE_VEC)
10123     dependent_p = any_dependent_template_arguments_p (t);
10124   else if (TREE_CODE (t) == TREE_LIST)
10125     dependent_p = (uses_template_parms (TREE_VALUE (t))
10126                    || uses_template_parms (TREE_CHAIN (t)));
10127   else if (TREE_CODE (t) == TYPE_DECL)
10128     dependent_p = dependent_type_p (TREE_TYPE (t));
10129   else if (DECL_P (t)
10130            || EXPR_P (t)
10131            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10132            || TREE_CODE (t) == OVERLOAD
10133            || BASELINK_P (t)
10134            || identifier_p (t)
10135            || TREE_CODE (t) == TRAIT_EXPR
10136            || TREE_CODE (t) == CONSTRUCTOR
10137            || CONSTANT_CLASS_P (t))
10138     dependent_p = (type_dependent_expression_p (t)
10139                    || value_dependent_expression_p (t));
10140   else
10141     {
10142       gcc_assert (t == error_mark_node);
10143       dependent_p = false;
10144     }
10145
10146   processing_template_decl = saved_processing_template_decl;
10147
10148   return dependent_p;
10149 }
10150
10151 /* Returns true iff current_function_decl is an incompletely instantiated
10152    template.  Useful instead of processing_template_decl because the latter
10153    is set to 0 during instantiate_non_dependent_expr.  */
10154
10155 bool
10156 in_template_function (void)
10157 {
10158   tree fn = current_function_decl;
10159   bool ret;
10160   ++processing_template_decl;
10161   ret = (fn && DECL_LANG_SPECIFIC (fn)
10162          && DECL_TEMPLATE_INFO (fn)
10163          && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10164   --processing_template_decl;
10165   return ret;
10166 }
10167
10168 /* Returns true if T depends on any template parameter with level LEVEL.  */
10169
10170 bool
10171 uses_template_parms_level (tree t, int level)
10172 {
10173   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10174                                  /*include_nondeduced_p=*/true);
10175 }
10176
10177 /* Returns true if the signature of DECL depends on any template parameter from
10178    its enclosing class.  */
10179
10180 bool
10181 uses_outer_template_parms (tree decl)
10182 {
10183   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10184   if (depth == 0)
10185     return false;
10186   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10187                               &depth, NULL, /*include_nondeduced_p=*/true))
10188     return true;
10189   if (PRIMARY_TEMPLATE_P (decl)
10190       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10191                                  (DECL_TEMPLATE_PARMS (decl)),
10192                                  template_parm_outer_level,
10193                                  &depth, NULL, /*include_nondeduced_p=*/true))
10194     return true;
10195   tree ci = get_constraints (decl);
10196   if (ci)
10197     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10198   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10199                                     &depth, NULL, /*nondeduced*/true))
10200     return true;
10201   return false;
10202 }
10203
10204 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10205    ill-formed translation unit, i.e. a variable or function that isn't
10206    usable in a constant expression.  */
10207
10208 static inline bool
10209 neglectable_inst_p (tree d)
10210 {
10211   return (d && DECL_P (d)
10212           && !undeduced_auto_decl (d)
10213           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10214                : decl_maybe_constant_var_p (d)));
10215 }
10216
10217 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10218    neglectable and instantiated from within an erroneous instantiation.  */
10219
10220 static bool
10221 limit_bad_template_recursion (tree decl)
10222 {
10223   struct tinst_level *lev = current_tinst_level;
10224   int errs = errorcount + sorrycount;
10225   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10226     return false;
10227
10228   for (; lev; lev = lev->next)
10229     if (neglectable_inst_p (lev->maybe_get_node ()))
10230       break;
10231
10232   return (lev && errs > lev->errors);
10233 }
10234
10235 static int tinst_depth;
10236 extern int max_tinst_depth;
10237 int depth_reached;
10238
10239 static GTY(()) struct tinst_level *last_error_tinst_level;
10240
10241 /* We're starting to instantiate D; record the template instantiation context
10242    at LOC for diagnostics and to restore it later.  */
10243
10244 static bool
10245 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10246 {
10247   struct tinst_level *new_level;
10248
10249   if (tinst_depth >= max_tinst_depth)
10250     {
10251       /* Tell error.c not to try to instantiate any templates.  */
10252       at_eof = 2;
10253       fatal_error (input_location,
10254                    "template instantiation depth exceeds maximum of %d"
10255                    " (use %<-ftemplate-depth=%> to increase the maximum)",
10256                    max_tinst_depth);
10257       return false;
10258     }
10259
10260   /* If the current instantiation caused problems, don't let it instantiate
10261      anything else.  Do allow deduction substitution and decls usable in
10262      constant expressions.  */
10263   if (!targs && limit_bad_template_recursion (tldcl))
10264     return false;
10265
10266   /* When not -quiet, dump template instantiations other than functions, since
10267      announce_function will take care of those.  */
10268   if (!quiet_flag && !targs
10269       && TREE_CODE (tldcl) != TREE_LIST
10270       && TREE_CODE (tldcl) != FUNCTION_DECL)
10271     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10272
10273   new_level = tinst_level_freelist ().alloc ();
10274   new_level->tldcl = tldcl;
10275   new_level->targs = targs;
10276   new_level->locus = loc;
10277   new_level->errors = errorcount + sorrycount;
10278   new_level->next = NULL;
10279   new_level->refcount = 0;
10280   set_refcount_ptr (new_level->next, current_tinst_level);
10281   set_refcount_ptr (current_tinst_level, new_level);
10282
10283   ++tinst_depth;
10284   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10285     depth_reached = tinst_depth;
10286
10287   return true;
10288 }
10289
10290 /* We're starting substitution of TMPL<ARGS>; record the template
10291    substitution context for diagnostics and to restore it later.  */
10292
10293 static bool
10294 push_tinst_level (tree tmpl, tree args)
10295 {
10296   return push_tinst_level_loc (tmpl, args, input_location);
10297 }
10298
10299 /* We're starting to instantiate D; record INPUT_LOCATION and the
10300    template instantiation context for diagnostics and to restore it
10301    later.  */
10302
10303 bool
10304 push_tinst_level (tree d)
10305 {
10306   return push_tinst_level_loc (d, input_location);
10307 }
10308
10309 /* Likewise, but record LOC as the program location.  */
10310
10311 bool
10312 push_tinst_level_loc (tree d, location_t loc)
10313 {
10314   gcc_assert (TREE_CODE (d) != TREE_LIST);
10315   return push_tinst_level_loc (d, NULL, loc);
10316 }
10317
10318 /* We're done instantiating this template; return to the instantiation
10319    context.  */
10320
10321 void
10322 pop_tinst_level (void)
10323 {
10324   /* Restore the filename and line number stashed away when we started
10325      this instantiation.  */
10326   input_location = current_tinst_level->locus;
10327   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10328   --tinst_depth;
10329 }
10330
10331 /* We're instantiating a deferred template; restore the template
10332    instantiation context in which the instantiation was requested, which
10333    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10334
10335 static tree
10336 reopen_tinst_level (struct tinst_level *level)
10337 {
10338   struct tinst_level *t;
10339
10340   tinst_depth = 0;
10341   for (t = level; t; t = t->next)
10342     ++tinst_depth;
10343
10344   set_refcount_ptr (current_tinst_level, level);
10345   pop_tinst_level ();
10346   if (current_tinst_level)
10347     current_tinst_level->errors = errorcount+sorrycount;
10348   return level->maybe_get_node ();
10349 }
10350
10351 /* Returns the TINST_LEVEL which gives the original instantiation
10352    context.  */
10353
10354 struct tinst_level *
10355 outermost_tinst_level (void)
10356 {
10357   struct tinst_level *level = current_tinst_level;
10358   if (level)
10359     while (level->next)
10360       level = level->next;
10361   return level;
10362 }
10363
10364 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10365    vector of template arguments, as for tsubst.
10366
10367    Returns an appropriate tsubst'd friend declaration.  */
10368
10369 static tree
10370 tsubst_friend_function (tree decl, tree args)
10371 {
10372   tree new_friend;
10373
10374   if (TREE_CODE (decl) == FUNCTION_DECL
10375       && DECL_TEMPLATE_INSTANTIATION (decl)
10376       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10377     /* This was a friend declared with an explicit template
10378        argument list, e.g.:
10379
10380        friend void f<>(T);
10381
10382        to indicate that f was a template instantiation, not a new
10383        function declaration.  Now, we have to figure out what
10384        instantiation of what template.  */
10385     {
10386       tree template_id, arglist, fns;
10387       tree new_args;
10388       tree tmpl;
10389       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10390
10391       /* Friend functions are looked up in the containing namespace scope.
10392          We must enter that scope, to avoid finding member functions of the
10393          current class with same name.  */
10394       push_nested_namespace (ns);
10395       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10396                          tf_warning_or_error, NULL_TREE,
10397                          /*integral_constant_expression_p=*/false);
10398       pop_nested_namespace (ns);
10399       arglist = tsubst (DECL_TI_ARGS (decl), args,
10400                         tf_warning_or_error, NULL_TREE);
10401       template_id = lookup_template_function (fns, arglist);
10402
10403       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10404       tmpl = determine_specialization (template_id, new_friend,
10405                                        &new_args,
10406                                        /*need_member_template=*/0,
10407                                        TREE_VEC_LENGTH (args),
10408                                        tsk_none);
10409       return instantiate_template (tmpl, new_args, tf_error);
10410     }
10411
10412   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10413
10414   /* The NEW_FRIEND will look like an instantiation, to the
10415      compiler, but is not an instantiation from the point of view of
10416      the language.  For example, we might have had:
10417
10418      template <class T> struct S {
10419        template <class U> friend void f(T, U);
10420      };
10421
10422      Then, in S<int>, template <class U> void f(int, U) is not an
10423      instantiation of anything.  */
10424   if (new_friend == error_mark_node)
10425     return error_mark_node;
10426
10427   DECL_USE_TEMPLATE (new_friend) = 0;
10428   if (TREE_CODE (decl) == TEMPLATE_DECL)
10429     {
10430       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10431       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10432         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10433     }
10434
10435   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10436      is not a template instantiation and should not be mangled like
10437      one.  Therefore, we forget the mangling here; we'll recompute it
10438      later if we need it.  */
10439   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10440     {
10441       SET_DECL_RTL (new_friend, NULL);
10442       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10443     }
10444
10445   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10446     {
10447       tree old_decl;
10448       tree new_friend_template_info;
10449       tree new_friend_result_template_info;
10450       tree ns;
10451       int  new_friend_is_defn;
10452
10453       /* We must save some information from NEW_FRIEND before calling
10454          duplicate decls since that function will free NEW_FRIEND if
10455          possible.  */
10456       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10457       new_friend_is_defn =
10458             (DECL_INITIAL (DECL_TEMPLATE_RESULT
10459                            (template_for_substitution (new_friend)))
10460              != NULL_TREE);
10461       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10462         {
10463           /* This declaration is a `primary' template.  */
10464           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10465
10466           new_friend_result_template_info
10467             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10468         }
10469       else
10470         new_friend_result_template_info = NULL_TREE;
10471
10472       /* Inside pushdecl_namespace_level, we will push into the
10473          current namespace. However, the friend function should go
10474          into the namespace of the template.  */
10475       ns = decl_namespace_context (new_friend);
10476       push_nested_namespace (ns);
10477       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10478       pop_nested_namespace (ns);
10479
10480       if (old_decl == error_mark_node)
10481         return error_mark_node;
10482
10483       if (old_decl != new_friend)
10484         {
10485           /* This new friend declaration matched an existing
10486              declaration.  For example, given:
10487
10488                template <class T> void f(T);
10489                template <class U> class C {
10490                  template <class T> friend void f(T) {}
10491                };
10492
10493              the friend declaration actually provides the definition
10494              of `f', once C has been instantiated for some type.  So,
10495              old_decl will be the out-of-class template declaration,
10496              while new_friend is the in-class definition.
10497
10498              But, if `f' was called before this point, the
10499              instantiation of `f' will have DECL_TI_ARGS corresponding
10500              to `T' but not to `U', references to which might appear
10501              in the definition of `f'.  Previously, the most general
10502              template for an instantiation of `f' was the out-of-class
10503              version; now it is the in-class version.  Therefore, we
10504              run through all specialization of `f', adding to their
10505              DECL_TI_ARGS appropriately.  In particular, they need a
10506              new set of outer arguments, corresponding to the
10507              arguments for this class instantiation.
10508
10509              The same situation can arise with something like this:
10510
10511                friend void f(int);
10512                template <class T> class C {
10513                  friend void f(T) {}
10514                };
10515
10516              when `C<int>' is instantiated.  Now, `f(int)' is defined
10517              in the class.  */
10518
10519           if (!new_friend_is_defn)
10520             /* On the other hand, if the in-class declaration does
10521                *not* provide a definition, then we don't want to alter
10522                existing definitions.  We can just leave everything
10523                alone.  */
10524             ;
10525           else
10526             {
10527               tree new_template = TI_TEMPLATE (new_friend_template_info);
10528               tree new_args = TI_ARGS (new_friend_template_info);
10529
10530               /* Overwrite whatever template info was there before, if
10531                  any, with the new template information pertaining to
10532                  the declaration.  */
10533               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10534
10535               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10536                 {
10537                   /* We should have called reregister_specialization in
10538                      duplicate_decls.  */
10539                   gcc_assert (retrieve_specialization (new_template,
10540                                                        new_args, 0)
10541                               == old_decl);
10542
10543                   /* Instantiate it if the global has already been used.  */
10544                   if (DECL_ODR_USED (old_decl))
10545                     instantiate_decl (old_decl, /*defer_ok=*/true,
10546                                       /*expl_inst_class_mem_p=*/false);
10547                 }
10548               else
10549                 {
10550                   tree t;
10551
10552                   /* Indicate that the old function template is a partial
10553                      instantiation.  */
10554                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10555                     = new_friend_result_template_info;
10556
10557                   gcc_assert (new_template
10558                               == most_general_template (new_template));
10559                   gcc_assert (new_template != old_decl);
10560
10561                   /* Reassign any specializations already in the hash table
10562                      to the new more general template, and add the
10563                      additional template args.  */
10564                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10565                        t != NULL_TREE;
10566                        t = TREE_CHAIN (t))
10567                     {
10568                       tree spec = TREE_VALUE (t);
10569                       spec_entry elt;
10570
10571                       elt.tmpl = old_decl;
10572                       elt.args = DECL_TI_ARGS (spec);
10573                       elt.spec = NULL_TREE;
10574
10575                       decl_specializations->remove_elt (&elt);
10576
10577                       DECL_TI_ARGS (spec)
10578                         = add_outermost_template_args (new_args,
10579                                                        DECL_TI_ARGS (spec));
10580
10581                       register_specialization
10582                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
10583
10584                     }
10585                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10586                 }
10587             }
10588
10589           /* The information from NEW_FRIEND has been merged into OLD_DECL
10590              by duplicate_decls.  */
10591           new_friend = old_decl;
10592         }
10593     }
10594   else
10595     {
10596       tree context = DECL_CONTEXT (new_friend);
10597       bool dependent_p;
10598
10599       /* In the code
10600            template <class T> class C {
10601              template <class U> friend void C1<U>::f (); // case 1
10602              friend void C2<T>::f ();                    // case 2
10603            };
10604          we only need to make sure CONTEXT is a complete type for
10605          case 2.  To distinguish between the two cases, we note that
10606          CONTEXT of case 1 remains dependent type after tsubst while
10607          this isn't true for case 2.  */
10608       ++processing_template_decl;
10609       dependent_p = dependent_type_p (context);
10610       --processing_template_decl;
10611
10612       if (!dependent_p
10613           && !complete_type_or_else (context, NULL_TREE))
10614         return error_mark_node;
10615
10616       if (COMPLETE_TYPE_P (context))
10617         {
10618           tree fn = new_friend;
10619           /* do_friend adds the TEMPLATE_DECL for any member friend
10620              template even if it isn't a member template, i.e.
10621                template <class T> friend A<T>::f();
10622              Look through it in that case.  */
10623           if (TREE_CODE (fn) == TEMPLATE_DECL
10624               && !PRIMARY_TEMPLATE_P (fn))
10625             fn = DECL_TEMPLATE_RESULT (fn);
10626           /* Check to see that the declaration is really present, and,
10627              possibly obtain an improved declaration.  */
10628           fn = check_classfn (context, fn, NULL_TREE);
10629
10630           if (fn)
10631             new_friend = fn;
10632         }
10633     }
10634
10635   return new_friend;
10636 }
10637
10638 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
10639    template arguments, as for tsubst.
10640
10641    Returns an appropriate tsubst'd friend type or error_mark_node on
10642    failure.  */
10643
10644 static tree
10645 tsubst_friend_class (tree friend_tmpl, tree args)
10646 {
10647   tree tmpl;
10648
10649   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10650     {
10651       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10652       return TREE_TYPE (tmpl);
10653     }
10654
10655   tree context = CP_DECL_CONTEXT (friend_tmpl);
10656   if (TREE_CODE (context) == NAMESPACE_DECL)
10657     push_nested_namespace (context);
10658   else
10659     {
10660       context = tsubst (context, args, tf_error, NULL_TREE);
10661       push_nested_class (context);
10662     }
10663
10664   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10665                            /*non_class=*/false, /*block_p=*/false,
10666                            /*namespaces_only=*/false, LOOKUP_HIDDEN);
10667
10668   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10669     {
10670       /* The friend template has already been declared.  Just
10671          check to see that the declarations match, and install any new
10672          default parameters.  We must tsubst the default parameters,
10673          of course.  We only need the innermost template parameters
10674          because that is all that redeclare_class_template will look
10675          at.  */
10676       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10677           > TMPL_ARGS_DEPTH (args))
10678         {
10679           tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10680                                               args, tf_warning_or_error);
10681           location_t saved_input_location = input_location;
10682           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10683           tree cons = get_constraints (tmpl);
10684           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10685           input_location = saved_input_location;
10686         }
10687     }
10688   else
10689     {
10690       /* The friend template has not already been declared.  In this
10691          case, the instantiation of the template class will cause the
10692          injection of this template into the namespace scope.  */
10693       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10694
10695       if (tmpl != error_mark_node)
10696         {
10697           /* The new TMPL is not an instantiation of anything, so we
10698              forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
10699              for the new type because that is supposed to be the
10700              corresponding template decl, i.e., TMPL.  */
10701           DECL_USE_TEMPLATE (tmpl) = 0;
10702           DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10703           CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10704           CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10705             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10706
10707           /* It is hidden.  */
10708           retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10709           DECL_ANTICIPATED (tmpl)
10710             = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10711
10712           /* Inject this template into the enclosing namspace scope.  */
10713           tmpl = pushdecl_namespace_level (tmpl, true);
10714         }
10715     }
10716
10717   if (TREE_CODE (context) == NAMESPACE_DECL)
10718     pop_nested_namespace (context);
10719   else
10720     pop_nested_class ();
10721
10722   return TREE_TYPE (tmpl);
10723 }
10724
10725 /* Returns zero if TYPE cannot be completed later due to circularity.
10726    Otherwise returns one.  */
10727
10728 static int
10729 can_complete_type_without_circularity (tree type)
10730 {
10731   if (type == NULL_TREE || type == error_mark_node)
10732     return 0;
10733   else if (COMPLETE_TYPE_P (type))
10734     return 1;
10735   else if (TREE_CODE (type) == ARRAY_TYPE)
10736     return can_complete_type_without_circularity (TREE_TYPE (type));
10737   else if (CLASS_TYPE_P (type)
10738            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10739     return 0;
10740   else
10741     return 1;
10742 }
10743
10744 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10745                                 tsubst_flags_t, tree);
10746
10747 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10748    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
10749
10750 static tree
10751 tsubst_attribute (tree t, tree *decl_p, tree args,
10752                   tsubst_flags_t complain, tree in_decl)
10753 {
10754   gcc_assert (ATTR_IS_DEPENDENT (t));
10755
10756   tree val = TREE_VALUE (t);
10757   if (val == NULL_TREE)
10758     /* Nothing to do.  */;
10759   else if ((flag_openmp || flag_openmp_simd)
10760            && is_attribute_p ("omp declare simd",
10761                               get_attribute_name (t)))
10762     {
10763       tree clauses = TREE_VALUE (val);
10764       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10765                                     complain, in_decl);
10766       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10767       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10768       tree parms = DECL_ARGUMENTS (*decl_p);
10769       clauses
10770         = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10771       if (clauses)
10772         val = build_tree_list (NULL_TREE, clauses);
10773       else
10774         val = NULL_TREE;
10775     }
10776   /* If the first attribute argument is an identifier, don't
10777      pass it through tsubst.  Attributes like mode, format,
10778      cleanup and several target specific attributes expect it
10779      unmodified.  */
10780   else if (attribute_takes_identifier_p (get_attribute_name (t)))
10781     {
10782       tree chain
10783         = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10784                        /*integral_constant_expression_p=*/false);
10785       if (chain != TREE_CHAIN (val))
10786         val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10787     }
10788   else if (PACK_EXPANSION_P (val))
10789     {
10790       /* An attribute pack expansion.  */
10791       tree purp = TREE_PURPOSE (t);
10792       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10793       if (pack == error_mark_node)
10794         return error_mark_node;
10795       int len = TREE_VEC_LENGTH (pack);
10796       tree list = NULL_TREE;
10797       tree *q = &list;
10798       for (int i = 0; i < len; ++i)
10799         {
10800           tree elt = TREE_VEC_ELT (pack, i);
10801           *q = build_tree_list (purp, elt);
10802           q = &TREE_CHAIN (*q);
10803         }
10804       return list;
10805     }
10806   else
10807     val = tsubst_expr (val, args, complain, in_decl,
10808                        /*integral_constant_expression_p=*/false);
10809
10810   if (val != TREE_VALUE (t))
10811     return build_tree_list (TREE_PURPOSE (t), val);
10812   return t;
10813 }
10814
10815 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10816    unchanged or a new TREE_LIST chain.  */
10817
10818 static tree
10819 tsubst_attributes (tree attributes, tree args,
10820                    tsubst_flags_t complain, tree in_decl)
10821 {
10822   tree last_dep = NULL_TREE;
10823
10824   for (tree t = attributes; t; t = TREE_CHAIN (t))
10825     if (ATTR_IS_DEPENDENT (t))
10826       {
10827         last_dep = t;
10828         attributes = copy_list (attributes);
10829         break;
10830       }
10831
10832   if (last_dep)
10833     for (tree *p = &attributes; *p; )
10834       {
10835         tree t = *p;
10836         if (ATTR_IS_DEPENDENT (t))
10837           {
10838             tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10839             if (subst != t)
10840               {
10841                 *p = subst;
10842                 while (*p)
10843                   p = &TREE_CHAIN (*p);
10844                 *p = TREE_CHAIN (t);
10845                 continue;
10846               }
10847           }
10848         p = &TREE_CHAIN (*p);
10849       }
10850
10851   return attributes;
10852 }
10853
10854 /* Apply any attributes which had to be deferred until instantiation
10855    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10856    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
10857
10858 static void
10859 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10860                                 tree args, tsubst_flags_t complain, tree in_decl)
10861 {
10862   tree last_dep = NULL_TREE;
10863   tree t;
10864   tree *p;
10865
10866   if (attributes == NULL_TREE)
10867     return;
10868
10869   if (DECL_P (*decl_p))
10870     {
10871       if (TREE_TYPE (*decl_p) == error_mark_node)
10872         return;
10873       p = &DECL_ATTRIBUTES (*decl_p);
10874       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10875          to our attributes parameter.  */
10876       gcc_assert (*p == attributes);
10877     }
10878   else
10879     {
10880       p = &TYPE_ATTRIBUTES (*decl_p);
10881       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10882          lookup_template_class_1, and should be preserved.  */
10883       gcc_assert (*p != attributes);
10884       while (*p)
10885         p = &TREE_CHAIN (*p);
10886     }
10887
10888   for (t = attributes; t; t = TREE_CHAIN (t))
10889     if (ATTR_IS_DEPENDENT (t))
10890       {
10891         last_dep = t;
10892         attributes = copy_list (attributes);
10893         break;
10894       }
10895
10896   *p = attributes;
10897   if (last_dep)
10898     {
10899       tree late_attrs = NULL_TREE;
10900       tree *q = &late_attrs;
10901
10902       for (; *p; )
10903         {
10904           t = *p;
10905           if (ATTR_IS_DEPENDENT (t))
10906             {
10907               *p = TREE_CHAIN (t);
10908               TREE_CHAIN (t) = NULL_TREE;
10909               *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10910               while (*q)
10911                 q = &TREE_CHAIN (*q);
10912             }
10913           else
10914             p = &TREE_CHAIN (t);
10915         }
10916
10917       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10918     }
10919 }
10920
10921 /* Perform (or defer) access check for typedefs that were referenced
10922    from within the template TMPL code.
10923    This is a subroutine of instantiate_decl and instantiate_class_template.
10924    TMPL is the template to consider and TARGS is the list of arguments of
10925    that template.  */
10926
10927 static void
10928 perform_typedefs_access_check (tree tmpl, tree targs)
10929 {
10930   location_t saved_location;
10931   unsigned i;
10932   qualified_typedef_usage_t *iter;
10933
10934   if (!tmpl
10935       || (!CLASS_TYPE_P (tmpl)
10936           && TREE_CODE (tmpl) != FUNCTION_DECL))
10937     return;
10938
10939   saved_location = input_location;
10940   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10941     {
10942       tree type_decl = iter->typedef_decl;
10943       tree type_scope = iter->context;
10944
10945       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10946         continue;
10947
10948       if (uses_template_parms (type_decl))
10949         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10950       if (uses_template_parms (type_scope))
10951         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10952
10953       /* Make access check error messages point to the location
10954          of the use of the typedef.  */
10955       input_location = iter->locus;
10956       perform_or_defer_access_check (TYPE_BINFO (type_scope),
10957                                      type_decl, type_decl,
10958                                      tf_warning_or_error);
10959     }
10960     input_location = saved_location;
10961 }
10962
10963 static tree
10964 instantiate_class_template_1 (tree type)
10965 {
10966   tree templ, args, pattern, t, member;
10967   tree typedecl;
10968   tree pbinfo;
10969   tree base_list;
10970   unsigned int saved_maximum_field_alignment;
10971   tree fn_context;
10972
10973   if (type == error_mark_node)
10974     return error_mark_node;
10975
10976   if (COMPLETE_OR_OPEN_TYPE_P (type)
10977       || uses_template_parms (type))
10978     return type;
10979
10980   /* Figure out which template is being instantiated.  */
10981   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10982   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10983
10984   /* Mark the type as in the process of being defined.  */
10985   TYPE_BEING_DEFINED (type) = 1;
10986
10987   /* We may be in the middle of deferred access check.  Disable
10988      it now.  */
10989   deferring_access_check_sentinel acs (dk_no_deferred);
10990
10991   /* Determine what specialization of the original template to
10992      instantiate.  */
10993   t = most_specialized_partial_spec (type, tf_warning_or_error);
10994   if (t == error_mark_node)
10995     return error_mark_node;
10996   else if (t)
10997     {
10998       /* This TYPE is actually an instantiation of a partial
10999          specialization.  We replace the innermost set of ARGS with
11000          the arguments appropriate for substitution.  For example,
11001          given:
11002
11003            template <class T> struct S {};
11004            template <class T> struct S<T*> {};
11005
11006          and supposing that we are instantiating S<int*>, ARGS will
11007          presently be {int*} -- but we need {int}.  */
11008       pattern = TREE_TYPE (t);
11009       args = TREE_PURPOSE (t);
11010     }
11011   else
11012     {
11013       pattern = TREE_TYPE (templ);
11014       args = CLASSTYPE_TI_ARGS (type);
11015     }
11016
11017   /* If the template we're instantiating is incomplete, then clearly
11018      there's nothing we can do.  */
11019   if (!COMPLETE_TYPE_P (pattern))
11020     {
11021       /* We can try again later.  */
11022       TYPE_BEING_DEFINED (type) = 0;
11023       return type;
11024     }
11025
11026   /* If we've recursively instantiated too many templates, stop.  */
11027   if (! push_tinst_level (type))
11028     return type;
11029
11030   int saved_unevaluated_operand = cp_unevaluated_operand;
11031   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11032
11033   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11034   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11035   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11036     fn_context = error_mark_node;
11037   if (!fn_context)
11038     push_to_top_level ();
11039   else
11040     {
11041       cp_unevaluated_operand = 0;
11042       c_inhibit_evaluation_warnings = 0;
11043     }
11044   /* Use #pragma pack from the template context.  */
11045   saved_maximum_field_alignment = maximum_field_alignment;
11046   maximum_field_alignment = TYPE_PRECISION (pattern);
11047
11048   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11049
11050   /* Set the input location to the most specialized template definition.
11051      This is needed if tsubsting causes an error.  */
11052   typedecl = TYPE_MAIN_DECL (pattern);
11053   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11054     DECL_SOURCE_LOCATION (typedecl);
11055
11056   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11057   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11058   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11059   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11060   if (ANON_AGGR_TYPE_P (pattern))
11061     SET_ANON_AGGR_TYPE_P (type);
11062   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11063     {
11064       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11065       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11066       /* Adjust visibility for template arguments.  */
11067       determine_visibility (TYPE_MAIN_DECL (type));
11068     }
11069   if (CLASS_TYPE_P (type))
11070     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11071
11072   pbinfo = TYPE_BINFO (pattern);
11073
11074   /* We should never instantiate a nested class before its enclosing
11075      class; we need to look up the nested class by name before we can
11076      instantiate it, and that lookup should instantiate the enclosing
11077      class.  */
11078   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11079               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11080
11081   base_list = NULL_TREE;
11082   if (BINFO_N_BASE_BINFOS (pbinfo))
11083     {
11084       tree pbase_binfo;
11085       tree pushed_scope;
11086       int i;
11087
11088       /* We must enter the scope containing the type, as that is where
11089          the accessibility of types named in dependent bases are
11090          looked up from.  */
11091       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11092
11093       /* Substitute into each of the bases to determine the actual
11094          basetypes.  */
11095       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11096         {
11097           tree base;
11098           tree access = BINFO_BASE_ACCESS (pbinfo, i);
11099           tree expanded_bases = NULL_TREE;
11100           int idx, len = 1;
11101
11102           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11103             {
11104               expanded_bases = 
11105                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11106                                        args, tf_error, NULL_TREE);
11107               if (expanded_bases == error_mark_node)
11108                 continue;
11109
11110               len = TREE_VEC_LENGTH (expanded_bases);
11111             }
11112
11113           for (idx = 0; idx < len; idx++)
11114             {
11115               if (expanded_bases)
11116                 /* Extract the already-expanded base class.  */
11117                 base = TREE_VEC_ELT (expanded_bases, idx);
11118               else
11119                 /* Substitute to figure out the base class.  */
11120                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
11121                                NULL_TREE);
11122
11123               if (base == error_mark_node)
11124                 continue;
11125
11126               base_list = tree_cons (access, base, base_list);
11127               if (BINFO_VIRTUAL_P (pbase_binfo))
11128                 TREE_TYPE (base_list) = integer_type_node;
11129             }
11130         }
11131
11132       /* The list is now in reverse order; correct that.  */
11133       base_list = nreverse (base_list);
11134
11135       if (pushed_scope)
11136         pop_scope (pushed_scope);
11137     }
11138   /* Now call xref_basetypes to set up all the base-class
11139      information.  */
11140   xref_basetypes (type, base_list);
11141
11142   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11143                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
11144                                   args, tf_error, NULL_TREE);
11145   fixup_attribute_variants (type);
11146
11147   /* Now that our base classes are set up, enter the scope of the
11148      class, so that name lookups into base classes, etc. will work
11149      correctly.  This is precisely analogous to what we do in
11150      begin_class_definition when defining an ordinary non-template
11151      class, except we also need to push the enclosing classes.  */
11152   push_nested_class (type);
11153
11154   /* Now members are processed in the order of declaration.  */
11155   for (member = CLASSTYPE_DECL_LIST (pattern);
11156        member; member = TREE_CHAIN (member))
11157     {
11158       tree t = TREE_VALUE (member);
11159
11160       if (TREE_PURPOSE (member))
11161         {
11162           if (TYPE_P (t))
11163             {
11164               if (LAMBDA_TYPE_P (t))
11165                 /* A closure type for a lambda in an NSDMI or default argument.
11166                    Ignore it; it will be regenerated when needed.  */
11167                 continue;
11168
11169               /* Build new CLASSTYPE_NESTED_UTDS.  */
11170
11171               tree newtag;
11172               bool class_template_p;
11173
11174               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11175                                   && TYPE_LANG_SPECIFIC (t)
11176                                   && CLASSTYPE_IS_TEMPLATE (t));
11177               /* If the member is a class template, then -- even after
11178                  substitution -- there may be dependent types in the
11179                  template argument list for the class.  We increment
11180                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11181                  that function will assume that no types are dependent
11182                  when outside of a template.  */
11183               if (class_template_p)
11184                 ++processing_template_decl;
11185               newtag = tsubst (t, args, tf_error, NULL_TREE);
11186               if (class_template_p)
11187                 --processing_template_decl;
11188               if (newtag == error_mark_node)
11189                 continue;
11190
11191               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11192                 {
11193                   tree name = TYPE_IDENTIFIER (t);
11194
11195                   if (class_template_p)
11196                     /* Unfortunately, lookup_template_class sets
11197                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11198                        instantiation (i.e., for the type of a member
11199                        template class nested within a template class.)
11200                        This behavior is required for
11201                        maybe_process_partial_specialization to work
11202                        correctly, but is not accurate in this case;
11203                        the TAG is not an instantiation of anything.
11204                        (The corresponding TEMPLATE_DECL is an
11205                        instantiation, but the TYPE is not.) */
11206                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11207
11208                   /* Now, we call pushtag to put this NEWTAG into the scope of
11209                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11210                      pushtag calling push_template_decl.  We don't have to do
11211                      this for enums because it will already have been done in
11212                      tsubst_enum.  */
11213                   if (name)
11214                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11215                   pushtag (name, newtag, /*tag_scope=*/ts_current);
11216                 }
11217             }
11218           else if (DECL_DECLARES_FUNCTION_P (t))
11219             {
11220               tree r;
11221
11222               if (TREE_CODE (t) == TEMPLATE_DECL)
11223                 ++processing_template_decl;
11224               r = tsubst (t, args, tf_error, NULL_TREE);
11225               if (TREE_CODE (t) == TEMPLATE_DECL)
11226                 --processing_template_decl;
11227               set_current_access_from_decl (r);
11228               finish_member_declaration (r);
11229               /* Instantiate members marked with attribute used.  */
11230               if (r != error_mark_node && DECL_PRESERVE_P (r))
11231                 mark_used (r);
11232               if (TREE_CODE (r) == FUNCTION_DECL
11233                   && DECL_OMP_DECLARE_REDUCTION_P (r))
11234                 cp_check_omp_declare_reduction (r);
11235             }
11236           else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11237                    && LAMBDA_TYPE_P (TREE_TYPE (t)))
11238             /* A closure type for a lambda in an NSDMI or default argument.
11239                Ignore it; it will be regenerated when needed.  */;
11240           else
11241             {
11242               /* Build new TYPE_FIELDS.  */
11243               if (TREE_CODE (t) == STATIC_ASSERT)
11244                 {
11245                   tree condition;
11246
11247                   ++c_inhibit_evaluation_warnings;
11248                   condition =
11249                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11250                                  tf_warning_or_error, NULL_TREE,
11251                                  /*integral_constant_expression_p=*/true);
11252                   --c_inhibit_evaluation_warnings;
11253
11254                   finish_static_assert (condition,
11255                                         STATIC_ASSERT_MESSAGE (t), 
11256                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11257                                         /*member_p=*/true);
11258                 }
11259               else if (TREE_CODE (t) != CONST_DECL)
11260                 {
11261                   tree r;
11262                   tree vec = NULL_TREE;
11263                   int len = 1;
11264
11265                   /* The file and line for this declaration, to
11266                      assist in error message reporting.  Since we
11267                      called push_tinst_level above, we don't need to
11268                      restore these.  */
11269                   input_location = DECL_SOURCE_LOCATION (t);
11270
11271                   if (TREE_CODE (t) == TEMPLATE_DECL)
11272                     ++processing_template_decl;
11273                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11274                   if (TREE_CODE (t) == TEMPLATE_DECL)
11275                     --processing_template_decl;
11276
11277                   if (TREE_CODE (r) == TREE_VEC)
11278                     {
11279                       /* A capture pack became multiple fields.  */
11280                       vec = r;
11281                       len = TREE_VEC_LENGTH (vec);
11282                     }
11283
11284                   for (int i = 0; i < len; ++i)
11285                     {
11286                       if (vec)
11287                         r = TREE_VEC_ELT (vec, i);
11288                       if (VAR_P (r))
11289                         {
11290                           /* In [temp.inst]:
11291
11292                              [t]he initialization (and any associated
11293                              side-effects) of a static data member does
11294                              not occur unless the static data member is
11295                              itself used in a way that requires the
11296                              definition of the static data member to
11297                              exist.
11298
11299                              Therefore, we do not substitute into the
11300                              initialized for the static data member here.  */
11301                           finish_static_data_member_decl
11302                             (r,
11303                              /*init=*/NULL_TREE,
11304                              /*init_const_expr_p=*/false,
11305                              /*asmspec_tree=*/NULL_TREE,
11306                              /*flags=*/0);
11307                           /* Instantiate members marked with attribute used. */
11308                           if (r != error_mark_node && DECL_PRESERVE_P (r))
11309                             mark_used (r);
11310                         }
11311                       else if (TREE_CODE (r) == FIELD_DECL)
11312                         {
11313                           /* Determine whether R has a valid type and can be
11314                              completed later.  If R is invalid, then its type
11315                              is replaced by error_mark_node.  */
11316                           tree rtype = TREE_TYPE (r);
11317                           if (can_complete_type_without_circularity (rtype))
11318                             complete_type (rtype);
11319
11320                           if (!complete_or_array_type_p (rtype))
11321                             {
11322                               /* If R's type couldn't be completed and
11323                                  it isn't a flexible array member (whose
11324                                  type is incomplete by definition) give
11325                                  an error.  */
11326                               cxx_incomplete_type_error (r, rtype);
11327                               TREE_TYPE (r) = error_mark_node;
11328                             }
11329                           else if (TREE_CODE (rtype) == ARRAY_TYPE
11330                                    && TYPE_DOMAIN (rtype) == NULL_TREE
11331                                    && (TREE_CODE (type) == UNION_TYPE
11332                                        || TREE_CODE (type) == QUAL_UNION_TYPE))
11333                             {
11334                               error ("flexible array member %qD in union", r);
11335                               TREE_TYPE (r) = error_mark_node;
11336                             }
11337                         }
11338
11339                       /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11340                          such a thing will already have been added to the field
11341                          list by tsubst_enum in finish_member_declaration in the
11342                          CLASSTYPE_NESTED_UTDS case above.  */
11343                       if (!(TREE_CODE (r) == TYPE_DECL
11344                             && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11345                             && DECL_ARTIFICIAL (r)))
11346                         {
11347                           set_current_access_from_decl (r);
11348                           finish_member_declaration (r);
11349                         }
11350                     }
11351                 }
11352             }
11353         }
11354       else
11355         {
11356           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11357               || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11358             {
11359               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11360
11361               tree friend_type = t;
11362               bool adjust_processing_template_decl = false;
11363
11364               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11365                 {
11366                   /* template <class T> friend class C;  */
11367                   friend_type = tsubst_friend_class (friend_type, args);
11368                   adjust_processing_template_decl = true;
11369                 }
11370               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11371                 {
11372                   /* template <class T> friend class C::D;  */
11373                   friend_type = tsubst (friend_type, args,
11374                                         tf_warning_or_error, NULL_TREE);
11375                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11376                     friend_type = TREE_TYPE (friend_type);
11377                   adjust_processing_template_decl = true;
11378                 }
11379               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11380                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11381                 {
11382                   /* This could be either
11383
11384                        friend class T::C;
11385
11386                      when dependent_type_p is false or
11387
11388                        template <class U> friend class T::C;
11389
11390                      otherwise.  */
11391                   /* Bump processing_template_decl in case this is something like
11392                      template <class T> friend struct A<T>::B.  */
11393                   ++processing_template_decl;
11394                   friend_type = tsubst (friend_type, args,
11395                                         tf_warning_or_error, NULL_TREE);
11396                   if (dependent_type_p (friend_type))
11397                     adjust_processing_template_decl = true;
11398                   --processing_template_decl;
11399                 }
11400               else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11401                        && !CLASSTYPE_USE_TEMPLATE (friend_type)
11402                        && TYPE_HIDDEN_P (friend_type))
11403                 {
11404                   /* friend class C;
11405
11406                      where C hasn't been declared yet.  Let's lookup name
11407                      from namespace scope directly, bypassing any name that
11408                      come from dependent base class.  */
11409                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11410
11411                   /* The call to xref_tag_from_type does injection for friend
11412                      classes.  */
11413                   push_nested_namespace (ns);
11414                   friend_type =
11415                     xref_tag_from_type (friend_type, NULL_TREE,
11416                                         /*tag_scope=*/ts_current);
11417                   pop_nested_namespace (ns);
11418                 }
11419               else if (uses_template_parms (friend_type))
11420                 /* friend class C<T>;  */
11421                 friend_type = tsubst (friend_type, args,
11422                                       tf_warning_or_error, NULL_TREE);
11423               /* Otherwise it's
11424
11425                    friend class C;
11426
11427                  where C is already declared or
11428
11429                    friend class C<int>;
11430
11431                  We don't have to do anything in these cases.  */
11432
11433               if (adjust_processing_template_decl)
11434                 /* Trick make_friend_class into realizing that the friend
11435                    we're adding is a template, not an ordinary class.  It's
11436                    important that we use make_friend_class since it will
11437                    perform some error-checking and output cross-reference
11438                    information.  */
11439                 ++processing_template_decl;
11440
11441               if (friend_type != error_mark_node)
11442                 make_friend_class (type, friend_type, /*complain=*/false);
11443
11444               if (adjust_processing_template_decl)
11445                 --processing_template_decl;
11446             }
11447           else
11448             {
11449               /* Build new DECL_FRIENDLIST.  */
11450               tree r;
11451
11452               /* The file and line for this declaration, to
11453                  assist in error message reporting.  Since we
11454                  called push_tinst_level above, we don't need to
11455                  restore these.  */
11456               input_location = DECL_SOURCE_LOCATION (t);
11457
11458               if (TREE_CODE (t) == TEMPLATE_DECL)
11459                 {
11460                   ++processing_template_decl;
11461                   push_deferring_access_checks (dk_no_check);
11462                 }
11463
11464               r = tsubst_friend_function (t, args);
11465               add_friend (type, r, /*complain=*/false);
11466               if (TREE_CODE (t) == TEMPLATE_DECL)
11467                 {
11468                   pop_deferring_access_checks ();
11469                   --processing_template_decl;
11470                 }
11471             }
11472         }
11473     }
11474
11475   if (fn_context)
11476     {
11477       /* Restore these before substituting into the lambda capture
11478          initializers.  */
11479       cp_unevaluated_operand = saved_unevaluated_operand;
11480       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11481     }
11482
11483   /* Set the file and line number information to whatever is given for
11484      the class itself.  This puts error messages involving generated
11485      implicit functions at a predictable point, and the same point
11486      that would be used for non-template classes.  */
11487   input_location = DECL_SOURCE_LOCATION (typedecl);
11488
11489   unreverse_member_declarations (type);
11490   finish_struct_1 (type);
11491   TYPE_BEING_DEFINED (type) = 0;
11492
11493   /* We don't instantiate default arguments for member functions.  14.7.1:
11494
11495      The implicit instantiation of a class template specialization causes
11496      the implicit instantiation of the declarations, but not of the
11497      definitions or default arguments, of the class member functions,
11498      member classes, static data members and member templates....  */
11499
11500   /* Some typedefs referenced from within the template code need to be access
11501      checked at template instantiation time, i.e now. These types were
11502      added to the template at parsing time. Let's get those and perform
11503      the access checks then.  */
11504   perform_typedefs_access_check (pattern, args);
11505   perform_deferred_access_checks (tf_warning_or_error);
11506   pop_nested_class ();
11507   maximum_field_alignment = saved_maximum_field_alignment;
11508   if (!fn_context)
11509     pop_from_top_level ();
11510   pop_tinst_level ();
11511
11512   /* The vtable for a template class can be emitted in any translation
11513      unit in which the class is instantiated.  When there is no key
11514      method, however, finish_struct_1 will already have added TYPE to
11515      the keyed_classes.  */
11516   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11517     vec_safe_push (keyed_classes, type);
11518
11519   return type;
11520 }
11521
11522 /* Wrapper for instantiate_class_template_1.  */
11523
11524 tree
11525 instantiate_class_template (tree type)
11526 {
11527   tree ret;
11528   timevar_push (TV_TEMPLATE_INST);
11529   ret = instantiate_class_template_1 (type);
11530   timevar_pop (TV_TEMPLATE_INST);
11531   return ret;
11532 }
11533
11534 static tree
11535 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11536 {
11537   tree r;
11538
11539   if (!t)
11540     r = t;
11541   else if (TYPE_P (t))
11542     r = tsubst (t, args, complain, in_decl);
11543   else
11544     {
11545       if (!(complain & tf_warning))
11546         ++c_inhibit_evaluation_warnings;
11547       r = tsubst_expr (t, args, complain, in_decl,
11548                        /*integral_constant_expression_p=*/true);
11549       if (!(complain & tf_warning))
11550         --c_inhibit_evaluation_warnings;
11551     }
11552   return r;
11553 }
11554
11555 /* Given a function parameter pack TMPL_PARM and some function parameters
11556    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11557    and set *SPEC_P to point at the next point in the list.  */
11558
11559 tree
11560 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11561 {
11562   /* Collect all of the extra "packed" parameters into an
11563      argument pack.  */
11564   tree parmvec;
11565   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11566   tree spec_parm = *spec_p;
11567   int i, len;
11568
11569   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11570     if (tmpl_parm
11571         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11572       break;
11573
11574   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
11575   parmvec = make_tree_vec (len);
11576   spec_parm = *spec_p;
11577   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11578     {
11579       tree elt = spec_parm;
11580       if (DECL_PACK_P (elt))
11581         elt = make_pack_expansion (elt);
11582       TREE_VEC_ELT (parmvec, i) = elt;
11583     }
11584
11585   /* Build the argument packs.  */
11586   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11587   *spec_p = spec_parm;
11588
11589   return argpack;
11590 }
11591
11592 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11593    NONTYPE_ARGUMENT_PACK.  */
11594
11595 static tree
11596 make_fnparm_pack (tree spec_parm)
11597 {
11598   return extract_fnparm_pack (NULL_TREE, &spec_parm);
11599 }
11600
11601 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11602    pack expansion with no extra args, 2 if it has extra args, or 0
11603    if it is not a pack expansion.  */
11604
11605 static int
11606 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11607 {
11608   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
11609     /* We're being called before this happens in tsubst_pack_expansion.  */
11610     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
11611   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11612   if (i >= TREE_VEC_LENGTH (vec))
11613     return 0;
11614   tree elt = TREE_VEC_ELT (vec, i);
11615   if (DECL_P (elt))
11616     /* A decl pack is itself an expansion.  */
11617     elt = TREE_TYPE (elt);
11618   if (!PACK_EXPANSION_P (elt))
11619     return 0;
11620   if (PACK_EXPANSION_EXTRA_ARGS (elt))
11621     return 2;
11622   return 1;
11623 }
11624
11625
11626 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
11627
11628 static tree
11629 make_argument_pack_select (tree arg_pack, unsigned index)
11630 {
11631   tree aps = make_node (ARGUMENT_PACK_SELECT);
11632
11633   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11634   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11635
11636   return aps;
11637 }
11638
11639 /*  This is a subroutine of tsubst_pack_expansion.
11640
11641     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11642     mechanism to store the (non complete list of) arguments of the
11643     substitution and return a non substituted pack expansion, in order
11644     to wait for when we have enough arguments to really perform the
11645     substitution.  */
11646
11647 static bool
11648 use_pack_expansion_extra_args_p (tree parm_packs,
11649                                  int arg_pack_len,
11650                                  bool has_empty_arg)
11651 {
11652   /* If one pack has an expansion and another pack has a normal
11653      argument or if one pack has an empty argument and an another
11654      one hasn't then tsubst_pack_expansion cannot perform the
11655      substitution and need to fall back on the
11656      PACK_EXPANSION_EXTRA mechanism.  */
11657   if (parm_packs == NULL_TREE)
11658     return false;
11659   else if (has_empty_arg)
11660     return true;
11661
11662   bool has_expansion_arg = false;
11663   for (int i = 0 ; i < arg_pack_len; ++i)
11664     {
11665       bool has_non_expansion_arg = false;
11666       for (tree parm_pack = parm_packs;
11667            parm_pack;
11668            parm_pack = TREE_CHAIN (parm_pack))
11669         {
11670           tree arg = TREE_VALUE (parm_pack);
11671
11672           int exp = argument_pack_element_is_expansion_p (arg, i);
11673           if (exp == 2)
11674             /* We can't substitute a pack expansion with extra args into
11675                our pattern.  */
11676             return true;
11677           else if (exp)
11678             has_expansion_arg = true;
11679           else
11680             has_non_expansion_arg = true;
11681         }
11682
11683       if (has_expansion_arg && has_non_expansion_arg)
11684         return true;
11685     }
11686   return false;
11687 }
11688
11689 /* [temp.variadic]/6 says that:
11690
11691        The instantiation of a pack expansion [...]
11692        produces a list E1,E2, ..., En, where N is the number of elements
11693        in the pack expansion parameters.
11694
11695    This subroutine of tsubst_pack_expansion produces one of these Ei.
11696
11697    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
11698    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11699    PATTERN, and each TREE_VALUE is its corresponding argument pack.
11700    INDEX is the index 'i' of the element Ei to produce.  ARGS,
11701    COMPLAIN, and IN_DECL are the same parameters as for the
11702    tsubst_pack_expansion function.
11703
11704    The function returns the resulting Ei upon successful completion,
11705    or error_mark_node.
11706
11707    Note that this function possibly modifies the ARGS parameter, so
11708    it's the responsibility of the caller to restore it.  */
11709
11710 static tree
11711 gen_elem_of_pack_expansion_instantiation (tree pattern,
11712                                           tree parm_packs,
11713                                           unsigned index,
11714                                           tree args /* This parm gets
11715                                                        modified.  */,
11716                                           tsubst_flags_t complain,
11717                                           tree in_decl)
11718 {
11719   tree t;
11720   bool ith_elem_is_expansion = false;
11721
11722   /* For each parameter pack, change the substitution of the parameter
11723      pack to the ith argument in its argument pack, then expand the
11724      pattern.  */
11725   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11726     {
11727       tree parm = TREE_PURPOSE (pack);
11728       tree arg_pack = TREE_VALUE (pack);
11729       tree aps;                 /* instance of ARGUMENT_PACK_SELECT.  */
11730
11731       ith_elem_is_expansion |=
11732         argument_pack_element_is_expansion_p (arg_pack, index);
11733
11734       /* Select the Ith argument from the pack.  */
11735       if (TREE_CODE (parm) == PARM_DECL
11736           || VAR_P (parm)
11737           || TREE_CODE (parm) == FIELD_DECL)
11738         {
11739           if (index == 0)
11740             {
11741               aps = make_argument_pack_select (arg_pack, index);
11742               if (!mark_used (parm, complain) && !(complain & tf_error))
11743                 return error_mark_node;
11744               register_local_specialization (aps, parm);
11745             }
11746           else
11747             aps = retrieve_local_specialization (parm);
11748         }
11749       else
11750         {
11751           int idx, level;
11752           template_parm_level_and_index (parm, &level, &idx);
11753
11754           if (index == 0)
11755             {
11756               aps = make_argument_pack_select (arg_pack, index);
11757               /* Update the corresponding argument.  */
11758               TMPL_ARG (args, level, idx) = aps;
11759             }
11760           else
11761             /* Re-use the ARGUMENT_PACK_SELECT.  */
11762             aps = TMPL_ARG (args, level, idx);
11763         }
11764       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11765     }
11766
11767   /* Substitute into the PATTERN with the (possibly altered)
11768      arguments.  */
11769   if (pattern == in_decl)
11770     /* Expanding a fixed parameter pack from
11771        coerce_template_parameter_pack.  */
11772     t = tsubst_decl (pattern, args, complain);
11773   else if (pattern == error_mark_node)
11774     t = error_mark_node;
11775   else if (constraint_p (pattern))
11776     {
11777       if (processing_template_decl)
11778         t = tsubst_constraint (pattern, args, complain, in_decl);
11779       else
11780         t = (constraints_satisfied_p (pattern, args)
11781              ? boolean_true_node : boolean_false_node);
11782     }
11783   else if (!TYPE_P (pattern))
11784     t = tsubst_expr (pattern, args, complain, in_decl,
11785                      /*integral_constant_expression_p=*/false);
11786   else
11787     t = tsubst (pattern, args, complain, in_decl);
11788
11789   /*  If the Ith argument pack element is a pack expansion, then
11790       the Ith element resulting from the substituting is going to
11791       be a pack expansion as well.  */
11792   if (ith_elem_is_expansion)
11793     t = make_pack_expansion (t, complain);
11794
11795   return t;
11796 }
11797
11798 /* When the unexpanded parameter pack in a fold expression expands to an empty
11799    sequence, the value of the expression is as follows; the program is
11800    ill-formed if the operator is not listed in this table.
11801
11802    &&   true
11803    ||   false
11804    ,    void()  */
11805
11806 tree
11807 expand_empty_fold (tree t, tsubst_flags_t complain)
11808 {
11809   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11810   if (!FOLD_EXPR_MODIFY_P (t))
11811     switch (code)
11812       {
11813       case TRUTH_ANDIF_EXPR:
11814         return boolean_true_node;
11815       case TRUTH_ORIF_EXPR:
11816         return boolean_false_node;
11817       case COMPOUND_EXPR:
11818         return void_node;
11819       default:
11820         break;
11821       }
11822
11823   if (complain & tf_error)
11824     error_at (location_of (t),
11825               "fold of empty expansion over %O", code);
11826   return error_mark_node;
11827 }
11828
11829 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11830    form an expression that combines the two terms using the
11831    operator of T. */
11832
11833 static tree
11834 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11835 {
11836   tree op = FOLD_EXPR_OP (t);
11837   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11838
11839   // Handle compound assignment operators.
11840   if (FOLD_EXPR_MODIFY_P (t))
11841     return build_x_modify_expr (input_location, left, code, right, complain);
11842
11843   switch (code)
11844     {
11845     case COMPOUND_EXPR:
11846       return build_x_compound_expr (input_location, left, right, complain);
11847     default:
11848       return build_x_binary_op (input_location, code,
11849                                 left, TREE_CODE (left),
11850                                 right, TREE_CODE (right),
11851                                 /*overload=*/NULL,
11852                                 complain);
11853     }
11854 }
11855
11856 /* Substitute ARGS into the pack of a fold expression T. */
11857
11858 static inline tree
11859 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11860 {
11861   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11862 }
11863
11864 /* Substitute ARGS into the pack of a fold expression T. */
11865
11866 static inline tree
11867 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11868 {
11869   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11870 }
11871
11872 /* Expand a PACK of arguments into a grouped as left fold.
11873    Given a pack containing elements A0, A1, ..., An and an
11874    operator @, this builds the expression:
11875
11876       ((A0 @ A1) @ A2) ... @ An
11877
11878    Note that PACK must not be empty.
11879
11880    The operator is defined by the original fold expression T. */
11881
11882 static tree
11883 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11884 {
11885   tree left = TREE_VEC_ELT (pack, 0);
11886   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11887     {
11888       tree right = TREE_VEC_ELT (pack, i);
11889       left = fold_expression (t, left, right, complain);
11890     }
11891   return left;
11892 }
11893
11894 /* Substitute into a unary left fold expression. */
11895
11896 static tree
11897 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11898                         tree in_decl)
11899 {
11900   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11901   if (pack == error_mark_node)
11902     return error_mark_node;
11903   if (PACK_EXPANSION_P (pack))
11904     {
11905       tree r = copy_node (t);
11906       FOLD_EXPR_PACK (r) = pack;
11907       return r;
11908     }
11909   if (TREE_VEC_LENGTH (pack) == 0)
11910     return expand_empty_fold (t, complain);
11911   else
11912     return expand_left_fold (t, pack, complain);
11913 }
11914
11915 /* Substitute into a binary left fold expression.
11916
11917    Do ths by building a single (non-empty) vector of argumnts and
11918    building the expression from those elements. */
11919
11920 static tree
11921 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11922                          tree in_decl)
11923 {
11924   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11925   if (pack == error_mark_node)
11926     return error_mark_node;
11927   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11928   if (init == error_mark_node)
11929     return error_mark_node;
11930
11931   if (PACK_EXPANSION_P (pack))
11932     {
11933       tree r = copy_node (t);
11934       FOLD_EXPR_PACK (r) = pack;
11935       FOLD_EXPR_INIT (r) = init;
11936       return r;
11937     }
11938
11939   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11940   TREE_VEC_ELT (vec, 0) = init;
11941   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11942     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11943
11944   return expand_left_fold (t, vec, complain);
11945 }
11946
11947 /* Expand a PACK of arguments into a grouped as right fold.
11948    Given a pack containing elementns A0, A1, ..., and an
11949    operator @, this builds the expression:
11950
11951       A0@ ... (An-2 @ (An-1 @ An))
11952
11953    Note that PACK must not be empty.
11954
11955    The operator is defined by the original fold expression T. */
11956
11957 tree
11958 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11959 {
11960   // Build the expression.
11961   int n = TREE_VEC_LENGTH (pack);
11962   tree right = TREE_VEC_ELT (pack, n - 1);
11963   for (--n; n != 0; --n)
11964     {
11965       tree left = TREE_VEC_ELT (pack, n - 1);
11966       right = fold_expression (t, left, right, complain);
11967     }
11968   return right;
11969 }
11970
11971 /* Substitute into a unary right fold expression. */
11972
11973 static tree
11974 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11975                          tree in_decl)
11976 {
11977   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11978   if (pack == error_mark_node)
11979     return error_mark_node;
11980   if (PACK_EXPANSION_P (pack))
11981     {
11982       tree r = copy_node (t);
11983       FOLD_EXPR_PACK (r) = pack;
11984       return r;
11985     }
11986   if (TREE_VEC_LENGTH (pack) == 0)
11987     return expand_empty_fold (t, complain);
11988   else
11989     return expand_right_fold (t, pack, complain);
11990 }
11991
11992 /* Substitute into a binary right fold expression.
11993
11994    Do ths by building a single (non-empty) vector of arguments and
11995    building the expression from those elements. */
11996
11997 static tree
11998 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11999                          tree in_decl)
12000 {
12001   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12002   if (pack == error_mark_node)
12003     return error_mark_node;
12004   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12005   if (init == error_mark_node)
12006     return error_mark_node;
12007
12008   if (PACK_EXPANSION_P (pack))
12009     {
12010       tree r = copy_node (t);
12011       FOLD_EXPR_PACK (r) = pack;
12012       FOLD_EXPR_INIT (r) = init;
12013       return r;
12014     }
12015
12016   int n = TREE_VEC_LENGTH (pack);
12017   tree vec = make_tree_vec (n + 1);
12018   for (int i = 0; i < n; ++i)
12019     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12020   TREE_VEC_ELT (vec, n) = init;
12021
12022   return expand_right_fold (t, vec, complain);
12023 }
12024
12025 /* Walk through the pattern of a pack expansion, adding everything in
12026    local_specializations to a list.  */
12027
12028 class el_data
12029 {
12030 public:
12031   hash_set<tree> internal;
12032   tree extra;
12033   tsubst_flags_t complain;
12034
12035   el_data (tsubst_flags_t c)
12036     : extra (NULL_TREE), complain (c) {}
12037 };
12038 static tree
12039 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12040 {
12041   el_data &data = *reinterpret_cast<el_data*>(data_);
12042   tree *extra = &data.extra;
12043   tsubst_flags_t complain = data.complain;
12044
12045   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12046     /* Remember local typedefs (85214).  */
12047     tp = &TYPE_NAME (*tp);
12048
12049   if (TREE_CODE (*tp) == DECL_EXPR)
12050     data.internal.add (DECL_EXPR_DECL (*tp));
12051   else if (tree spec = retrieve_local_specialization (*tp))
12052     {
12053       if (data.internal.contains (*tp))
12054         /* Don't mess with variables declared within the pattern.  */
12055         return NULL_TREE;
12056       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12057         {
12058           /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12059           tree args = ARGUMENT_PACK_ARGS (spec);
12060           if (TREE_VEC_LENGTH (args) == 1)
12061             {
12062               tree elt = TREE_VEC_ELT (args, 0);
12063               if (PACK_EXPANSION_P (elt))
12064                 elt = PACK_EXPANSION_PATTERN (elt);
12065               if (DECL_PACK_P (elt))
12066                 spec = elt;
12067             }
12068           if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12069             {
12070               /* Handle lambda capture here, since we aren't doing any
12071                  substitution now, and so tsubst_copy won't call
12072                  process_outer_var_ref.  */
12073               tree args = ARGUMENT_PACK_ARGS (spec);
12074               int len = TREE_VEC_LENGTH (args);
12075               for (int i = 0; i < len; ++i)
12076                 {
12077                   tree arg = TREE_VEC_ELT (args, i);
12078                   tree carg = arg;
12079                   if (outer_automatic_var_p (arg))
12080                     carg = process_outer_var_ref (arg, complain);
12081                   if (carg != arg)
12082                     {
12083                       /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12084                          proxies.  */
12085                       if (i == 0)
12086                         {
12087                           spec = copy_node (spec);
12088                           args = copy_node (args);
12089                           SET_ARGUMENT_PACK_ARGS (spec, args);
12090                           register_local_specialization (spec, *tp);
12091                         }
12092                       TREE_VEC_ELT (args, i) = carg;
12093                     }
12094                 }
12095             }
12096         }
12097       if (outer_automatic_var_p (spec))
12098         spec = process_outer_var_ref (spec, complain);
12099       *extra = tree_cons (*tp, spec, *extra);
12100     }
12101   return NULL_TREE;
12102 }
12103 static tree
12104 extract_local_specs (tree pattern, tsubst_flags_t complain)
12105 {
12106   el_data data (complain);
12107   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
12108   return data.extra;
12109 }
12110
12111 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12112    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12113
12114 tree
12115 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12116 {
12117   tree extra = args;
12118   if (local_specializations)
12119     if (tree locals = extract_local_specs (pattern, complain))
12120       extra = tree_cons (NULL_TREE, extra, locals);
12121   return extra;
12122 }
12123
12124 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12125    normal template args to ARGS.  */
12126
12127 tree
12128 add_extra_args (tree extra, tree args)
12129 {
12130   if (extra && TREE_CODE (extra) == TREE_LIST)
12131     {
12132       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12133         {
12134           /* The partial instantiation involved local declarations collected in
12135              extract_local_specs; map from the general template to our local
12136              context.  */
12137           tree gen = TREE_PURPOSE (elt);
12138           tree inst = TREE_VALUE (elt);
12139           if (DECL_P (inst))
12140             if (tree local = retrieve_local_specialization (inst))
12141               inst = local;
12142           /* else inst is already a full instantiation of the pack.  */
12143           register_local_specialization (inst, gen);
12144         }
12145       gcc_assert (!TREE_PURPOSE (extra));
12146       extra = TREE_VALUE (extra);
12147     }
12148   return add_to_template_args (extra, args);
12149 }
12150
12151 /* Substitute ARGS into T, which is an pack expansion
12152    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12153    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12154    (if only a partial substitution could be performed) or
12155    ERROR_MARK_NODE if there was an error.  */
12156 tree
12157 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12158                        tree in_decl)
12159 {
12160   tree pattern;
12161   tree pack, packs = NULL_TREE;
12162   bool unsubstituted_packs = false;
12163   bool unsubstituted_fn_pack = false;
12164   int i, len = -1;
12165   tree result;
12166   hash_map<tree, tree> *saved_local_specializations = NULL;
12167   bool need_local_specializations = false;
12168   int levels;
12169
12170   gcc_assert (PACK_EXPANSION_P (t));
12171   pattern = PACK_EXPANSION_PATTERN (t);
12172
12173   /* Add in any args remembered from an earlier partial instantiation.  */
12174   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12175
12176   levels = TMPL_ARGS_DEPTH (args);
12177
12178   /* Determine the argument packs that will instantiate the parameter
12179      packs used in the expansion expression. While we're at it,
12180      compute the number of arguments to be expanded and make sure it
12181      is consistent.  */
12182   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12183        pack = TREE_CHAIN (pack))
12184     {
12185       tree parm_pack = TREE_VALUE (pack);
12186       tree arg_pack = NULL_TREE;
12187       tree orig_arg = NULL_TREE;
12188       int level = 0;
12189
12190       if (TREE_CODE (parm_pack) == BASES)
12191         {
12192           gcc_assert (parm_pack == pattern);
12193           if (BASES_DIRECT (parm_pack))
12194             return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12195                                                         args, complain,
12196                                                         in_decl, false),
12197                                            complain);
12198           else
12199             return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12200                                                  args, complain, in_decl,
12201                                                  false), complain);
12202         }
12203       else if (builtin_pack_call_p (parm_pack))
12204         {
12205           if (parm_pack != pattern)
12206             {
12207               if (complain & tf_error)
12208                 sorry ("%qE is not the entire pattern of the pack expansion",
12209                        parm_pack);
12210               return error_mark_node;
12211             }
12212           return expand_builtin_pack_call (parm_pack, args,
12213                                            complain, in_decl);
12214         }
12215       else if (TREE_CODE (parm_pack) == PARM_DECL)
12216         {
12217           /* We know we have correct local_specializations if this
12218              expansion is at function scope, or if we're dealing with a
12219              local parameter in a requires expression; for the latter,
12220              tsubst_requires_expr set it up appropriately.  */
12221           if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12222             arg_pack = retrieve_local_specialization (parm_pack);
12223           else
12224             /* We can't rely on local_specializations for a parameter
12225                name used later in a function declaration (such as in a
12226                late-specified return type).  Even if it exists, it might
12227                have the wrong value for a recursive call.  */
12228             need_local_specializations = true;
12229
12230           if (!arg_pack)
12231             {
12232               /* This parameter pack was used in an unevaluated context.  Just
12233                  make a dummy decl, since it's only used for its type.  */
12234               ++cp_unevaluated_operand;
12235               arg_pack = tsubst_decl (parm_pack, args, complain);
12236               --cp_unevaluated_operand;
12237               if (arg_pack && DECL_PACK_P (arg_pack))
12238                 /* Partial instantiation of the parm_pack, we can't build
12239                    up an argument pack yet.  */
12240                 arg_pack = NULL_TREE;
12241               else
12242                 arg_pack = make_fnparm_pack (arg_pack);
12243             }
12244           else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12245             /* This argument pack isn't fully instantiated yet.  We set this
12246                flag rather than clear arg_pack because we do want to do the
12247                optimization below, and we don't want to substitute directly
12248                into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12249                where it isn't expected).  */
12250             unsubstituted_fn_pack = true;
12251         }
12252       else if (is_capture_proxy (parm_pack))
12253         {
12254           arg_pack = retrieve_local_specialization (parm_pack);
12255           if (argument_pack_element_is_expansion_p (arg_pack, 0))
12256             unsubstituted_fn_pack = true;
12257         }
12258       else
12259         {
12260           int idx;
12261           template_parm_level_and_index (parm_pack, &level, &idx);
12262
12263           if (level <= levels)
12264             arg_pack = TMPL_ARG (args, level, idx);
12265         }
12266
12267       orig_arg = arg_pack;
12268       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12269         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12270
12271       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12272         /* This can only happen if we forget to expand an argument
12273            pack somewhere else. Just return an error, silently.  */
12274         {
12275           result = make_tree_vec (1);
12276           TREE_VEC_ELT (result, 0) = error_mark_node;
12277           return result;
12278         }
12279
12280       if (arg_pack)
12281         {
12282           int my_len = 
12283             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12284
12285           /* Don't bother trying to do a partial substitution with
12286              incomplete packs; we'll try again after deduction.  */
12287           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12288             return t;
12289
12290           if (len < 0)
12291             len = my_len;
12292           else if (len != my_len
12293                    && !unsubstituted_fn_pack)
12294             {
12295               if (!(complain & tf_error))
12296                 /* Fail quietly.  */;
12297               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12298                 error ("mismatched argument pack lengths while expanding %qT",
12299                        pattern);
12300               else
12301                 error ("mismatched argument pack lengths while expanding %qE",
12302                        pattern);
12303               return error_mark_node;
12304             }
12305
12306           /* Keep track of the parameter packs and their corresponding
12307              argument packs.  */
12308           packs = tree_cons (parm_pack, arg_pack, packs);
12309           TREE_TYPE (packs) = orig_arg;
12310         }
12311       else
12312         {
12313           /* We can't substitute for this parameter pack.  We use a flag as
12314              well as the missing_level counter because function parameter
12315              packs don't have a level.  */
12316           gcc_assert (processing_template_decl || is_auto (parm_pack));
12317           unsubstituted_packs = true;
12318         }
12319     }
12320
12321   /* If the expansion is just T..., return the matching argument pack, unless
12322      we need to call convert_from_reference on all the elements.  This is an
12323      important optimization; see c++/68422.  */
12324   if (!unsubstituted_packs
12325       && TREE_PURPOSE (packs) == pattern)
12326     {
12327       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12328
12329       /* If the argument pack is a single pack expansion, pull it out.  */
12330       if (TREE_VEC_LENGTH (args) == 1
12331           && pack_expansion_args_count (args))
12332         return TREE_VEC_ELT (args, 0);
12333
12334       /* Types need no adjustment, nor does sizeof..., and if we still have
12335          some pack expansion args we won't do anything yet.  */
12336       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12337           || PACK_EXPANSION_SIZEOF_P (t)
12338           || pack_expansion_args_count (args))
12339         return args;
12340       /* Also optimize expression pack expansions if we can tell that the
12341          elements won't have reference type.  */
12342       tree type = TREE_TYPE (pattern);
12343       if (type && !TYPE_REF_P (type)
12344           && !PACK_EXPANSION_P (type)
12345           && !WILDCARD_TYPE_P (type))
12346         return args;
12347       /* Otherwise use the normal path so we get convert_from_reference.  */
12348     }
12349
12350   /* We cannot expand this expansion expression, because we don't have
12351      all of the argument packs we need.  */
12352   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12353     {
12354       /* We got some full packs, but we can't substitute them in until we
12355          have values for all the packs.  So remember these until then.  */
12356
12357       t = make_pack_expansion (pattern, complain);
12358       PACK_EXPANSION_EXTRA_ARGS (t)
12359         = build_extra_args (pattern, args, complain);
12360       return t;
12361     }
12362   else if (unsubstituted_packs)
12363     {
12364       /* There were no real arguments, we're just replacing a parameter
12365          pack with another version of itself. Substitute into the
12366          pattern and return a PACK_EXPANSION_*. The caller will need to
12367          deal with that.  */
12368       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12369         t = tsubst_expr (pattern, args, complain, in_decl,
12370                          /*integral_constant_expression_p=*/false);
12371       else
12372         t = tsubst (pattern, args, complain, in_decl);
12373       t = make_pack_expansion (t, complain);
12374       return t;
12375     }
12376
12377   gcc_assert (len >= 0);
12378
12379   if (need_local_specializations)
12380     {
12381       /* We're in a late-specified return type, so create our own local
12382          specializations map; the current map is either NULL or (in the
12383          case of recursive unification) might have bindings that we don't
12384          want to use or alter.  */
12385       saved_local_specializations = local_specializations;
12386       local_specializations = new hash_map<tree, tree>;
12387     }
12388
12389   /* For each argument in each argument pack, substitute into the
12390      pattern.  */
12391   result = make_tree_vec (len);
12392   tree elem_args = copy_template_args (args);
12393   for (i = 0; i < len; ++i)
12394     {
12395       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12396                                                     i,
12397                                                     elem_args, complain,
12398                                                     in_decl);
12399       TREE_VEC_ELT (result, i) = t;
12400       if (t == error_mark_node)
12401         {
12402           result = error_mark_node;
12403           break;
12404         }
12405     }
12406
12407   /* Update ARGS to restore the substitution from parameter packs to
12408      their argument packs.  */
12409   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12410     {
12411       tree parm = TREE_PURPOSE (pack);
12412
12413       if (TREE_CODE (parm) == PARM_DECL
12414           || VAR_P (parm)
12415           || TREE_CODE (parm) == FIELD_DECL)
12416         register_local_specialization (TREE_TYPE (pack), parm);
12417       else
12418         {
12419           int idx, level;
12420
12421           if (TREE_VALUE (pack) == NULL_TREE)
12422             continue;
12423
12424           template_parm_level_and_index (parm, &level, &idx);
12425
12426           /* Update the corresponding argument.  */
12427           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12428             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12429               TREE_TYPE (pack);
12430           else
12431             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12432         }
12433     }
12434
12435   if (need_local_specializations)
12436     {
12437       delete local_specializations;
12438       local_specializations = saved_local_specializations;
12439     }
12440
12441   /* If the dependent pack arguments were such that we end up with only a
12442      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
12443   if (len == 1 && TREE_CODE (result) == TREE_VEC
12444       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12445     return TREE_VEC_ELT (result, 0);
12446
12447   return result;
12448 }
12449
12450 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12451    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
12452    parameter packs; all parms generated from a function parameter pack will
12453    have the same DECL_PARM_INDEX.  */
12454
12455 tree
12456 get_pattern_parm (tree parm, tree tmpl)
12457 {
12458   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12459   tree patparm;
12460
12461   if (DECL_ARTIFICIAL (parm))
12462     {
12463       for (patparm = DECL_ARGUMENTS (pattern);
12464            patparm; patparm = DECL_CHAIN (patparm))
12465         if (DECL_ARTIFICIAL (patparm)
12466             && DECL_NAME (parm) == DECL_NAME (patparm))
12467           break;
12468     }
12469   else
12470     {
12471       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12472       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12473       gcc_assert (DECL_PARM_INDEX (patparm)
12474                   == DECL_PARM_INDEX (parm));
12475     }
12476
12477   return patparm;
12478 }
12479
12480 /* Make an argument pack out of the TREE_VEC VEC.  */
12481
12482 static tree
12483 make_argument_pack (tree vec)
12484 {
12485   tree pack;
12486   tree elt = TREE_VEC_ELT (vec, 0);
12487   if (TYPE_P (elt))
12488     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12489   else
12490     {
12491       pack = make_node (NONTYPE_ARGUMENT_PACK);
12492       TREE_CONSTANT (pack) = 1;
12493     }
12494   SET_ARGUMENT_PACK_ARGS (pack, vec);
12495   return pack;
12496 }
12497
12498 /* Return an exact copy of template args T that can be modified
12499    independently.  */
12500
12501 static tree
12502 copy_template_args (tree t)
12503 {
12504   if (t == error_mark_node)
12505     return t;
12506
12507   int len = TREE_VEC_LENGTH (t);
12508   tree new_vec = make_tree_vec (len);
12509
12510   for (int i = 0; i < len; ++i)
12511     {
12512       tree elt = TREE_VEC_ELT (t, i);
12513       if (elt && TREE_CODE (elt) == TREE_VEC)
12514         elt = copy_template_args (elt);
12515       TREE_VEC_ELT (new_vec, i) = elt;
12516     }
12517
12518   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12519     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12520
12521   return new_vec;
12522 }
12523
12524 /* Substitute ARGS into the vector or list of template arguments T.  */
12525
12526 static tree
12527 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12528 {
12529   tree orig_t = t;
12530   int len, need_new = 0, i, expanded_len_adjust = 0, out;
12531   tree *elts;
12532
12533   if (t == error_mark_node)
12534     return error_mark_node;
12535
12536   len = TREE_VEC_LENGTH (t);
12537   elts = XALLOCAVEC (tree, len);
12538
12539   for (i = 0; i < len; i++)
12540     {
12541       tree orig_arg = TREE_VEC_ELT (t, i);
12542       tree new_arg;
12543
12544       if (TREE_CODE (orig_arg) == TREE_VEC)
12545         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12546       else if (PACK_EXPANSION_P (orig_arg))
12547         {
12548           /* Substitute into an expansion expression.  */
12549           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12550
12551           if (TREE_CODE (new_arg) == TREE_VEC)
12552             /* Add to the expanded length adjustment the number of
12553                expanded arguments. We subtract one from this
12554                measurement, because the argument pack expression
12555                itself is already counted as 1 in
12556                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12557                the argument pack is empty.  */
12558             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12559         }
12560       else if (ARGUMENT_PACK_P (orig_arg))
12561         {
12562           /* Substitute into each of the arguments.  */
12563           new_arg = TYPE_P (orig_arg)
12564             ? cxx_make_type (TREE_CODE (orig_arg))
12565             : make_node (TREE_CODE (orig_arg));
12566
12567           tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12568                                                  args, complain, in_decl);
12569           if (pack_args == error_mark_node)
12570             new_arg = error_mark_node;
12571           else
12572             SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12573
12574           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12575             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12576         }
12577       else
12578         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12579
12580       if (new_arg == error_mark_node)
12581         return error_mark_node;
12582
12583       elts[i] = new_arg;
12584       if (new_arg != orig_arg)
12585         need_new = 1;
12586     }
12587
12588   if (!need_new)
12589     return t;
12590
12591   /* Make space for the expanded arguments coming from template
12592      argument packs.  */
12593   t = make_tree_vec (len + expanded_len_adjust);
12594   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12595      arguments for a member template.
12596      In that case each TREE_VEC in ORIG_T represents a level of template
12597      arguments, and ORIG_T won't carry any non defaulted argument count.
12598      It will rather be the nested TREE_VECs that will carry one.
12599      In other words, ORIG_T carries a non defaulted argument count only
12600      if it doesn't contain any nested TREE_VEC.  */
12601   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12602     {
12603       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12604       count += expanded_len_adjust;
12605       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12606     }
12607   for (i = 0, out = 0; i < len; i++)
12608     {
12609       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12610            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12611           && TREE_CODE (elts[i]) == TREE_VEC)
12612         {
12613           int idx;
12614
12615           /* Now expand the template argument pack "in place".  */
12616           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12617             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12618         }
12619       else
12620         {
12621           TREE_VEC_ELT (t, out) = elts[i];
12622           out++;
12623         }
12624     }
12625
12626   return t;
12627 }
12628
12629 /* Substitute ARGS into one level PARMS of template parameters.  */
12630
12631 static tree
12632 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12633 {
12634   if (parms == error_mark_node)
12635     return error_mark_node;
12636
12637   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12638
12639   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12640     {
12641       tree tuple = TREE_VEC_ELT (parms, i);
12642
12643       if (tuple == error_mark_node)
12644         continue;
12645
12646       TREE_VEC_ELT (new_vec, i) =
12647         tsubst_template_parm (tuple, args, complain);
12648     }
12649
12650   return new_vec;
12651 }
12652
12653 /* Return the result of substituting ARGS into the template parameters
12654    given by PARMS.  If there are m levels of ARGS and m + n levels of
12655    PARMS, then the result will contain n levels of PARMS.  For
12656    example, if PARMS is `template <class T> template <class U>
12657    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12658    result will be `template <int*, double, class V>'.  */
12659
12660 static tree
12661 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12662 {
12663   tree r = NULL_TREE;
12664   tree* new_parms;
12665
12666   /* When substituting into a template, we must set
12667      PROCESSING_TEMPLATE_DECL as the template parameters may be
12668      dependent if they are based on one-another, and the dependency
12669      predicates are short-circuit outside of templates.  */
12670   ++processing_template_decl;
12671
12672   for (new_parms = &r;
12673        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12674        new_parms = &(TREE_CHAIN (*new_parms)),
12675          parms = TREE_CHAIN (parms))
12676     {
12677       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12678                                                   args, complain);
12679       *new_parms =
12680         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12681                              - TMPL_ARGS_DEPTH (args)),
12682                    new_vec, NULL_TREE);
12683     }
12684
12685   --processing_template_decl;
12686
12687   return r;
12688 }
12689
12690 /* Return the result of substituting ARGS into one template parameter
12691    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12692    parameter and which TREE_PURPOSE is the default argument of the
12693    template parameter.  */
12694
12695 static tree
12696 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12697 {
12698   tree default_value, parm_decl;
12699
12700   if (args == NULL_TREE
12701       || t == NULL_TREE
12702       || t == error_mark_node)
12703     return t;
12704
12705   gcc_assert (TREE_CODE (t) == TREE_LIST);
12706
12707   default_value = TREE_PURPOSE (t);
12708   parm_decl = TREE_VALUE (t);
12709
12710   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12711   if (TREE_CODE (parm_decl) == PARM_DECL
12712       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12713     parm_decl = error_mark_node;
12714   default_value = tsubst_template_arg (default_value, args,
12715                                        complain, NULL_TREE);
12716
12717   return build_tree_list (default_value, parm_decl);
12718 }
12719
12720 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12721    type T.  If T is not an aggregate or enumeration type, it is
12722    handled as if by tsubst.  IN_DECL is as for tsubst.  If
12723    ENTERING_SCOPE is nonzero, T is the context for a template which
12724    we are presently tsubst'ing.  Return the substituted value.  */
12725
12726 static tree
12727 tsubst_aggr_type (tree t,
12728                   tree args,
12729                   tsubst_flags_t complain,
12730                   tree in_decl,
12731                   int entering_scope)
12732 {
12733   if (t == NULL_TREE)
12734     return NULL_TREE;
12735
12736   switch (TREE_CODE (t))
12737     {
12738     case RECORD_TYPE:
12739       if (TYPE_PTRMEMFUNC_P (t))
12740         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12741
12742       /* Fall through.  */
12743     case ENUMERAL_TYPE:
12744     case UNION_TYPE:
12745       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12746         {
12747           tree argvec;
12748           tree context;
12749           tree r;
12750
12751           /* In "sizeof(X<I>)" we need to evaluate "I".  */
12752           cp_evaluated ev;
12753
12754           /* First, determine the context for the type we are looking
12755              up.  */
12756           context = TYPE_CONTEXT (t);
12757           if (context && TYPE_P (context))
12758             {
12759               context = tsubst_aggr_type (context, args, complain,
12760                                           in_decl, /*entering_scope=*/1);
12761               /* If context is a nested class inside a class template,
12762                  it may still need to be instantiated (c++/33959).  */
12763               context = complete_type (context);
12764             }
12765
12766           /* Then, figure out what arguments are appropriate for the
12767              type we are trying to find.  For example, given:
12768
12769                template <class T> struct S;
12770                template <class T, class U> void f(T, U) { S<U> su; }
12771
12772              and supposing that we are instantiating f<int, double>,
12773              then our ARGS will be {int, double}, but, when looking up
12774              S we only want {double}.  */
12775           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12776                                          complain, in_decl);
12777           if (argvec == error_mark_node)
12778             r = error_mark_node;
12779           else
12780             {
12781               r = lookup_template_class (t, argvec, in_decl, context,
12782                                          entering_scope, complain);
12783               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12784             }
12785
12786           return r;
12787         }
12788       else
12789         /* This is not a template type, so there's nothing to do.  */
12790         return t;
12791
12792     default:
12793       return tsubst (t, args, complain, in_decl);
12794     }
12795 }
12796
12797 static GTY((cache)) tree_cache_map *defarg_inst;
12798
12799 /* Substitute into the default argument ARG (a default argument for
12800    FN), which has the indicated TYPE.  */
12801
12802 tree
12803 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12804                          tsubst_flags_t complain)
12805 {
12806   int errs = errorcount + sorrycount;
12807
12808   /* This can happen in invalid code.  */
12809   if (TREE_CODE (arg) == DEFERRED_PARSE)
12810     return arg;
12811
12812   tree parm = FUNCTION_FIRST_USER_PARM (fn);
12813   parm = chain_index (parmnum, parm);
12814   tree parmtype = TREE_TYPE (parm);
12815   if (DECL_BY_REFERENCE (parm))
12816     parmtype = TREE_TYPE (parmtype);
12817   if (parmtype == error_mark_node)
12818     return error_mark_node;
12819
12820   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12821
12822   tree *slot;
12823   if (defarg_inst && (slot = defarg_inst->get (parm)))
12824     return *slot;
12825
12826   /* This default argument came from a template.  Instantiate the
12827      default argument here, not in tsubst.  In the case of
12828      something like:
12829
12830        template <class T>
12831        struct S {
12832          static T t();
12833          void f(T = t());
12834        };
12835
12836      we must be careful to do name lookup in the scope of S<T>,
12837      rather than in the current class.  */
12838   push_to_top_level ();
12839   push_access_scope (fn);
12840   push_deferring_access_checks (dk_no_deferred);
12841   start_lambda_scope (parm);
12842
12843   /* The default argument expression may cause implicitly defined
12844      member functions to be synthesized, which will result in garbage
12845      collection.  We must treat this situation as if we were within
12846      the body of function so as to avoid collecting live data on the
12847      stack.  */
12848   ++function_depth;
12849   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12850                      complain, NULL_TREE,
12851                      /*integral_constant_expression_p=*/false);
12852   --function_depth;
12853
12854   finish_lambda_scope ();
12855
12856   /* Make sure the default argument is reasonable.  */
12857   arg = check_default_argument (type, arg, complain);
12858
12859   if (errorcount+sorrycount > errs
12860       && (complain & tf_warning_or_error))
12861     inform (input_location,
12862             "  when instantiating default argument for call to %qD", fn);
12863
12864   pop_deferring_access_checks ();
12865   pop_access_scope (fn);
12866   pop_from_top_level ();
12867
12868   if (arg != error_mark_node && !cp_unevaluated_operand)
12869     {
12870       if (!defarg_inst)
12871         defarg_inst = tree_cache_map::create_ggc (37);
12872       defarg_inst->put (parm, arg);
12873     }
12874
12875   return arg;
12876 }
12877
12878 /* Substitute into all the default arguments for FN.  */
12879
12880 static void
12881 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12882 {
12883   tree arg;
12884   tree tmpl_args;
12885
12886   tmpl_args = DECL_TI_ARGS (fn);
12887
12888   /* If this function is not yet instantiated, we certainly don't need
12889      its default arguments.  */
12890   if (uses_template_parms (tmpl_args))
12891     return;
12892   /* Don't do this again for clones.  */
12893   if (DECL_CLONED_FUNCTION_P (fn))
12894     return;
12895
12896   int i = 0;
12897   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12898        arg;
12899        arg = TREE_CHAIN (arg), ++i)
12900     if (TREE_PURPOSE (arg))
12901       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12902                                                     TREE_VALUE (arg),
12903                                                     TREE_PURPOSE (arg),
12904                                                     complain);
12905 }
12906
12907 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
12908 static GTY((cache)) tree_cache_map *explicit_specifier_map;
12909
12910 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
12911
12912 void
12913 store_explicit_specifier (tree v, tree t)
12914 {
12915   if (!explicit_specifier_map)
12916     explicit_specifier_map = tree_cache_map::create_ggc (37);
12917   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
12918   explicit_specifier_map->put (v, t);
12919 }
12920
12921 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
12922
12923 static tree
12924 lookup_explicit_specifier (tree v)
12925 {
12926   return *explicit_specifier_map->get (v);
12927 }
12928
12929 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
12930
12931 static tree
12932 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12933                       tree lambda_fntype)
12934 {
12935   tree gen_tmpl, argvec;
12936   hashval_t hash = 0;
12937   tree in_decl = t;
12938
12939   /* Nobody should be tsubst'ing into non-template functions.  */
12940   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12941
12942   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12943     {
12944       /* If T is not dependent, just return it.  */
12945       if (!uses_template_parms (DECL_TI_ARGS (t))
12946           && !LAMBDA_FUNCTION_P (t))
12947         return t;
12948
12949       /* Calculate the most general template of which R is a
12950          specialization.  */
12951       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12952
12953       /* We're substituting a lambda function under tsubst_lambda_expr but not
12954          directly from it; find the matching function we're already inside.
12955          But don't do this if T is a generic lambda with a single level of
12956          template parms, as in that case we're doing a normal instantiation. */
12957       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12958           && (!generic_lambda_fn_p (t)
12959               || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12960         return enclosing_instantiation_of (t);
12961
12962       /* Calculate the complete set of arguments used to
12963          specialize R.  */
12964       argvec = tsubst_template_args (DECL_TI_ARGS
12965                                      (DECL_TEMPLATE_RESULT
12966                                       (DECL_TI_TEMPLATE (t))),
12967                                      args, complain, in_decl);
12968       if (argvec == error_mark_node)
12969         return error_mark_node;
12970
12971       /* Check to see if we already have this specialization.  */
12972       if (!lambda_fntype)
12973         {
12974           hash = hash_tmpl_and_args (gen_tmpl, argvec);
12975           if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12976             return spec;
12977         }
12978
12979       /* We can see more levels of arguments than parameters if
12980          there was a specialization of a member template, like
12981          this:
12982
12983          template <class T> struct S { template <class U> void f(); }
12984          template <> template <class U> void S<int>::f(U);
12985
12986          Here, we'll be substituting into the specialization,
12987          because that's where we can find the code we actually
12988          want to generate, but we'll have enough arguments for
12989          the most general template.
12990
12991          We also deal with the peculiar case:
12992
12993          template <class T> struct S {
12994            template <class U> friend void f();
12995          };
12996          template <class U> void f() {}
12997          template S<int>;
12998          template void f<double>();
12999
13000          Here, the ARGS for the instantiation of will be {int,
13001          double}.  But, we only need as many ARGS as there are
13002          levels of template parameters in CODE_PATTERN.  We are
13003          careful not to get fooled into reducing the ARGS in
13004          situations like:
13005
13006          template <class T> struct S { template <class U> void f(U); }
13007          template <class T> template <> void S<T>::f(int) {}
13008
13009          which we can spot because the pattern will be a
13010          specialization in this case.  */
13011       int args_depth = TMPL_ARGS_DEPTH (args);
13012       int parms_depth =
13013         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
13014
13015       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
13016         args = get_innermost_template_args (args, parms_depth);
13017     }
13018   else
13019     {
13020       /* This special case arises when we have something like this:
13021
13022          template <class T> struct S {
13023          friend void f<int>(int, double);
13024          };
13025
13026          Here, the DECL_TI_TEMPLATE for the friend declaration
13027          will be an IDENTIFIER_NODE.  We are being called from
13028          tsubst_friend_function, and we want only to create a
13029          new decl (R) with appropriate types so that we can call
13030          determine_specialization.  */
13031       gen_tmpl = NULL_TREE;
13032       argvec = NULL_TREE;
13033     }
13034
13035   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13036                   : NULL_TREE);
13037   tree ctx = closure ? closure : DECL_CONTEXT (t);
13038   bool member = ctx && TYPE_P (ctx);
13039
13040   if (member && !closure)
13041     ctx = tsubst_aggr_type (ctx, args,
13042                             complain, t, /*entering_scope=*/1);
13043
13044   tree type = (lambda_fntype ? lambda_fntype
13045                : tsubst (TREE_TYPE (t), args,
13046                          complain | tf_fndecl_type, in_decl));
13047   if (type == error_mark_node)
13048     return error_mark_node;
13049
13050   /* If we hit excessive deduction depth, the type is bogus even if
13051      it isn't error_mark_node, so don't build a decl.  */
13052   if (excessive_deduction_depth)
13053     return error_mark_node;
13054
13055   /* We do NOT check for matching decls pushed separately at this
13056      point, as they may not represent instantiations of this
13057      template, and in any case are considered separate under the
13058      discrete model.  */
13059   tree r = copy_decl (t);
13060   DECL_USE_TEMPLATE (r) = 0;
13061   TREE_TYPE (r) = type;
13062   /* Clear out the mangled name and RTL for the instantiation.  */
13063   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13064   SET_DECL_RTL (r, NULL);
13065   /* Leave DECL_INITIAL set on deleted instantiations.  */
13066   if (!DECL_DELETED_FN (r))
13067     DECL_INITIAL (r) = NULL_TREE;
13068   DECL_CONTEXT (r) = ctx;
13069
13070   /* Handle explicit(dependent-expr).  */
13071   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
13072     {
13073       tree spec = lookup_explicit_specifier (t);
13074       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
13075                                     /*function_p=*/false,
13076                                     /*i_c_e_p=*/true);
13077       spec = build_explicit_specifier (spec, complain);
13078       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
13079     }
13080
13081   /* OpenMP UDRs have the only argument a reference to the declared
13082      type.  We want to diagnose if the declared type is a reference,
13083      which is invalid, but as references to references are usually
13084      quietly merged, diagnose it here.  */
13085   if (DECL_OMP_DECLARE_REDUCTION_P (t))
13086     {
13087       tree argtype
13088         = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
13089       argtype = tsubst (argtype, args, complain, in_decl);
13090       if (TYPE_REF_P (argtype))
13091         error_at (DECL_SOURCE_LOCATION (t),
13092                   "reference type %qT in "
13093                   "%<#pragma omp declare reduction%>", argtype);
13094       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13095         DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13096                                           argtype);
13097     }
13098
13099   if (member && DECL_CONV_FN_P (r))
13100     /* Type-conversion operator.  Reconstruct the name, in
13101        case it's the name of one of the template's parameters.  */
13102     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13103
13104   tree parms = DECL_ARGUMENTS (t);
13105   if (closure)
13106     parms = DECL_CHAIN (parms);
13107   parms = tsubst (parms, args, complain, t);
13108   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13109     DECL_CONTEXT (parm) = r;
13110   if (closure)
13111     {
13112       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13113       DECL_CHAIN (tparm) = parms;
13114       parms = tparm;
13115     }
13116   DECL_ARGUMENTS (r) = parms;
13117   DECL_RESULT (r) = NULL_TREE;
13118
13119   TREE_STATIC (r) = 0;
13120   TREE_PUBLIC (r) = TREE_PUBLIC (t);
13121   DECL_EXTERNAL (r) = 1;
13122   /* If this is an instantiation of a function with internal
13123      linkage, we already know what object file linkage will be
13124      assigned to the instantiation.  */
13125   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13126   DECL_DEFER_OUTPUT (r) = 0;
13127   DECL_CHAIN (r) = NULL_TREE;
13128   DECL_PENDING_INLINE_INFO (r) = 0;
13129   DECL_PENDING_INLINE_P (r) = 0;
13130   DECL_SAVED_TREE (r) = NULL_TREE;
13131   DECL_STRUCT_FUNCTION (r) = NULL;
13132   TREE_USED (r) = 0;
13133   /* We'll re-clone as appropriate in instantiate_template.  */
13134   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13135
13136   /* If we aren't complaining now, return on error before we register
13137      the specialization so that we'll complain eventually.  */
13138   if ((complain & tf_error) == 0
13139       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13140       && !grok_op_properties (r, /*complain=*/false))
13141     return error_mark_node;
13142
13143   /* When instantiating a constrained member, substitute
13144      into the constraints to create a new constraint.  */
13145   if (tree ci = get_constraints (t))
13146     if (member)
13147       {
13148         ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13149         set_constraints (r, ci);
13150       }
13151
13152   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13153     SET_DECL_FRIEND_CONTEXT (r,
13154                              tsubst (DECL_FRIEND_CONTEXT (t),
13155                                      args, complain, in_decl));
13156
13157   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13158      this in the special friend case mentioned above where
13159      GEN_TMPL is NULL.  */
13160   if (gen_tmpl && !closure)
13161     {
13162       DECL_TEMPLATE_INFO (r)
13163         = build_template_info (gen_tmpl, argvec);
13164       SET_DECL_IMPLICIT_INSTANTIATION (r);
13165
13166       tree new_r
13167         = register_specialization (r, gen_tmpl, argvec, false, hash);
13168       if (new_r != r)
13169         /* We instantiated this while substituting into
13170            the type earlier (template/friend54.C).  */
13171         return new_r;
13172
13173       /* We're not supposed to instantiate default arguments
13174          until they are called, for a template.  But, for a
13175          declaration like:
13176
13177          template <class T> void f ()
13178          { extern void g(int i = T()); }
13179
13180          we should do the substitution when the template is
13181          instantiated.  We handle the member function case in
13182          instantiate_class_template since the default arguments
13183          might refer to other members of the class.  */
13184       if (!member
13185           && !PRIMARY_TEMPLATE_P (gen_tmpl)
13186           && !uses_template_parms (argvec))
13187         tsubst_default_arguments (r, complain);
13188     }
13189   else
13190     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13191
13192   /* Copy the list of befriending classes.  */
13193   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13194        *friends;
13195        friends = &TREE_CHAIN (*friends))
13196     {
13197       *friends = copy_node (*friends);
13198       TREE_VALUE (*friends)
13199         = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13200     }
13201
13202   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13203     {
13204       maybe_retrofit_in_chrg (r);
13205       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13206         return error_mark_node;
13207       /* If this is an instantiation of a member template, clone it.
13208          If it isn't, that'll be handled by
13209          clone_constructors_and_destructors.  */
13210       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13211         clone_function_decl (r, /*update_methods=*/false);
13212     }
13213   else if ((complain & tf_error) != 0
13214            && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13215            && !grok_op_properties (r, /*complain=*/true))
13216     return error_mark_node;
13217
13218   /* Possibly limit visibility based on template args.  */
13219   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13220   if (DECL_VISIBILITY_SPECIFIED (t))
13221     {
13222       DECL_VISIBILITY_SPECIFIED (r) = 0;
13223       DECL_ATTRIBUTES (r)
13224         = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13225     }
13226   determine_visibility (r);
13227   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13228       && !processing_template_decl)
13229     defaulted_late_check (r);
13230
13231   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13232                                   args, complain, in_decl);
13233   return r;
13234 }
13235
13236 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13237
13238 static tree
13239 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13240                       tree lambda_fntype)
13241 {
13242   /* We can get here when processing a member function template,
13243      member class template, or template template parameter.  */
13244   tree decl = DECL_TEMPLATE_RESULT (t);
13245   tree in_decl = t;
13246   tree spec;
13247   tree tmpl_args;
13248   tree full_args;
13249   tree r;
13250   hashval_t hash = 0;
13251
13252   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13253     {
13254       /* Template template parameter is treated here.  */
13255       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13256       if (new_type == error_mark_node)
13257         r = error_mark_node;
13258       /* If we get a real template back, return it.  This can happen in
13259          the context of most_specialized_partial_spec.  */
13260       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13261         r = new_type;
13262       else
13263         /* The new TEMPLATE_DECL was built in
13264            reduce_template_parm_level.  */
13265         r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13266       return r;
13267     }
13268
13269   if (!lambda_fntype)
13270     {
13271       /* We might already have an instance of this template.
13272          The ARGS are for the surrounding class type, so the
13273          full args contain the tsubst'd args for the context,
13274          plus the innermost args from the template decl.  */
13275       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13276         ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13277         : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13278       /* Because this is a template, the arguments will still be
13279          dependent, even after substitution.  If
13280          PROCESSING_TEMPLATE_DECL is not set, the dependency
13281          predicates will short-circuit.  */
13282       ++processing_template_decl;
13283       full_args = tsubst_template_args (tmpl_args, args,
13284                                         complain, in_decl);
13285       --processing_template_decl;
13286       if (full_args == error_mark_node)
13287         return error_mark_node;
13288
13289       /* If this is a default template template argument,
13290          tsubst might not have changed anything.  */
13291       if (full_args == tmpl_args)
13292         return t;
13293
13294       hash = hash_tmpl_and_args (t, full_args);
13295       spec = retrieve_specialization (t, full_args, hash);
13296       if (spec != NULL_TREE)
13297         {
13298           if (TYPE_P (spec))
13299             /* Type partial instantiations are stored as the type by
13300                lookup_template_class_1, not here as the template.  */
13301             spec = CLASSTYPE_TI_TEMPLATE (spec);
13302           return spec;
13303         }
13304     }
13305
13306   /* Make a new template decl.  It will be similar to the
13307      original, but will record the current template arguments.
13308      We also create a new function declaration, which is just
13309      like the old one, but points to this new template, rather
13310      than the old one.  */
13311   r = copy_decl (t);
13312   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13313   DECL_CHAIN (r) = NULL_TREE;
13314
13315   // Build new template info linking to the original template decl.
13316   if (!lambda_fntype)
13317     {
13318       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13319       SET_DECL_IMPLICIT_INSTANTIATION (r);
13320     }
13321   else
13322     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13323
13324   /* The template parameters for this new template are all the
13325      template parameters for the old template, except the
13326      outermost level of parameters.  */
13327   DECL_TEMPLATE_PARMS (r)
13328     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13329                              complain);
13330
13331   if (TREE_CODE (decl) == TYPE_DECL
13332       && !TYPE_DECL_ALIAS_P (decl))
13333     {
13334       tree new_type;
13335       ++processing_template_decl;
13336       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13337       --processing_template_decl;
13338       if (new_type == error_mark_node)
13339         return error_mark_node;
13340
13341       TREE_TYPE (r) = new_type;
13342       /* For a partial specialization, we need to keep pointing to
13343          the primary template.  */
13344       if (!DECL_TEMPLATE_SPECIALIZATION (t))
13345         CLASSTYPE_TI_TEMPLATE (new_type) = r;
13346       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13347       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13348       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13349     }
13350   else
13351     {
13352       tree new_decl;
13353       ++processing_template_decl;
13354       if (TREE_CODE (decl) == FUNCTION_DECL)
13355         new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13356       else
13357         new_decl = tsubst (decl, args, complain, in_decl);
13358       --processing_template_decl;
13359       if (new_decl == error_mark_node)
13360         return error_mark_node;
13361
13362       DECL_TEMPLATE_RESULT (r) = new_decl;
13363       TREE_TYPE (r) = TREE_TYPE (new_decl);
13364       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13365       if (lambda_fntype)
13366         {
13367           tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13368           DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13369         }
13370       else
13371         {
13372           DECL_TI_TEMPLATE (new_decl) = r;
13373           DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13374         }
13375     }
13376
13377   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13378   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13379
13380   if (PRIMARY_TEMPLATE_P (t))
13381     DECL_PRIMARY_TEMPLATE (r) = r;
13382
13383   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13384       && !lambda_fntype)
13385     /* Record this non-type partial instantiation.  */
13386     register_specialization (r, t,
13387                              DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13388                              false, hash);
13389
13390   return r;
13391 }
13392
13393 /* True if FN is the op() for a lambda in an uninstantiated template.  */
13394
13395 bool
13396 lambda_fn_in_template_p (tree fn)
13397 {
13398   if (!fn || !LAMBDA_FUNCTION_P (fn))
13399     return false;
13400   tree closure = DECL_CONTEXT (fn);
13401   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13402 }
13403
13404 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
13405    which the above is true.  */
13406
13407 bool
13408 instantiated_lambda_fn_p (tree fn)
13409 {
13410   if (!fn || !LAMBDA_FUNCTION_P (fn))
13411     return false;
13412   tree closure = DECL_CONTEXT (fn);
13413   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
13414   return LAMBDA_EXPR_INSTANTIATED (lam);
13415 }
13416
13417 /* We're instantiating a variable from template function TCTX.  Return the
13418    corresponding current enclosing scope.  This gets complicated because lambda
13419    functions in templates are regenerated rather than instantiated, but generic
13420    lambda functions are subsequently instantiated.  */
13421
13422 static tree
13423 enclosing_instantiation_of (tree otctx)
13424 {
13425   tree tctx = otctx;
13426   tree fn = current_function_decl;
13427   int lambda_count = 0;
13428
13429   for (; tctx && (lambda_fn_in_template_p (tctx)
13430                   || instantiated_lambda_fn_p (tctx));
13431        tctx = decl_function_context (tctx))
13432     ++lambda_count;
13433   for (; fn; fn = decl_function_context (fn))
13434     {
13435       tree ofn = fn;
13436       int flambda_count = 0;
13437       for (; fn && instantiated_lambda_fn_p (fn);
13438            fn = decl_function_context (fn))
13439         ++flambda_count;
13440       if ((fn && DECL_TEMPLATE_INFO (fn))
13441           ? most_general_template (fn) != most_general_template (tctx)
13442           : fn != tctx)
13443         continue;
13444       if (flambda_count != lambda_count)
13445         {
13446           gcc_assert (flambda_count > lambda_count);
13447           for (; flambda_count > lambda_count; --flambda_count)
13448             ofn = decl_function_context (ofn);
13449         }
13450       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13451                   || DECL_CONV_FN_P (ofn));
13452       return ofn;
13453     }
13454   gcc_unreachable ();
13455 }
13456
13457 /* Substitute the ARGS into the T, which is a _DECL.  Return the
13458    result of the substitution.  Issue error and warning messages under
13459    control of COMPLAIN.  */
13460
13461 static tree
13462 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13463 {
13464 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13465   location_t saved_loc;
13466   tree r = NULL_TREE;
13467   tree in_decl = t;
13468   hashval_t hash = 0;
13469
13470   /* Set the filename and linenumber to improve error-reporting.  */
13471   saved_loc = input_location;
13472   input_location = DECL_SOURCE_LOCATION (t);
13473
13474   switch (TREE_CODE (t))
13475     {
13476     case TEMPLATE_DECL:
13477       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13478       break;
13479
13480     case FUNCTION_DECL:
13481       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13482       break;
13483
13484     case PARM_DECL:
13485       {
13486         tree type = NULL_TREE;
13487         int i, len = 1;
13488         tree expanded_types = NULL_TREE;
13489         tree prev_r = NULL_TREE;
13490         tree first_r = NULL_TREE;
13491
13492         if (DECL_PACK_P (t))
13493           {
13494             /* If there is a local specialization that isn't a
13495                parameter pack, it means that we're doing a "simple"
13496                substitution from inside tsubst_pack_expansion. Just
13497                return the local specialization (which will be a single
13498                parm).  */
13499             tree spec = retrieve_local_specialization (t);
13500             if (spec 
13501                 && TREE_CODE (spec) == PARM_DECL
13502                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13503               RETURN (spec);
13504
13505             /* Expand the TYPE_PACK_EXPANSION that provides the types for
13506                the parameters in this function parameter pack.  */
13507             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13508                                                     complain, in_decl);
13509             if (TREE_CODE (expanded_types) == TREE_VEC)
13510               {
13511                 len = TREE_VEC_LENGTH (expanded_types);
13512
13513                 /* Zero-length parameter packs are boring. Just substitute
13514                    into the chain.  */
13515                 if (len == 0)
13516                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
13517                                   TREE_CHAIN (t)));
13518               }
13519             else
13520               {
13521                 /* All we did was update the type. Make a note of that.  */
13522                 type = expanded_types;
13523                 expanded_types = NULL_TREE;
13524               }
13525           }
13526
13527         /* Loop through all of the parameters we'll build. When T is
13528            a function parameter pack, LEN is the number of expanded
13529            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
13530         r = NULL_TREE;
13531         for (i = 0; i < len; ++i)
13532           {
13533             prev_r = r;
13534             r = copy_node (t);
13535             if (DECL_TEMPLATE_PARM_P (t))
13536               SET_DECL_TEMPLATE_PARM_P (r);
13537
13538             if (expanded_types)
13539               /* We're on the Ith parameter of the function parameter
13540                  pack.  */
13541               {
13542                 /* Get the Ith type.  */
13543                 type = TREE_VEC_ELT (expanded_types, i);
13544
13545                 /* Rename the parameter to include the index.  */
13546                 DECL_NAME (r)
13547                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
13548               }
13549             else if (!type)
13550               /* We're dealing with a normal parameter.  */
13551               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13552
13553             type = type_decays_to (type);
13554             TREE_TYPE (r) = type;
13555             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13556
13557             if (DECL_INITIAL (r))
13558               {
13559                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13560                   DECL_INITIAL (r) = TREE_TYPE (r);
13561                 else
13562                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13563                                              complain, in_decl);
13564               }
13565
13566             DECL_CONTEXT (r) = NULL_TREE;
13567
13568             if (!DECL_TEMPLATE_PARM_P (r))
13569               DECL_ARG_TYPE (r) = type_passed_as (type);
13570
13571             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13572                                             args, complain, in_decl);
13573
13574             /* Keep track of the first new parameter we
13575                generate. That's what will be returned to the
13576                caller.  */
13577             if (!first_r)
13578               first_r = r;
13579
13580             /* Build a proper chain of parameters when substituting
13581                into a function parameter pack.  */
13582             if (prev_r)
13583               DECL_CHAIN (prev_r) = r;
13584           }
13585
13586         /* If cp_unevaluated_operand is set, we're just looking for a
13587            single dummy parameter, so don't keep going.  */
13588         if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13589           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13590                                    complain, DECL_CHAIN (t));
13591
13592         /* FIRST_R contains the start of the chain we've built.  */
13593         r = first_r;
13594       }
13595       break;
13596
13597     case FIELD_DECL:
13598       {
13599         tree type = NULL_TREE;
13600         tree vec = NULL_TREE;
13601         tree expanded_types = NULL_TREE;
13602         int len = 1;
13603
13604         if (PACK_EXPANSION_P (TREE_TYPE (t)))
13605           {
13606             /* This field is a lambda capture pack.  Return a TREE_VEC of
13607                the expanded fields to instantiate_class_template_1.  */
13608             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13609                                                     complain, in_decl);
13610             if (TREE_CODE (expanded_types) == TREE_VEC)
13611               {
13612                 len = TREE_VEC_LENGTH (expanded_types);
13613                 vec = make_tree_vec (len);
13614               }
13615             else
13616               {
13617                 /* All we did was update the type. Make a note of that.  */
13618                 type = expanded_types;
13619                 expanded_types = NULL_TREE;
13620               }
13621           }
13622
13623         for (int i = 0; i < len; ++i)
13624           {
13625             r = copy_decl (t);
13626             if (expanded_types)
13627               {
13628                 type = TREE_VEC_ELT (expanded_types, i);
13629                 DECL_NAME (r)
13630                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
13631               }
13632             else if (!type)
13633               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13634
13635             if (type == error_mark_node)
13636               RETURN (error_mark_node);
13637             TREE_TYPE (r) = type;
13638             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13639
13640             if (DECL_C_BIT_FIELD (r))
13641               /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13642                  number of bits.  */
13643               DECL_BIT_FIELD_REPRESENTATIVE (r)
13644                 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13645                                complain, in_decl,
13646                                /*integral_constant_expression_p=*/true);
13647             if (DECL_INITIAL (t))
13648               {
13649                 /* Set up DECL_TEMPLATE_INFO so that we can get at the
13650                    NSDMI in perform_member_init.  Still set DECL_INITIAL
13651                    so that we know there is one.  */
13652                 DECL_INITIAL (r) = void_node;
13653                 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13654                 retrofit_lang_decl (r);
13655                 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13656               }
13657             /* We don't have to set DECL_CONTEXT here; it is set by
13658                finish_member_declaration.  */
13659             DECL_CHAIN (r) = NULL_TREE;
13660
13661             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13662                                             args, complain, in_decl);
13663
13664             if (vec)
13665               TREE_VEC_ELT (vec, i) = r;
13666           }
13667
13668         if (vec)
13669           r = vec;
13670       }
13671       break;
13672
13673     case USING_DECL:
13674       /* We reach here only for member using decls.  We also need to check
13675          uses_template_parms because DECL_DEPENDENT_P is not set for a
13676          using-declaration that designates a member of the current
13677          instantiation (c++/53549).  */
13678       if (DECL_DEPENDENT_P (t)
13679           || uses_template_parms (USING_DECL_SCOPE (t)))
13680         {
13681           tree scope = USING_DECL_SCOPE (t);
13682           tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13683           if (PACK_EXPANSION_P (scope))
13684             {
13685               tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13686               int len = TREE_VEC_LENGTH (vec);
13687               r = make_tree_vec (len);
13688               for (int i = 0; i < len; ++i)
13689                 {
13690                   tree escope = TREE_VEC_ELT (vec, i);
13691                   tree elt = do_class_using_decl (escope, name);
13692                   if (!elt)
13693                     {
13694                       r = error_mark_node;
13695                       break;
13696                     }
13697                   else
13698                     {
13699                       TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13700                       TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13701                     }
13702                   TREE_VEC_ELT (r, i) = elt;
13703                 }
13704             }
13705           else
13706             {
13707               tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13708                                              complain, in_decl);
13709               r = do_class_using_decl (inst_scope, name);
13710               if (!r)
13711                 r = error_mark_node;
13712               else
13713                 {
13714                   TREE_PROTECTED (r) = TREE_PROTECTED (t);
13715                   TREE_PRIVATE (r) = TREE_PRIVATE (t);
13716                 }
13717             }
13718         }
13719       else
13720         {
13721           r = copy_node (t);
13722           DECL_CHAIN (r) = NULL_TREE;
13723         }
13724       break;
13725
13726     case TYPE_DECL:
13727     case VAR_DECL:
13728       {
13729         tree argvec = NULL_TREE;
13730         tree gen_tmpl = NULL_TREE;
13731         tree spec;
13732         tree tmpl = NULL_TREE;
13733         tree ctx;
13734         tree type = NULL_TREE;
13735         bool local_p;
13736
13737         if (TREE_TYPE (t) == error_mark_node)
13738           RETURN (error_mark_node);
13739
13740         if (TREE_CODE (t) == TYPE_DECL
13741             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13742           {
13743             /* If this is the canonical decl, we don't have to
13744                mess with instantiations, and often we can't (for
13745                typename, template type parms and such).  Note that
13746                TYPE_NAME is not correct for the above test if
13747                we've copied the type for a typedef.  */
13748             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13749             if (type == error_mark_node)
13750               RETURN (error_mark_node);
13751             r = TYPE_NAME (type);
13752             break;
13753           }
13754
13755         /* Check to see if we already have the specialization we
13756            need.  */
13757         spec = NULL_TREE;
13758         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13759           {
13760             /* T is a static data member or namespace-scope entity.
13761                We have to substitute into namespace-scope variables
13762                (not just variable templates) because of cases like:
13763
13764                  template <class T> void f() { extern T t; }
13765
13766                where the entity referenced is not known until
13767                instantiation time.  */
13768             local_p = false;
13769             ctx = DECL_CONTEXT (t);
13770             if (DECL_CLASS_SCOPE_P (t))
13771               {
13772                 ctx = tsubst_aggr_type (ctx, args,
13773                                         complain,
13774                                         in_decl, /*entering_scope=*/1);
13775                 /* If CTX is unchanged, then T is in fact the
13776                    specialization we want.  That situation occurs when
13777                    referencing a static data member within in its own
13778                    class.  We can use pointer equality, rather than
13779                    same_type_p, because DECL_CONTEXT is always
13780                    canonical...  */
13781                 if (ctx == DECL_CONTEXT (t)
13782                     /* ... unless T is a member template; in which
13783                        case our caller can be willing to create a
13784                        specialization of that template represented
13785                        by T.  */
13786                     && !(DECL_TI_TEMPLATE (t)
13787                          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13788                   spec = t;
13789               }
13790
13791             if (!spec)
13792               {
13793                 tmpl = DECL_TI_TEMPLATE (t);
13794                 gen_tmpl = most_general_template (tmpl);
13795                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13796                 if (argvec != error_mark_node)
13797                   argvec = (coerce_innermost_template_parms
13798                             (DECL_TEMPLATE_PARMS (gen_tmpl),
13799                              argvec, t, complain,
13800                              /*all*/true, /*defarg*/true));
13801                 if (argvec == error_mark_node)
13802                   RETURN (error_mark_node);
13803                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
13804                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
13805               }
13806           }
13807         else
13808           {
13809             /* A local variable.  */
13810             local_p = true;
13811             /* Subsequent calls to pushdecl will fill this in.  */
13812             ctx = NULL_TREE;
13813             /* Unless this is a reference to a static variable from an
13814                enclosing function, in which case we need to fill it in now.  */
13815             if (TREE_STATIC (t))
13816               {
13817                 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13818                 if (fn != current_function_decl)
13819                   ctx = fn;
13820               }
13821             spec = retrieve_local_specialization (t);
13822           }
13823         /* If we already have the specialization we need, there is
13824            nothing more to do.  */
13825         if (spec)
13826           {
13827             r = spec;
13828             break;
13829           }
13830
13831         /* Create a new node for the specialization we need.  */
13832         if (type == NULL_TREE)
13833           {
13834             if (is_typedef_decl (t))
13835               type = DECL_ORIGINAL_TYPE (t);
13836             else
13837               type = TREE_TYPE (t);
13838             if (VAR_P (t)
13839                 && VAR_HAD_UNKNOWN_BOUND (t)
13840                 && type != error_mark_node)
13841               type = strip_array_domain (type);
13842             tree sub_args = args;
13843             if (tree auto_node = type_uses_auto (type))
13844               {
13845                 /* Mask off any template args past the variable's context so we
13846                    don't replace the auto with an unrelated argument.  */
13847                 int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13848                 int extra = TMPL_ARGS_DEPTH (args) - nouter;
13849                 if (extra > 0)
13850                   /* This should never happen with the new lambda instantiation
13851                      model, but keep the handling just in case.  */
13852                   gcc_assert (!CHECKING_P),
13853                   sub_args = strip_innermost_template_args (args, extra);
13854               }
13855             type = tsubst (type, sub_args, complain, in_decl);
13856             /* Substituting the type might have recursively instantiated this
13857                same alias (c++/86171).  */
13858             if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
13859                 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
13860               {
13861                 r = spec;
13862                 break;
13863               }
13864           }
13865         r = copy_decl (t);
13866         if (VAR_P (r))
13867           {
13868             DECL_INITIALIZED_P (r) = 0;
13869             DECL_TEMPLATE_INSTANTIATED (r) = 0;
13870             if (type == error_mark_node)
13871               RETURN (error_mark_node);
13872             if (TREE_CODE (type) == FUNCTION_TYPE)
13873               {
13874                 /* It may seem that this case cannot occur, since:
13875
13876                    typedef void f();
13877                    void g() { f x; }
13878
13879                    declares a function, not a variable.  However:
13880
13881                    typedef void f();
13882                    template <typename T> void g() { T t; }
13883                    template void g<f>();
13884
13885                    is an attempt to declare a variable with function
13886                    type.  */
13887                 error ("variable %qD has function type",
13888                        /* R is not yet sufficiently initialized, so we
13889                           just use its name.  */
13890                        DECL_NAME (r));
13891                 RETURN (error_mark_node);
13892               }
13893             type = complete_type (type);
13894             /* Wait until cp_finish_decl to set this again, to handle
13895                circular dependency (template/instantiate6.C). */
13896             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13897             type = check_var_type (DECL_NAME (r), type,
13898                                    DECL_SOURCE_LOCATION (r));
13899             if (DECL_HAS_VALUE_EXPR_P (t))
13900               {
13901                 tree ve = DECL_VALUE_EXPR (t);
13902                 ve = tsubst_expr (ve, args, complain, in_decl,
13903                                   /*constant_expression_p=*/false);
13904                 if (REFERENCE_REF_P (ve))
13905                   {
13906                     gcc_assert (TYPE_REF_P (type));
13907                     ve = TREE_OPERAND (ve, 0);
13908                   }
13909                 SET_DECL_VALUE_EXPR (r, ve);
13910               }
13911             if (CP_DECL_THREAD_LOCAL_P (r)
13912                 && !processing_template_decl)
13913               set_decl_tls_model (r, decl_default_tls_model (r));
13914           }
13915         else if (DECL_SELF_REFERENCE_P (t))
13916           SET_DECL_SELF_REFERENCE_P (r);
13917         TREE_TYPE (r) = type;
13918         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13919         DECL_CONTEXT (r) = ctx;
13920         /* Clear out the mangled name and RTL for the instantiation.  */
13921         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13922         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13923           SET_DECL_RTL (r, NULL);
13924         /* The initializer must not be expanded until it is required;
13925            see [temp.inst].  */
13926         DECL_INITIAL (r) = NULL_TREE;
13927         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13928         if (VAR_P (r))
13929           {
13930             if (DECL_LANG_SPECIFIC (r))
13931               SET_DECL_DEPENDENT_INIT_P (r, false);
13932
13933             SET_DECL_MODE (r, VOIDmode);
13934
13935             /* Possibly limit visibility based on template args.  */
13936             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13937             if (DECL_VISIBILITY_SPECIFIED (t))
13938               {
13939                 DECL_VISIBILITY_SPECIFIED (r) = 0;
13940                 DECL_ATTRIBUTES (r)
13941                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13942               }
13943             determine_visibility (r);
13944           }
13945
13946         if (!local_p)
13947           {
13948             /* A static data member declaration is always marked
13949                external when it is declared in-class, even if an
13950                initializer is present.  We mimic the non-template
13951                processing here.  */
13952             DECL_EXTERNAL (r) = 1;
13953             if (DECL_NAMESPACE_SCOPE_P (t))
13954               DECL_NOT_REALLY_EXTERN (r) = 1;
13955
13956             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13957             SET_DECL_IMPLICIT_INSTANTIATION (r);
13958             /* Remember whether we require constant initialization of
13959                a non-constant template variable.  */
13960             TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (r))
13961               = TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (t));
13962             if (!error_operand_p (r) || (complain & tf_error))
13963               register_specialization (r, gen_tmpl, argvec, false, hash);
13964           }
13965         else
13966           {
13967             if (DECL_LANG_SPECIFIC (r))
13968               DECL_TEMPLATE_INFO (r) = NULL_TREE;
13969             if (!cp_unevaluated_operand)
13970               register_local_specialization (r, t);
13971           }
13972
13973         DECL_CHAIN (r) = NULL_TREE;
13974
13975         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13976                                         /*flags=*/0,
13977                                         args, complain, in_decl);
13978
13979         /* Preserve a typedef that names a type.  */
13980         if (is_typedef_decl (r) && type != error_mark_node)
13981           {
13982             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13983             set_underlying_type (r);
13984             if (TYPE_DECL_ALIAS_P (r))
13985               /* An alias template specialization can be dependent
13986                  even if its underlying type is not.  */
13987               TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13988           }
13989
13990         layout_decl (r, 0);
13991       }
13992       break;
13993
13994     default:
13995       gcc_unreachable ();
13996     }
13997 #undef RETURN
13998
13999  out:
14000   /* Restore the file and line information.  */
14001   input_location = saved_loc;
14002
14003   return r;
14004 }
14005
14006 /* Substitute into the ARG_TYPES of a function type.
14007    If END is a TREE_CHAIN, leave it and any following types
14008    un-substituted.  */
14009
14010 static tree
14011 tsubst_arg_types (tree arg_types,
14012                   tree args,
14013                   tree end,
14014                   tsubst_flags_t complain,
14015                   tree in_decl)
14016 {
14017   tree remaining_arg_types;
14018   tree type = NULL_TREE;
14019   int i = 1;
14020   tree expanded_args = NULL_TREE;
14021   tree default_arg;
14022
14023   if (!arg_types || arg_types == void_list_node || arg_types == end)
14024     return arg_types;
14025
14026   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
14027                                           args, end, complain, in_decl);
14028   if (remaining_arg_types == error_mark_node)
14029     return error_mark_node;
14030
14031   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
14032     {
14033       /* For a pack expansion, perform substitution on the
14034          entire expression. Later on, we'll handle the arguments
14035          one-by-one.  */
14036       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
14037                                             args, complain, in_decl);
14038
14039       if (TREE_CODE (expanded_args) == TREE_VEC)
14040         /* So that we'll spin through the parameters, one by one.  */
14041         i = TREE_VEC_LENGTH (expanded_args);
14042       else
14043         {
14044           /* We only partially substituted into the parameter
14045              pack. Our type is TYPE_PACK_EXPANSION.  */
14046           type = expanded_args;
14047           expanded_args = NULL_TREE;
14048         }
14049     }
14050
14051   while (i > 0) {
14052     --i;
14053
14054     if (expanded_args)
14055       type = TREE_VEC_ELT (expanded_args, i);
14056     else if (!type)
14057       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
14058
14059     if (type == error_mark_node)
14060       return error_mark_node;
14061     if (VOID_TYPE_P (type))
14062       {
14063         if (complain & tf_error)
14064           {
14065             error ("invalid parameter type %qT", type);
14066             if (in_decl)
14067               error ("in declaration %q+D", in_decl);
14068           }
14069         return error_mark_node;
14070     }
14071     /* DR 657. */
14072     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
14073       return error_mark_node;
14074
14075     /* Do array-to-pointer, function-to-pointer conversion, and ignore
14076        top-level qualifiers as required.  */
14077     type = cv_unqualified (type_decays_to (type));
14078
14079     /* We do not substitute into default arguments here.  The standard
14080        mandates that they be instantiated only when needed, which is
14081        done in build_over_call.  */
14082     default_arg = TREE_PURPOSE (arg_types);
14083
14084     /* Except that we do substitute default arguments under tsubst_lambda_expr,
14085        since the new op() won't have any associated template arguments for us
14086        to refer to later.  */
14087     if (lambda_fn_in_template_p (in_decl))
14088       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
14089                                            false/*fn*/, false/*constexpr*/);
14090
14091     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
14092       {
14093         /* We've instantiated a template before its default arguments
14094            have been parsed.  This can happen for a nested template
14095            class, and is not an error unless we require the default
14096            argument in a call of this function.  */
14097         remaining_arg_types = 
14098           tree_cons (default_arg, type, remaining_arg_types);
14099         vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
14100                        remaining_arg_types);
14101       }
14102     else
14103       remaining_arg_types =
14104         hash_tree_cons (default_arg, type, remaining_arg_types);
14105   }
14106
14107   return remaining_arg_types;
14108 }
14109
14110 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
14111    *not* handle the exception-specification for FNTYPE, because the
14112    initial substitution of explicitly provided template parameters
14113    during argument deduction forbids substitution into the
14114    exception-specification:
14115
14116      [temp.deduct]
14117
14118      All references in the function type of the function template to  the
14119      corresponding template parameters are replaced by the specified tem-
14120      plate argument values.  If a substitution in a template parameter or
14121      in  the function type of the function template results in an invalid
14122      type, type deduction fails.  [Note: The equivalent  substitution  in
14123      exception specifications is done only when the function is instanti-
14124      ated, at which point a program is  ill-formed  if  the  substitution
14125      results in an invalid type.]  */
14126
14127 static tree
14128 tsubst_function_type (tree t,
14129                       tree args,
14130                       tsubst_flags_t complain,
14131                       tree in_decl)
14132 {
14133   tree return_type;
14134   tree arg_types = NULL_TREE;
14135   tree fntype;
14136
14137   /* The TYPE_CONTEXT is not used for function/method types.  */
14138   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14139
14140   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14141      failure.  */
14142   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14143
14144   if (late_return_type_p)
14145     {
14146       /* Substitute the argument types.  */
14147       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14148                                     complain, in_decl);
14149       if (arg_types == error_mark_node)
14150         return error_mark_node;
14151
14152       tree save_ccp = current_class_ptr;
14153       tree save_ccr = current_class_ref;
14154       tree this_type = (TREE_CODE (t) == METHOD_TYPE
14155                         ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14156       bool do_inject = this_type && CLASS_TYPE_P (this_type);
14157       if (do_inject)
14158         {
14159           /* DR 1207: 'this' is in scope in the trailing return type.  */
14160           inject_this_parameter (this_type, cp_type_quals (this_type));
14161         }
14162
14163       /* Substitute the return type.  */
14164       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14165
14166       if (do_inject)
14167         {
14168           current_class_ptr = save_ccp;
14169           current_class_ref = save_ccr;
14170         }
14171     }
14172   else
14173     /* Substitute the return type.  */
14174     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14175
14176   if (return_type == error_mark_node)
14177     return error_mark_node;
14178   /* DR 486 clarifies that creation of a function type with an
14179      invalid return type is a deduction failure.  */
14180   if (TREE_CODE (return_type) == ARRAY_TYPE
14181       || TREE_CODE (return_type) == FUNCTION_TYPE)
14182     {
14183       if (complain & tf_error)
14184         {
14185           if (TREE_CODE (return_type) == ARRAY_TYPE)
14186             error ("function returning an array");
14187           else
14188             error ("function returning a function");
14189         }
14190       return error_mark_node;
14191     }
14192   /* And DR 657. */
14193   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14194     return error_mark_node;
14195
14196   if (!late_return_type_p)
14197     {
14198       /* Substitute the argument types.  */
14199       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14200                                     complain, in_decl);
14201       if (arg_types == error_mark_node)
14202         return error_mark_node;
14203     }
14204
14205   /* Construct a new type node and return it.  */
14206   if (TREE_CODE (t) == FUNCTION_TYPE)
14207     {
14208       fntype = build_function_type (return_type, arg_types);
14209       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
14210     }
14211   else
14212     {
14213       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14214       /* Don't pick up extra function qualifiers from the basetype.  */
14215       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14216       if (! MAYBE_CLASS_TYPE_P (r))
14217         {
14218           /* [temp.deduct]
14219
14220              Type deduction may fail for any of the following
14221              reasons:
14222
14223              -- Attempting to create "pointer to member of T" when T
14224              is not a class type.  */
14225           if (complain & tf_error)
14226             error ("creating pointer to member function of non-class type %qT",
14227                       r);
14228           return error_mark_node;
14229         }
14230
14231       fntype = build_method_type_directly (r, return_type,
14232                                            TREE_CHAIN (arg_types));
14233     }
14234   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14235
14236   /* See comment above.  */
14237   tree raises = NULL_TREE;
14238   cp_ref_qualifier rqual = type_memfn_rqual (t);
14239   fntype = build_cp_fntype_variant (fntype, rqual, raises, late_return_type_p);
14240
14241   return fntype;
14242 }
14243
14244 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14245    ARGS into that specification, and return the substituted
14246    specification.  If there is no specification, return NULL_TREE.  */
14247
14248 static tree
14249 tsubst_exception_specification (tree fntype,
14250                                 tree args,
14251                                 tsubst_flags_t complain,
14252                                 tree in_decl,
14253                                 bool defer_ok)
14254 {
14255   tree specs;
14256   tree new_specs;
14257
14258   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14259   new_specs = NULL_TREE;
14260   if (specs && TREE_PURPOSE (specs))
14261     {
14262       /* A noexcept-specifier.  */
14263       tree expr = TREE_PURPOSE (specs);
14264       if (TREE_CODE (expr) == INTEGER_CST)
14265         new_specs = expr;
14266       else if (defer_ok)
14267         {
14268           /* Defer instantiation of noexcept-specifiers to avoid
14269              excessive instantiations (c++/49107).  */
14270           new_specs = make_node (DEFERRED_NOEXCEPT);
14271           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14272             {
14273               /* We already partially instantiated this member template,
14274                  so combine the new args with the old.  */
14275               DEFERRED_NOEXCEPT_PATTERN (new_specs)
14276                 = DEFERRED_NOEXCEPT_PATTERN (expr);
14277               DEFERRED_NOEXCEPT_ARGS (new_specs)
14278                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14279             }
14280           else
14281             {
14282               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14283               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14284             }
14285         }
14286       else
14287         {
14288           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14289             {
14290               args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
14291                                            args);
14292               expr = DEFERRED_NOEXCEPT_PATTERN (expr);
14293             }
14294           new_specs = tsubst_copy_and_build
14295             (expr, args, complain, in_decl, /*function_p=*/false,
14296              /*integral_constant_expression_p=*/true);
14297         }
14298       new_specs = build_noexcept_spec (new_specs, complain);
14299     }
14300   else if (specs)
14301     {
14302       if (! TREE_VALUE (specs))
14303         new_specs = specs;
14304       else
14305         while (specs)
14306           {
14307             tree spec;
14308             int i, len = 1;
14309             tree expanded_specs = NULL_TREE;
14310
14311             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14312               {
14313                 /* Expand the pack expansion type.  */
14314                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14315                                                        args, complain,
14316                                                        in_decl);
14317
14318                 if (expanded_specs == error_mark_node)
14319                   return error_mark_node;
14320                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
14321                   len = TREE_VEC_LENGTH (expanded_specs);
14322                 else
14323                   {
14324                     /* We're substituting into a member template, so
14325                        we got a TYPE_PACK_EXPANSION back.  Add that
14326                        expansion and move on.  */
14327                     gcc_assert (TREE_CODE (expanded_specs)
14328                                 == TYPE_PACK_EXPANSION);
14329                     new_specs = add_exception_specifier (new_specs,
14330                                                          expanded_specs,
14331                                                          complain);
14332                     specs = TREE_CHAIN (specs);
14333                     continue;
14334                   }
14335               }
14336
14337             for (i = 0; i < len; ++i)
14338               {
14339                 if (expanded_specs)
14340                   spec = TREE_VEC_ELT (expanded_specs, i);
14341                 else
14342                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14343                 if (spec == error_mark_node)
14344                   return spec;
14345                 new_specs = add_exception_specifier (new_specs, spec, 
14346                                                      complain);
14347               }
14348
14349             specs = TREE_CHAIN (specs);
14350           }
14351     }
14352   return new_specs;
14353 }
14354
14355 /* Take the tree structure T and replace template parameters used
14356    therein with the argument vector ARGS.  IN_DECL is an associated
14357    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
14358    Issue error and warning messages under control of COMPLAIN.  Note
14359    that we must be relatively non-tolerant of extensions here, in
14360    order to preserve conformance; if we allow substitutions that
14361    should not be allowed, we may allow argument deductions that should
14362    not succeed, and therefore report ambiguous overload situations
14363    where there are none.  In theory, we could allow the substitution,
14364    but indicate that it should have failed, and allow our caller to
14365    make sure that the right thing happens, but we don't try to do this
14366    yet.
14367
14368    This function is used for dealing with types, decls and the like;
14369    for expressions, use tsubst_expr or tsubst_copy.  */
14370
14371 tree
14372 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14373 {
14374   enum tree_code code;
14375   tree type, r = NULL_TREE;
14376
14377   if (t == NULL_TREE || t == error_mark_node
14378       || t == integer_type_node
14379       || t == void_type_node
14380       || t == char_type_node
14381       || t == unknown_type_node
14382       || TREE_CODE (t) == NAMESPACE_DECL
14383       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14384     return t;
14385
14386   if (DECL_P (t))
14387     return tsubst_decl (t, args, complain);
14388
14389   if (args == NULL_TREE)
14390     return t;
14391
14392   code = TREE_CODE (t);
14393
14394   if (code == IDENTIFIER_NODE)
14395     type = IDENTIFIER_TYPE_VALUE (t);
14396   else
14397     type = TREE_TYPE (t);
14398
14399   gcc_assert (type != unknown_type_node);
14400
14401   /* Reuse typedefs.  We need to do this to handle dependent attributes,
14402      such as attribute aligned.  */
14403   if (TYPE_P (t)
14404       && typedef_variant_p (t))
14405     {
14406       tree decl = TYPE_NAME (t);
14407
14408       if (alias_template_specialization_p (t))
14409         {
14410           /* DECL represents an alias template and we want to
14411              instantiate it.  */
14412           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14413           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14414           r = instantiate_alias_template (tmpl, gen_args, complain);
14415         }
14416       else if (DECL_CLASS_SCOPE_P (decl)
14417                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14418                && uses_template_parms (DECL_CONTEXT (decl)))
14419         {
14420           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14421           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14422           r = retrieve_specialization (tmpl, gen_args, 0);
14423         }
14424       else if (DECL_FUNCTION_SCOPE_P (decl)
14425                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14426                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14427         r = retrieve_local_specialization (decl);
14428       else
14429         /* The typedef is from a non-template context.  */
14430         return t;
14431
14432       if (r)
14433         {
14434           r = TREE_TYPE (r);
14435           r = cp_build_qualified_type_real
14436             (r, cp_type_quals (t) | cp_type_quals (r),
14437              complain | tf_ignore_bad_quals);
14438           return r;
14439         }
14440       else
14441         {
14442           /* We don't have an instantiation yet, so drop the typedef.  */
14443           int quals = cp_type_quals (t);
14444           t = DECL_ORIGINAL_TYPE (decl);
14445           t = cp_build_qualified_type_real (t, quals,
14446                                             complain | tf_ignore_bad_quals);
14447         }
14448     }
14449
14450   bool fndecl_type = (complain & tf_fndecl_type);
14451   complain &= ~tf_fndecl_type;
14452
14453   if (type
14454       && code != TYPENAME_TYPE
14455       && code != TEMPLATE_TYPE_PARM
14456       && code != TEMPLATE_PARM_INDEX
14457       && code != IDENTIFIER_NODE
14458       && code != FUNCTION_TYPE
14459       && code != METHOD_TYPE)
14460     type = tsubst (type, args, complain, in_decl);
14461   if (type == error_mark_node)
14462     return error_mark_node;
14463
14464   switch (code)
14465     {
14466     case RECORD_TYPE:
14467     case UNION_TYPE:
14468     case ENUMERAL_TYPE:
14469       return tsubst_aggr_type (t, args, complain, in_decl,
14470                                /*entering_scope=*/0);
14471
14472     case ERROR_MARK:
14473     case IDENTIFIER_NODE:
14474     case VOID_TYPE:
14475     case REAL_TYPE:
14476     case COMPLEX_TYPE:
14477     case VECTOR_TYPE:
14478     case BOOLEAN_TYPE:
14479     case NULLPTR_TYPE:
14480     case LANG_TYPE:
14481       return t;
14482
14483     case INTEGER_TYPE:
14484       if (t == integer_type_node)
14485         return t;
14486
14487       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14488           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14489         return t;
14490
14491       {
14492         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14493
14494         max = tsubst_expr (omax, args, complain, in_decl,
14495                            /*integral_constant_expression_p=*/false);
14496
14497         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14498            needed.  */
14499         if (TREE_CODE (max) == NOP_EXPR
14500             && TREE_SIDE_EFFECTS (omax)
14501             && !TREE_TYPE (max))
14502           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14503
14504         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
14505            with TREE_SIDE_EFFECTS that indicates this is not an integral
14506            constant expression.  */
14507         if (processing_template_decl
14508             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14509           {
14510             gcc_assert (TREE_CODE (max) == NOP_EXPR);
14511             TREE_SIDE_EFFECTS (max) = 1;
14512           }
14513
14514         return compute_array_index_type (NULL_TREE, max, complain);
14515       }
14516
14517     case TEMPLATE_TYPE_PARM:
14518     case TEMPLATE_TEMPLATE_PARM:
14519     case BOUND_TEMPLATE_TEMPLATE_PARM:
14520     case TEMPLATE_PARM_INDEX:
14521       {
14522         int idx;
14523         int level;
14524         int levels;
14525         tree arg = NULL_TREE;
14526
14527         /* Early in template argument deduction substitution, we don't
14528            want to reduce the level of 'auto', or it will be confused
14529            with a normal template parm in subsequent deduction.  */
14530         if (is_auto (t) && (complain & tf_partial))
14531           return t;
14532
14533         r = NULL_TREE;
14534
14535         gcc_assert (TREE_VEC_LENGTH (args) > 0);
14536         template_parm_level_and_index (t, &level, &idx);
14537
14538         levels = TMPL_ARGS_DEPTH (args);
14539         if (level <= levels
14540             && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14541           {
14542             arg = TMPL_ARG (args, level, idx);
14543
14544             /* See through ARGUMENT_PACK_SELECT arguments. */
14545             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14546               arg = argument_pack_select_arg (arg);
14547           }
14548
14549         if (arg == error_mark_node)
14550           return error_mark_node;
14551         else if (arg != NULL_TREE)
14552           {
14553             if (ARGUMENT_PACK_P (arg))
14554               /* If ARG is an argument pack, we don't actually want to
14555                  perform a substitution here, because substitutions
14556                  for argument packs are only done
14557                  element-by-element. We can get to this point when
14558                  substituting the type of a non-type template
14559                  parameter pack, when that type actually contains
14560                  template parameter packs from an outer template, e.g.,
14561
14562                  template<typename... Types> struct A {
14563                    template<Types... Values> struct B { };
14564                  };  */
14565               return t;
14566
14567             if (code == TEMPLATE_TYPE_PARM)
14568               {
14569                 int quals;
14570                 gcc_assert (TYPE_P (arg));
14571
14572                 quals = cp_type_quals (arg) | cp_type_quals (t);
14573
14574                 return cp_build_qualified_type_real
14575                   (arg, quals, complain | tf_ignore_bad_quals);
14576               }
14577             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14578               {
14579                 /* We are processing a type constructed from a
14580                    template template parameter.  */
14581                 tree argvec = tsubst (TYPE_TI_ARGS (t),
14582                                       args, complain, in_decl);
14583                 if (argvec == error_mark_node)
14584                   return error_mark_node;
14585
14586                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14587                             || TREE_CODE (arg) == TEMPLATE_DECL
14588                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14589
14590                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14591                   /* Consider this code:
14592
14593                         template <template <class> class Template>
14594                         struct Internal {
14595                         template <class Arg> using Bind = Template<Arg>;
14596                         };
14597
14598                         template <template <class> class Template, class Arg>
14599                         using Instantiate = Template<Arg>; //#0
14600
14601                         template <template <class> class Template,
14602                                   class Argument>
14603                         using Bind =
14604                           Instantiate<Internal<Template>::template Bind,
14605                                       Argument>; //#1
14606
14607                      When #1 is parsed, the
14608                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
14609                      parameter `Template' in #0 matches the
14610                      UNBOUND_CLASS_TEMPLATE representing the argument
14611                      `Internal<Template>::template Bind'; We then want
14612                      to assemble the type `Bind<Argument>' that can't
14613                      be fully created right now, because
14614                      `Internal<Template>' not being complete, the Bind
14615                      template cannot be looked up in that context.  So
14616                      we need to "store" `Bind<Argument>' for later
14617                      when the context of Bind becomes complete.  Let's
14618                      store that in a TYPENAME_TYPE.  */
14619                   return make_typename_type (TYPE_CONTEXT (arg),
14620                                              build_nt (TEMPLATE_ID_EXPR,
14621                                                        TYPE_IDENTIFIER (arg),
14622                                                        argvec),
14623                                              typename_type,
14624                                              complain);
14625
14626                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
14627                    are resolving nested-types in the signature of a
14628                    member function templates.  Otherwise ARG is a
14629                    TEMPLATE_DECL and is the real template to be
14630                    instantiated.  */
14631                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14632                   arg = TYPE_NAME (arg);
14633
14634                 r = lookup_template_class (arg,
14635                                            argvec, in_decl,
14636                                            DECL_CONTEXT (arg),
14637                                             /*entering_scope=*/0,
14638                                            complain);
14639                 return cp_build_qualified_type_real
14640                   (r, cp_type_quals (t) | cp_type_quals (r), complain);
14641               }
14642             else if (code == TEMPLATE_TEMPLATE_PARM)
14643               return arg;
14644             else
14645               /* TEMPLATE_PARM_INDEX.  */
14646               return convert_from_reference (unshare_expr (arg));
14647           }
14648
14649         if (level == 1)
14650           /* This can happen during the attempted tsubst'ing in
14651              unify.  This means that we don't yet have any information
14652              about the template parameter in question.  */
14653           return t;
14654
14655         /* If we get here, we must have been looking at a parm for a
14656            more deeply nested template.  Make a new version of this
14657            template parameter, but with a lower level.  */
14658         switch (code)
14659           {
14660           case TEMPLATE_TYPE_PARM:
14661           case TEMPLATE_TEMPLATE_PARM:
14662           case BOUND_TEMPLATE_TEMPLATE_PARM:
14663             if (cp_type_quals (t))
14664               {
14665                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14666                 r = cp_build_qualified_type_real
14667                   (r, cp_type_quals (t),
14668                    complain | (code == TEMPLATE_TYPE_PARM
14669                                ? tf_ignore_bad_quals : 0));
14670               }
14671             else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14672                      && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14673                      && (r = (TEMPLATE_PARM_DESCENDANTS
14674                               (TEMPLATE_TYPE_PARM_INDEX (t))))
14675                      && (r = TREE_TYPE (r))
14676                      && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14677               /* Break infinite recursion when substituting the constraints
14678                  of a constrained placeholder.  */;
14679             else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14680                      && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
14681                      && !CLASS_PLACEHOLDER_TEMPLATE (t)
14682                      && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
14683                          r = TEMPLATE_PARM_DESCENDANTS (arg))
14684                      && (TEMPLATE_PARM_LEVEL (r)
14685                          == TEMPLATE_PARM_LEVEL (arg) - levels))
14686                 /* Cache the simple case of lowering a type parameter.  */
14687               r = TREE_TYPE (r);
14688             else
14689               {
14690                 r = copy_type (t);
14691                 TEMPLATE_TYPE_PARM_INDEX (r)
14692                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14693                                                 r, levels, args, complain);
14694                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14695                 TYPE_MAIN_VARIANT (r) = r;
14696                 TYPE_POINTER_TO (r) = NULL_TREE;
14697                 TYPE_REFERENCE_TO (r) = NULL_TREE;
14698
14699                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14700                   {
14701                     /* Propagate constraints on placeholders.  */
14702                     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14703                       PLACEHOLDER_TYPE_CONSTRAINTS (r)
14704                         = tsubst_constraint (constr, args, complain, in_decl);
14705                     else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14706                       {
14707                         pl = tsubst_copy (pl, args, complain, in_decl);
14708                         CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14709                       }
14710                   }
14711
14712                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14713                   /* We have reduced the level of the template
14714                      template parameter, but not the levels of its
14715                      template parameters, so canonical_type_parameter
14716                      will not be able to find the canonical template
14717                      template parameter for this level. Thus, we
14718                      require structural equality checking to compare
14719                      TEMPLATE_TEMPLATE_PARMs. */
14720                   SET_TYPE_STRUCTURAL_EQUALITY (r);
14721                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14722                   SET_TYPE_STRUCTURAL_EQUALITY (r);
14723                 else
14724                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
14725
14726                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14727                   {
14728                     tree tinfo = TYPE_TEMPLATE_INFO (t);
14729                     /* We might need to substitute into the types of non-type
14730                        template parameters.  */
14731                     tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14732                                         complain, in_decl);
14733                     if (tmpl == error_mark_node)
14734                       return error_mark_node;
14735                     tree argvec = tsubst (TI_ARGS (tinfo), args,
14736                                           complain, in_decl);
14737                     if (argvec == error_mark_node)
14738                       return error_mark_node;
14739
14740                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14741                       = build_template_info (tmpl, argvec);
14742                   }
14743               }
14744             break;
14745
14746           case TEMPLATE_PARM_INDEX:
14747             /* OK, now substitute the type of the non-type parameter.  We
14748                couldn't do it earlier because it might be an auto parameter,
14749                and we wouldn't need to if we had an argument.  */
14750             type = tsubst (type, args, complain, in_decl);
14751             if (type == error_mark_node)
14752               return error_mark_node;
14753             r = reduce_template_parm_level (t, type, levels, args, complain);
14754             break;
14755
14756           default:
14757             gcc_unreachable ();
14758           }
14759
14760         return r;
14761       }
14762
14763     case TREE_LIST:
14764       {
14765         tree purpose, value, chain;
14766
14767         if (t == void_list_node)
14768           return t;
14769
14770         purpose = TREE_PURPOSE (t);
14771         if (purpose)
14772           {
14773             purpose = tsubst (purpose, args, complain, in_decl);
14774             if (purpose == error_mark_node)
14775               return error_mark_node;
14776           }
14777         value = TREE_VALUE (t);
14778         if (value)
14779           {
14780             value = tsubst (value, args, complain, in_decl);
14781             if (value == error_mark_node)
14782               return error_mark_node;
14783           }
14784         chain = TREE_CHAIN (t);
14785         if (chain && chain != void_type_node)
14786           {
14787             chain = tsubst (chain, args, complain, in_decl);
14788             if (chain == error_mark_node)
14789               return error_mark_node;
14790           }
14791         if (purpose == TREE_PURPOSE (t)
14792             && value == TREE_VALUE (t)
14793             && chain == TREE_CHAIN (t))
14794           return t;
14795         return hash_tree_cons (purpose, value, chain);
14796       }
14797
14798     case TREE_BINFO:
14799       /* We should never be tsubsting a binfo.  */
14800       gcc_unreachable ();
14801
14802     case TREE_VEC:
14803       /* A vector of template arguments.  */
14804       gcc_assert (!type);
14805       return tsubst_template_args (t, args, complain, in_decl);
14806
14807     case POINTER_TYPE:
14808     case REFERENCE_TYPE:
14809       {
14810         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14811           return t;
14812
14813         /* [temp.deduct]
14814
14815            Type deduction may fail for any of the following
14816            reasons:
14817
14818            -- Attempting to create a pointer to reference type.
14819            -- Attempting to create a reference to a reference type or
14820               a reference to void.
14821
14822           Core issue 106 says that creating a reference to a reference
14823           during instantiation is no longer a cause for failure. We
14824           only enforce this check in strict C++98 mode.  */
14825         if ((TYPE_REF_P (type)
14826              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14827             || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14828           {
14829             static location_t last_loc;
14830
14831             /* We keep track of the last time we issued this error
14832                message to avoid spewing a ton of messages during a
14833                single bad template instantiation.  */
14834             if (complain & tf_error
14835                 && last_loc != input_location)
14836               {
14837                 if (VOID_TYPE_P (type))
14838                   error ("forming reference to void");
14839                else if (code == POINTER_TYPE)
14840                  error ("forming pointer to reference type %qT", type);
14841                else
14842                   error ("forming reference to reference type %qT", type);
14843                 last_loc = input_location;
14844               }
14845
14846             return error_mark_node;
14847           }
14848         else if (TREE_CODE (type) == FUNCTION_TYPE
14849                  && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14850                      || type_memfn_rqual (type) != REF_QUAL_NONE))
14851           {
14852             if (complain & tf_error)
14853               {
14854                 if (code == POINTER_TYPE)
14855                   error ("forming pointer to qualified function type %qT",
14856                          type);
14857                 else
14858                   error ("forming reference to qualified function type %qT",
14859                          type);
14860               }
14861             return error_mark_node;
14862           }
14863         else if (code == POINTER_TYPE)
14864           {
14865             r = build_pointer_type (type);
14866             if (TREE_CODE (type) == METHOD_TYPE)
14867               r = build_ptrmemfunc_type (r);
14868           }
14869         else if (TYPE_REF_P (type))
14870           /* In C++0x, during template argument substitution, when there is an
14871              attempt to create a reference to a reference type, reference
14872              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14873
14874              "If a template-argument for a template-parameter T names a type
14875              that is a reference to a type A, an attempt to create the type
14876              'lvalue reference to cv T' creates the type 'lvalue reference to
14877              A,' while an attempt to create the type type rvalue reference to
14878              cv T' creates the type T"
14879           */
14880           r = cp_build_reference_type
14881               (TREE_TYPE (type),
14882                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14883         else
14884           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14885         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14886
14887         if (r != error_mark_node)
14888           /* Will this ever be needed for TYPE_..._TO values?  */
14889           layout_type (r);
14890
14891         return r;
14892       }
14893     case OFFSET_TYPE:
14894       {
14895         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14896         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14897           {
14898             /* [temp.deduct]
14899
14900                Type deduction may fail for any of the following
14901                reasons:
14902
14903                -- Attempting to create "pointer to member of T" when T
14904                   is not a class type.  */
14905             if (complain & tf_error)
14906               error ("creating pointer to member of non-class type %qT", r);
14907             return error_mark_node;
14908           }
14909         if (TYPE_REF_P (type))
14910           {
14911             if (complain & tf_error)
14912               error ("creating pointer to member reference type %qT", type);
14913             return error_mark_node;
14914           }
14915         if (VOID_TYPE_P (type))
14916           {
14917             if (complain & tf_error)
14918               error ("creating pointer to member of type void");
14919             return error_mark_node;
14920           }
14921         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14922         if (TREE_CODE (type) == FUNCTION_TYPE)
14923           {
14924             /* The type of the implicit object parameter gets its
14925                cv-qualifiers from the FUNCTION_TYPE. */
14926             tree memptr;
14927             tree method_type
14928               = build_memfn_type (type, r, type_memfn_quals (type),
14929                                   type_memfn_rqual (type));
14930             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14931             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14932                                                  complain);
14933           }
14934         else
14935           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14936                                                cp_type_quals (t),
14937                                                complain);
14938       }
14939     case FUNCTION_TYPE:
14940     case METHOD_TYPE:
14941       {
14942         tree fntype;
14943         tree specs;
14944         fntype = tsubst_function_type (t, args, complain, in_decl);
14945         if (fntype == error_mark_node)
14946           return error_mark_node;
14947
14948         /* Substitute the exception specification.  */
14949         specs = tsubst_exception_specification (t, args, complain, in_decl,
14950                                                 /*defer_ok*/fndecl_type);
14951         if (specs == error_mark_node)
14952           return error_mark_node;
14953         if (specs)
14954           fntype = build_exception_variant (fntype, specs);
14955         return fntype;
14956       }
14957     case ARRAY_TYPE:
14958       {
14959         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14960         if (domain == error_mark_node)
14961           return error_mark_node;
14962
14963         /* As an optimization, we avoid regenerating the array type if
14964            it will obviously be the same as T.  */
14965         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14966           return t;
14967
14968         /* These checks should match the ones in create_array_type_for_decl.
14969
14970            [temp.deduct]
14971
14972            The deduction may fail for any of the following reasons:
14973
14974            -- Attempting to create an array with an element type that
14975               is void, a function type, or a reference type, or [DR337]
14976               an abstract class type.  */
14977         if (VOID_TYPE_P (type)
14978             || TREE_CODE (type) == FUNCTION_TYPE
14979             || (TREE_CODE (type) == ARRAY_TYPE
14980                 && TYPE_DOMAIN (type) == NULL_TREE)
14981             || TYPE_REF_P (type))
14982           {
14983             if (complain & tf_error)
14984               error ("creating array of %qT", type);
14985             return error_mark_node;
14986           }
14987
14988         if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14989           return error_mark_node;
14990
14991         r = build_cplus_array_type (type, domain);
14992
14993         if (!valid_array_size_p (input_location, r, in_decl,
14994                                  (complain & tf_error)))
14995           return error_mark_node;
14996
14997         if (TYPE_USER_ALIGN (t))
14998           {
14999             SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
15000             TYPE_USER_ALIGN (r) = 1;
15001           }
15002
15003         return r;
15004       }
15005
15006     case TYPENAME_TYPE:
15007       {
15008         tree ctx = TYPE_CONTEXT (t);
15009         if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
15010           {
15011             ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
15012             if (ctx == error_mark_node
15013                 || TREE_VEC_LENGTH (ctx) > 1)
15014               return error_mark_node;
15015             if (TREE_VEC_LENGTH (ctx) == 0)
15016               {
15017                 if (complain & tf_error)
15018                   error ("%qD is instantiated for an empty pack",
15019                          TYPENAME_TYPE_FULLNAME (t));
15020                 return error_mark_node;
15021               }
15022             ctx = TREE_VEC_ELT (ctx, 0);
15023           }
15024         else
15025           ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
15026                                   /*entering_scope=*/1);
15027         if (ctx == error_mark_node)
15028           return error_mark_node;
15029
15030         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
15031                               complain, in_decl);
15032         if (f == error_mark_node)
15033           return error_mark_node;
15034
15035         if (!MAYBE_CLASS_TYPE_P (ctx))
15036           {
15037             if (complain & tf_error)
15038               error ("%qT is not a class, struct, or union type", ctx);
15039             return error_mark_node;
15040           }
15041         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
15042           {
15043             /* Normally, make_typename_type does not require that the CTX
15044                have complete type in order to allow things like:
15045
15046                  template <class T> struct S { typename S<T>::X Y; };
15047
15048                But, such constructs have already been resolved by this
15049                point, so here CTX really should have complete type, unless
15050                it's a partial instantiation.  */
15051             ctx = complete_type (ctx);
15052             if (!COMPLETE_TYPE_P (ctx))
15053               {
15054                 if (complain & tf_error)
15055                   cxx_incomplete_type_error (NULL_TREE, ctx);
15056                 return error_mark_node;
15057               }
15058           }
15059
15060         f = make_typename_type (ctx, f, typename_type,
15061                                 complain | tf_keep_type_decl);
15062         if (f == error_mark_node)
15063           return f;
15064         if (TREE_CODE (f) == TYPE_DECL)
15065           {
15066             complain |= tf_ignore_bad_quals;
15067             f = TREE_TYPE (f);
15068           }
15069
15070         if (TREE_CODE (f) != TYPENAME_TYPE)
15071           {
15072             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
15073               {
15074                 if (complain & tf_error)
15075                   error ("%qT resolves to %qT, which is not an enumeration type",
15076                          t, f);
15077                 else
15078                   return error_mark_node;
15079               }
15080             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
15081               {
15082                 if (complain & tf_error)
15083                   error ("%qT resolves to %qT, which is is not a class type",
15084                          t, f);
15085                 else
15086                   return error_mark_node;
15087               }
15088           }
15089
15090         return cp_build_qualified_type_real
15091           (f, cp_type_quals (f) | cp_type_quals (t), complain);
15092       }
15093
15094     case UNBOUND_CLASS_TEMPLATE:
15095       {
15096         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
15097                                      in_decl, /*entering_scope=*/1);
15098         tree name = TYPE_IDENTIFIER (t);
15099         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
15100
15101         if (ctx == error_mark_node || name == error_mark_node)
15102           return error_mark_node;
15103
15104         if (parm_list)
15105           parm_list = tsubst_template_parms (parm_list, args, complain);
15106         return make_unbound_class_template (ctx, name, parm_list, complain);
15107       }
15108
15109     case TYPEOF_TYPE:
15110       {
15111         tree type;
15112
15113         ++cp_unevaluated_operand;
15114         ++c_inhibit_evaluation_warnings;
15115
15116         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
15117                             complain, in_decl,
15118                             /*integral_constant_expression_p=*/false);
15119
15120         --cp_unevaluated_operand;
15121         --c_inhibit_evaluation_warnings;
15122
15123         type = finish_typeof (type);
15124         return cp_build_qualified_type_real (type,
15125                                              cp_type_quals (t)
15126                                              | cp_type_quals (type),
15127                                              complain);
15128       }
15129
15130     case DECLTYPE_TYPE:
15131       {
15132         tree type;
15133
15134         ++cp_unevaluated_operand;
15135         ++c_inhibit_evaluation_warnings;
15136
15137         type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
15138                                       complain|tf_decltype, in_decl,
15139                                       /*function_p*/false,
15140                                       /*integral_constant_expression*/false);
15141
15142         --cp_unevaluated_operand;
15143         --c_inhibit_evaluation_warnings;
15144
15145         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
15146           type = lambda_capture_field_type (type,
15147                                             false /*explicit_init*/,
15148                                             DECLTYPE_FOR_REF_CAPTURE (t));
15149         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
15150           type = lambda_proxy_type (type);
15151         else
15152           {
15153             bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
15154             if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
15155                 && EXPR_P (type))
15156               /* In a template ~id could be either a complement expression
15157                  or an unqualified-id naming a destructor; if instantiating
15158                  it produces an expression, it's not an id-expression or
15159                  member access.  */
15160               id = false;
15161             type = finish_decltype_type (type, id, complain);
15162           }
15163         return cp_build_qualified_type_real (type,
15164                                              cp_type_quals (t)
15165                                              | cp_type_quals (type),
15166                                              complain | tf_ignore_bad_quals);
15167       }
15168
15169     case UNDERLYING_TYPE:
15170       {
15171         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
15172                             complain, in_decl);
15173         return finish_underlying_type (type);
15174       }
15175
15176     case TYPE_ARGUMENT_PACK:
15177     case NONTYPE_ARGUMENT_PACK:
15178       {
15179         tree r;
15180
15181         if (code == NONTYPE_ARGUMENT_PACK)
15182           r = make_node (code);
15183         else
15184           r = cxx_make_type (code);
15185
15186         tree pack_args = ARGUMENT_PACK_ARGS (t);
15187         pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15188         SET_ARGUMENT_PACK_ARGS (r, pack_args);
15189
15190         return r;
15191       }
15192
15193     case VOID_CST:
15194     case INTEGER_CST:
15195     case REAL_CST:
15196     case STRING_CST:
15197     case PLUS_EXPR:
15198     case MINUS_EXPR:
15199     case NEGATE_EXPR:
15200     case NOP_EXPR:
15201     case INDIRECT_REF:
15202     case ADDR_EXPR:
15203     case CALL_EXPR:
15204     case ARRAY_REF:
15205     case SCOPE_REF:
15206       /* We should use one of the expression tsubsts for these codes.  */
15207       gcc_unreachable ();
15208
15209     default:
15210       sorry ("use of %qs in template", get_tree_code_name (code));
15211       return error_mark_node;
15212     }
15213 }
15214
15215 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
15216    expression on the left-hand side of the "." or "->" operator.  We
15217    only do the lookup if we had a dependent BASELINK.  Otherwise we
15218    adjust it onto the instantiated heirarchy.  */
15219
15220 static tree
15221 tsubst_baselink (tree baselink, tree object_type,
15222                  tree args, tsubst_flags_t complain, tree in_decl)
15223 {
15224   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15225   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15226   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15227
15228   tree optype = BASELINK_OPTYPE (baselink);
15229   optype = tsubst (optype, args, complain, in_decl);
15230
15231   tree template_args = NULL_TREE;
15232   bool template_id_p = false;
15233   tree fns = BASELINK_FUNCTIONS (baselink);
15234   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15235     {
15236       template_id_p = true;
15237       template_args = TREE_OPERAND (fns, 1);
15238       fns = TREE_OPERAND (fns, 0);
15239       if (template_args)
15240         template_args = tsubst_template_args (template_args, args,
15241                                               complain, in_decl);
15242     }
15243
15244   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15245   binfo_type = tsubst (binfo_type, args, complain, in_decl);
15246   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15247
15248   if (dependent_p)
15249     {
15250       tree name = OVL_NAME (fns);
15251       if (IDENTIFIER_CONV_OP_P (name))
15252         name = make_conv_op_name (optype);
15253
15254       if (name == complete_dtor_identifier)
15255         /* Treat as-if non-dependent below.  */
15256         dependent_p = false;
15257
15258       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15259       if (!baselink)
15260         {
15261           if ((complain & tf_error)
15262               && constructor_name_p (name, qualifying_scope))
15263             error ("cannot call constructor %<%T::%D%> directly",
15264                    qualifying_scope, name);
15265           return error_mark_node;
15266         }
15267
15268       if (BASELINK_P (baselink))
15269         fns = BASELINK_FUNCTIONS (baselink);
15270     }
15271   else
15272     /* We're going to overwrite pieces below, make a duplicate.  */
15273     baselink = copy_node (baselink);
15274
15275   /* If lookup found a single function, mark it as used at this point.
15276      (If lookup found multiple functions the one selected later by
15277      overload resolution will be marked as used at that point.)  */
15278   if (!template_id_p && !really_overloaded_fn (fns))
15279     {
15280       tree fn = OVL_FIRST (fns);
15281       bool ok = mark_used (fn, complain);
15282       if (!ok && !(complain & tf_error))
15283         return error_mark_node;
15284       if (ok && BASELINK_P (baselink))
15285         /* We might have instantiated an auto function.  */
15286         TREE_TYPE (baselink) = TREE_TYPE (fn);
15287     }
15288
15289   if (BASELINK_P (baselink))
15290     {
15291       /* Add back the template arguments, if present.  */
15292       if (template_id_p)
15293         BASELINK_FUNCTIONS (baselink)
15294           = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15295
15296       /* Update the conversion operator type.  */
15297       BASELINK_OPTYPE (baselink) = optype;
15298     }
15299
15300   if (!object_type)
15301     object_type = current_class_type;
15302
15303   if (qualified_p || !dependent_p)
15304     {
15305       baselink = adjust_result_of_qualified_name_lookup (baselink,
15306                                                          qualifying_scope,
15307                                                          object_type);
15308       if (!qualified_p)
15309         /* We need to call adjust_result_of_qualified_name_lookup in case the
15310            destructor names a base class, but we unset BASELINK_QUALIFIED_P
15311            so that we still get virtual function binding.  */
15312         BASELINK_QUALIFIED_P (baselink) = false;
15313     }
15314
15315   return baselink;
15316 }
15317
15318 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
15319    true if the qualified-id will be a postfix-expression in-and-of
15320    itself; false if more of the postfix-expression follows the
15321    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
15322    of "&".  */
15323
15324 static tree
15325 tsubst_qualified_id (tree qualified_id, tree args,
15326                      tsubst_flags_t complain, tree in_decl,
15327                      bool done, bool address_p)
15328 {
15329   tree expr;
15330   tree scope;
15331   tree name;
15332   bool is_template;
15333   tree template_args;
15334   location_t loc = UNKNOWN_LOCATION;
15335
15336   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15337
15338   /* Figure out what name to look up.  */
15339   name = TREE_OPERAND (qualified_id, 1);
15340   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15341     {
15342       is_template = true;
15343       loc = EXPR_LOCATION (name);
15344       template_args = TREE_OPERAND (name, 1);
15345       if (template_args)
15346         template_args = tsubst_template_args (template_args, args,
15347                                               complain, in_decl);
15348       if (template_args == error_mark_node)
15349         return error_mark_node;
15350       name = TREE_OPERAND (name, 0);
15351     }
15352   else
15353     {
15354       is_template = false;
15355       template_args = NULL_TREE;
15356     }
15357
15358   /* Substitute into the qualifying scope.  When there are no ARGS, we
15359      are just trying to simplify a non-dependent expression.  In that
15360      case the qualifying scope may be dependent, and, in any case,
15361      substituting will not help.  */
15362   scope = TREE_OPERAND (qualified_id, 0);
15363   if (args)
15364     {
15365       scope = tsubst (scope, args, complain, in_decl);
15366       expr = tsubst_copy (name, args, complain, in_decl);
15367     }
15368   else
15369     expr = name;
15370
15371   if (dependent_scope_p (scope))
15372     {
15373       if (is_template)
15374         expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15375       tree r = build_qualified_name (NULL_TREE, scope, expr,
15376                                      QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15377       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15378       return r;
15379     }
15380
15381   if (!BASELINK_P (name) && !DECL_P (expr))
15382     {
15383       if (TREE_CODE (expr) == BIT_NOT_EXPR)
15384         {
15385           /* A BIT_NOT_EXPR is used to represent a destructor.  */
15386           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15387             {
15388               error ("qualifying type %qT does not match destructor name ~%qT",
15389                      scope, TREE_OPERAND (expr, 0));
15390               expr = error_mark_node;
15391             }
15392           else
15393             expr = lookup_qualified_name (scope, complete_dtor_identifier,
15394                                           /*is_type_p=*/0, false);
15395         }
15396       else
15397         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15398       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15399                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15400         {
15401           if (complain & tf_error)
15402             {
15403               error ("dependent-name %qE is parsed as a non-type, but "
15404                      "instantiation yields a type", qualified_id);
15405               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15406             }
15407           return error_mark_node;
15408         }
15409     }
15410
15411   if (DECL_P (expr))
15412     {
15413       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15414                                            scope);
15415       /* Remember that there was a reference to this entity.  */
15416       if (!mark_used (expr, complain) && !(complain & tf_error))
15417         return error_mark_node;
15418     }
15419
15420   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15421     {
15422       if (complain & tf_error)
15423         qualified_name_lookup_error (scope,
15424                                      TREE_OPERAND (qualified_id, 1),
15425                                      expr, input_location);
15426       return error_mark_node;
15427     }
15428
15429   if (is_template)
15430     {
15431       /* We may be repeating a check already done during parsing, but
15432          if it was well-formed and passed then, it will pass again
15433          now, and if it didn't, we wouldn't have got here.  The case
15434          we want to catch is when we couldn't tell then, and can now,
15435          namely when templ prior to substitution was an
15436          identifier.  */
15437       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15438         return error_mark_node;
15439
15440       if (variable_template_p (expr))
15441         expr = lookup_and_finish_template_variable (expr, template_args,
15442                                                     complain);
15443       else
15444         expr = lookup_template_function (expr, template_args);
15445     }
15446
15447   if (expr == error_mark_node && complain & tf_error)
15448     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15449                                  expr, input_location);
15450   else if (TYPE_P (scope))
15451     {
15452       expr = (adjust_result_of_qualified_name_lookup
15453               (expr, scope, current_nonlambda_class_type ()));
15454       expr = (finish_qualified_id_expr
15455               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15456                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15457                /*template_arg_p=*/false, complain));
15458     }
15459
15460   /* Expressions do not generally have reference type.  */
15461   if (TREE_CODE (expr) != SCOPE_REF
15462       /* However, if we're about to form a pointer-to-member, we just
15463          want the referenced member referenced.  */
15464       && TREE_CODE (expr) != OFFSET_REF)
15465     expr = convert_from_reference (expr);
15466
15467   if (REF_PARENTHESIZED_P (qualified_id))
15468     expr = force_paren_expr (expr);
15469
15470   return expr;
15471 }
15472
15473 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
15474    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
15475    for tsubst.  */
15476
15477 static tree
15478 tsubst_init (tree init, tree decl, tree args,
15479              tsubst_flags_t complain, tree in_decl)
15480 {
15481   if (!init)
15482     return NULL_TREE;
15483
15484   init = tsubst_expr (init, args, complain, in_decl, false);
15485
15486   tree type = TREE_TYPE (decl);
15487
15488   if (!init && type != error_mark_node)
15489     {
15490       if (tree auto_node = type_uses_auto (type))
15491         {
15492           if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
15493             {
15494               if (complain & tf_error)
15495                 error ("initializer for %q#D expands to an empty list "
15496                        "of expressions", decl);
15497               return error_mark_node;
15498             }
15499         }
15500       else if (!dependent_type_p (type))
15501         {
15502           /* If we had an initializer but it
15503              instantiated to nothing,
15504              value-initialize the object.  This will
15505              only occur when the initializer was a
15506              pack expansion where the parameter packs
15507              used in that expansion were of length
15508              zero.  */
15509           init = build_value_init (type, complain);
15510           if (TREE_CODE (init) == AGGR_INIT_EXPR)
15511             init = get_target_expr_sfinae (init, complain);
15512           if (TREE_CODE (init) == TARGET_EXPR)
15513             TARGET_EXPR_DIRECT_INIT_P (init) = true;
15514         }
15515     }
15516
15517   return init;
15518 }
15519
15520 /* Like tsubst, but deals with expressions.  This function just replaces
15521    template parms; to finish processing the resultant expression, use
15522    tsubst_copy_and_build or tsubst_expr.  */
15523
15524 static tree
15525 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15526 {
15527   enum tree_code code;
15528   tree r;
15529
15530   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15531     return t;
15532
15533   code = TREE_CODE (t);
15534
15535   switch (code)
15536     {
15537     case PARM_DECL:
15538       r = retrieve_local_specialization (t);
15539
15540       if (r == NULL_TREE)
15541         {
15542           /* We get here for a use of 'this' in an NSDMI.  */
15543           if (DECL_NAME (t) == this_identifier && current_class_ptr)
15544             return current_class_ptr;
15545
15546           /* This can happen for a parameter name used later in a function
15547              declaration (such as in a late-specified return type).  Just
15548              make a dummy decl, since it's only used for its type.  */
15549           gcc_assert (cp_unevaluated_operand != 0);
15550           r = tsubst_decl (t, args, complain);
15551           /* Give it the template pattern as its context; its true context
15552              hasn't been instantiated yet and this is good enough for
15553              mangling.  */
15554           DECL_CONTEXT (r) = DECL_CONTEXT (t);
15555         }
15556
15557       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15558         r = argument_pack_select_arg (r);
15559       if (!mark_used (r, complain) && !(complain & tf_error))
15560         return error_mark_node;
15561       return r;
15562
15563     case CONST_DECL:
15564       {
15565         tree enum_type;
15566         tree v;
15567
15568         if (DECL_TEMPLATE_PARM_P (t))
15569           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15570         /* There is no need to substitute into namespace-scope
15571            enumerators.  */
15572         if (DECL_NAMESPACE_SCOPE_P (t))
15573           return t;
15574         /* If ARGS is NULL, then T is known to be non-dependent.  */
15575         if (args == NULL_TREE)
15576           return scalar_constant_value (t);
15577
15578         /* Unfortunately, we cannot just call lookup_name here.
15579            Consider:
15580
15581              template <int I> int f() {
15582              enum E { a = I };
15583              struct S { void g() { E e = a; } };
15584              };
15585
15586            When we instantiate f<7>::S::g(), say, lookup_name is not
15587            clever enough to find f<7>::a.  */
15588         enum_type
15589           = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15590                               /*entering_scope=*/0);
15591
15592         for (v = TYPE_VALUES (enum_type);
15593              v != NULL_TREE;
15594              v = TREE_CHAIN (v))
15595           if (TREE_PURPOSE (v) == DECL_NAME (t))
15596             return TREE_VALUE (v);
15597
15598           /* We didn't find the name.  That should never happen; if
15599              name-lookup found it during preliminary parsing, we
15600              should find it again here during instantiation.  */
15601         gcc_unreachable ();
15602       }
15603       return t;
15604
15605     case FIELD_DECL:
15606       if (DECL_CONTEXT (t))
15607         {
15608           tree ctx;
15609
15610           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15611                                   /*entering_scope=*/1);
15612           if (ctx != DECL_CONTEXT (t))
15613             {
15614               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15615               if (!r)
15616                 {
15617                   if (complain & tf_error)
15618                     error ("using invalid field %qD", t);
15619                   return error_mark_node;
15620                 }
15621               return r;
15622             }
15623         }
15624
15625       return t;
15626
15627     case VAR_DECL:
15628     case FUNCTION_DECL:
15629       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15630         r = tsubst (t, args, complain, in_decl);
15631       else if (local_variable_p (t)
15632                && uses_template_parms (DECL_CONTEXT (t)))
15633         {
15634           r = retrieve_local_specialization (t);
15635           if (r == NULL_TREE)
15636             {
15637               /* First try name lookup to find the instantiation.  */
15638               r = lookup_name (DECL_NAME (t));
15639               if (r)
15640                 {
15641                   if (!VAR_P (r))
15642                     {
15643                       /* During error-recovery we may find a non-variable,
15644                          even an OVERLOAD: just bail out and avoid ICEs and
15645                          duplicate diagnostics (c++/62207).  */
15646                       gcc_assert (seen_error ());
15647                       return error_mark_node;
15648                     }
15649                   if (!is_capture_proxy (r))
15650                     {
15651                       /* Make sure the one we found is the one we want.  */
15652                       tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15653                       if (ctx != DECL_CONTEXT (r))
15654                         r = NULL_TREE;
15655                     }
15656                 }
15657
15658               if (r)
15659                 /* OK */;
15660               else
15661                 {
15662                   /* This can happen for a variable used in a
15663                      late-specified return type of a local lambda, or for a
15664                      local static or constant.  Building a new VAR_DECL
15665                      should be OK in all those cases.  */
15666                   r = tsubst_decl (t, args, complain);
15667                   if (local_specializations)
15668                     /* Avoid infinite recursion (79640).  */
15669                     register_local_specialization (r, t);
15670                   if (decl_maybe_constant_var_p (r))
15671                     {
15672                       /* We can't call cp_finish_decl, so handle the
15673                          initializer by hand.  */
15674                       tree init = tsubst_init (DECL_INITIAL (t), r, args,
15675                                                complain, in_decl);
15676                       if (!processing_template_decl)
15677                         init = maybe_constant_init (init);
15678                       if (processing_template_decl
15679                           ? potential_constant_expression (init)
15680                           : reduced_constant_expression_p (init))
15681                         DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15682                           = TREE_CONSTANT (r) = true;
15683                       DECL_INITIAL (r) = init;
15684                       if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15685                         TREE_TYPE (r)
15686                           = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15687                                                complain, adc_variable_type);
15688                     }
15689                   gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15690                               || decl_constant_var_p (r)
15691                               || seen_error ());
15692                   if (!processing_template_decl
15693                       && !TREE_STATIC (r))
15694                     r = process_outer_var_ref (r, complain);
15695                 }
15696               /* Remember this for subsequent uses.  */
15697               if (local_specializations)
15698                 register_local_specialization (r, t);
15699             }
15700           if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15701             r = argument_pack_select_arg (r);
15702         }
15703       else
15704         r = t;
15705       if (!mark_used (r, complain))
15706         return error_mark_node;
15707       return r;
15708
15709     case NAMESPACE_DECL:
15710       return t;
15711
15712     case OVERLOAD:
15713       return t;
15714
15715     case BASELINK:
15716       return tsubst_baselink (t, current_nonlambda_class_type (),
15717                               args, complain, in_decl);
15718
15719     case TEMPLATE_DECL:
15720       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15721         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15722                        args, complain, in_decl);
15723       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15724         return tsubst (t, args, complain, in_decl);
15725       else if (DECL_CLASS_SCOPE_P (t)
15726                && uses_template_parms (DECL_CONTEXT (t)))
15727         {
15728           /* Template template argument like the following example need
15729              special treatment:
15730
15731                template <template <class> class TT> struct C {};
15732                template <class T> struct D {
15733                  template <class U> struct E {};
15734                  C<E> c;                                // #1
15735                };
15736                D<int> d;                                // #2
15737
15738              We are processing the template argument `E' in #1 for
15739              the template instantiation #2.  Originally, `E' is a
15740              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
15741              have to substitute this with one having context `D<int>'.  */
15742
15743           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15744           if (dependent_scope_p (context))
15745             {
15746               /* When rewriting a constructor into a deduction guide, a
15747                  non-dependent name can become dependent, so memtmpl<args>
15748                  becomes context::template memtmpl<args>.  */
15749               tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15750               return build_qualified_name (type, context, DECL_NAME (t),
15751                                            /*template*/true);
15752             }
15753           return lookup_field (context, DECL_NAME(t), 0, false);
15754         }
15755       else
15756         /* Ordinary template template argument.  */
15757         return t;
15758
15759     case NON_LVALUE_EXPR:
15760     case VIEW_CONVERT_EXPR:
15761         {
15762           /* Handle location wrappers by substituting the wrapped node
15763              first, *then* reusing the resulting type.  Doing the type
15764              first ensures that we handle template parameters and
15765              parameter pack expansions.  */
15766           if (location_wrapper_p (t))
15767             {
15768               tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
15769                                       complain, in_decl);
15770               return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15771             }
15772           tree op = TREE_OPERAND (t, 0);
15773           if (code == VIEW_CONVERT_EXPR
15774               && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
15775             {
15776               /* Wrapper to make a C++20 template parameter object const.  */
15777               op = tsubst_copy (op, args, complain, in_decl);
15778               if (TREE_CODE (op) == TEMPLATE_PARM_INDEX)
15779                 {
15780                   tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15781                   return build1 (code, type, op);
15782                 }
15783               else
15784                 {
15785                   gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (op)));
15786                   return op;
15787                 }
15788             }
15789           /* We shouldn't see any other uses of these in templates.  */
15790           gcc_unreachable ();
15791         }
15792
15793     case CAST_EXPR:
15794     case REINTERPRET_CAST_EXPR:
15795     case CONST_CAST_EXPR:
15796     case STATIC_CAST_EXPR:
15797     case DYNAMIC_CAST_EXPR:
15798     case IMPLICIT_CONV_EXPR:
15799     case CONVERT_EXPR:
15800     case NOP_EXPR:
15801       {
15802         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15803         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15804         return build1 (code, type, op0);
15805       }
15806
15807     case SIZEOF_EXPR:
15808       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15809           || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15810         {
15811           tree expanded, op = TREE_OPERAND (t, 0);
15812           int len = 0;
15813
15814           if (SIZEOF_EXPR_TYPE_P (t))
15815             op = TREE_TYPE (op);
15816
15817           ++cp_unevaluated_operand;
15818           ++c_inhibit_evaluation_warnings;
15819           /* We only want to compute the number of arguments.  */
15820           if (PACK_EXPANSION_P (op))
15821             expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15822           else
15823             expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15824                                              args, complain, in_decl);
15825           --cp_unevaluated_operand;
15826           --c_inhibit_evaluation_warnings;
15827
15828           if (TREE_CODE (expanded) == TREE_VEC)
15829             {
15830               len = TREE_VEC_LENGTH (expanded);
15831               /* Set TREE_USED for the benefit of -Wunused.  */
15832               for (int i = 0; i < len; i++)
15833                 if (DECL_P (TREE_VEC_ELT (expanded, i)))
15834                   TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15835             }
15836
15837           if (expanded == error_mark_node)
15838             return error_mark_node;
15839           else if (PACK_EXPANSION_P (expanded)
15840                    || (TREE_CODE (expanded) == TREE_VEC
15841                        && pack_expansion_args_count (expanded)))
15842
15843             {
15844               if (PACK_EXPANSION_P (expanded))
15845                 /* OK.  */;
15846               else if (TREE_VEC_LENGTH (expanded) == 1)
15847                 expanded = TREE_VEC_ELT (expanded, 0);
15848               else
15849                 expanded = make_argument_pack (expanded);
15850
15851               if (TYPE_P (expanded))
15852                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15853                                                    false,
15854                                                    complain & tf_error);
15855               else
15856                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15857                                                    complain & tf_error);
15858             }
15859           else
15860             return build_int_cst (size_type_node, len);
15861         }
15862       if (SIZEOF_EXPR_TYPE_P (t))
15863         {
15864           r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15865                       args, complain, in_decl);
15866           r = build1 (NOP_EXPR, r, error_mark_node);
15867           r = build1 (SIZEOF_EXPR,
15868                       tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15869           SIZEOF_EXPR_TYPE_P (r) = 1;
15870           return r;
15871         }
15872       /* Fall through */
15873
15874     case INDIRECT_REF:
15875     case NEGATE_EXPR:
15876     case TRUTH_NOT_EXPR:
15877     case BIT_NOT_EXPR:
15878     case ADDR_EXPR:
15879     case UNARY_PLUS_EXPR:      /* Unary + */
15880     case ALIGNOF_EXPR:
15881     case AT_ENCODE_EXPR:
15882     case ARROW_EXPR:
15883     case THROW_EXPR:
15884     case TYPEID_EXPR:
15885     case REALPART_EXPR:
15886     case IMAGPART_EXPR:
15887     case PAREN_EXPR:
15888       {
15889         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15890         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15891         r = build1 (code, type, op0);
15892         if (code == ALIGNOF_EXPR)
15893           ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15894         return r;
15895       }
15896
15897     case COMPONENT_REF:
15898       {
15899         tree object;
15900         tree name;
15901
15902         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15903         name = TREE_OPERAND (t, 1);
15904         if (TREE_CODE (name) == BIT_NOT_EXPR)
15905           {
15906             name = tsubst_copy (TREE_OPERAND (name, 0), args,
15907                                 complain, in_decl);
15908             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15909           }
15910         else if (TREE_CODE (name) == SCOPE_REF
15911                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15912           {
15913             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15914                                      complain, in_decl);
15915             name = TREE_OPERAND (name, 1);
15916             name = tsubst_copy (TREE_OPERAND (name, 0), args,
15917                                 complain, in_decl);
15918             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15919             name = build_qualified_name (/*type=*/NULL_TREE,
15920                                          base, name,
15921                                          /*template_p=*/false);
15922           }
15923         else if (BASELINK_P (name))
15924           name = tsubst_baselink (name,
15925                                   non_reference (TREE_TYPE (object)),
15926                                   args, complain,
15927                                   in_decl);
15928         else
15929           name = tsubst_copy (name, args, complain, in_decl);
15930         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15931       }
15932
15933     case PLUS_EXPR:
15934     case MINUS_EXPR:
15935     case MULT_EXPR:
15936     case TRUNC_DIV_EXPR:
15937     case CEIL_DIV_EXPR:
15938     case FLOOR_DIV_EXPR:
15939     case ROUND_DIV_EXPR:
15940     case EXACT_DIV_EXPR:
15941     case BIT_AND_EXPR:
15942     case BIT_IOR_EXPR:
15943     case BIT_XOR_EXPR:
15944     case TRUNC_MOD_EXPR:
15945     case FLOOR_MOD_EXPR:
15946     case TRUTH_ANDIF_EXPR:
15947     case TRUTH_ORIF_EXPR:
15948     case TRUTH_AND_EXPR:
15949     case TRUTH_OR_EXPR:
15950     case RSHIFT_EXPR:
15951     case LSHIFT_EXPR:
15952     case RROTATE_EXPR:
15953     case LROTATE_EXPR:
15954     case EQ_EXPR:
15955     case NE_EXPR:
15956     case MAX_EXPR:
15957     case MIN_EXPR:
15958     case LE_EXPR:
15959     case GE_EXPR:
15960     case LT_EXPR:
15961     case GT_EXPR:
15962     case COMPOUND_EXPR:
15963     case DOTSTAR_EXPR:
15964     case MEMBER_REF:
15965     case PREDECREMENT_EXPR:
15966     case PREINCREMENT_EXPR:
15967     case POSTDECREMENT_EXPR:
15968     case POSTINCREMENT_EXPR:
15969       {
15970         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15971         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15972         return build_nt (code, op0, op1);
15973       }
15974
15975     case SCOPE_REF:
15976       {
15977         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15978         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15979         return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15980                                      QUALIFIED_NAME_IS_TEMPLATE (t));
15981       }
15982
15983     case ARRAY_REF:
15984       {
15985         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15986         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15987         return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15988       }
15989
15990     case CALL_EXPR:
15991       {
15992         int n = VL_EXP_OPERAND_LENGTH (t);
15993         tree result = build_vl_exp (CALL_EXPR, n);
15994         int i;
15995         for (i = 0; i < n; i++)
15996           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15997                                              complain, in_decl);
15998         return result;
15999       }
16000
16001     case COND_EXPR:
16002     case MODOP_EXPR:
16003     case PSEUDO_DTOR_EXPR:
16004     case VEC_PERM_EXPR:
16005       {
16006         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16007         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16008         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16009         r = build_nt (code, op0, op1, op2);
16010         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16011         return r;
16012       }
16013
16014     case NEW_EXPR:
16015       {
16016         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16017         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16018         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16019         r = build_nt (code, op0, op1, op2);
16020         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
16021         return r;
16022       }
16023
16024     case DELETE_EXPR:
16025       {
16026         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16027         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16028         r = build_nt (code, op0, op1);
16029         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
16030         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
16031         return r;
16032       }
16033
16034     case TEMPLATE_ID_EXPR:
16035       {
16036         /* Substituted template arguments */
16037         tree fn = TREE_OPERAND (t, 0);
16038         tree targs = TREE_OPERAND (t, 1);
16039
16040         fn = tsubst_copy (fn, args, complain, in_decl);
16041         if (targs)
16042           targs = tsubst_template_args (targs, args, complain, in_decl);
16043
16044         return lookup_template_function (fn, targs);
16045       }
16046
16047     case TREE_LIST:
16048       {
16049         tree purpose, value, chain;
16050
16051         if (t == void_list_node)
16052           return t;
16053
16054         purpose = TREE_PURPOSE (t);
16055         if (purpose)
16056           purpose = tsubst_copy (purpose, args, complain, in_decl);
16057         value = TREE_VALUE (t);
16058         if (value)
16059           value = tsubst_copy (value, args, complain, in_decl);
16060         chain = TREE_CHAIN (t);
16061         if (chain && chain != void_type_node)
16062           chain = tsubst_copy (chain, args, complain, in_decl);
16063         if (purpose == TREE_PURPOSE (t)
16064             && value == TREE_VALUE (t)
16065             && chain == TREE_CHAIN (t))
16066           return t;
16067         return tree_cons (purpose, value, chain);
16068       }
16069
16070     case RECORD_TYPE:
16071     case UNION_TYPE:
16072     case ENUMERAL_TYPE:
16073     case INTEGER_TYPE:
16074     case TEMPLATE_TYPE_PARM:
16075     case TEMPLATE_TEMPLATE_PARM:
16076     case BOUND_TEMPLATE_TEMPLATE_PARM:
16077     case TEMPLATE_PARM_INDEX:
16078     case POINTER_TYPE:
16079     case REFERENCE_TYPE:
16080     case OFFSET_TYPE:
16081     case FUNCTION_TYPE:
16082     case METHOD_TYPE:
16083     case ARRAY_TYPE:
16084     case TYPENAME_TYPE:
16085     case UNBOUND_CLASS_TEMPLATE:
16086     case TYPEOF_TYPE:
16087     case DECLTYPE_TYPE:
16088     case TYPE_DECL:
16089       return tsubst (t, args, complain, in_decl);
16090
16091     case USING_DECL:
16092       t = DECL_NAME (t);
16093       /* Fall through.  */
16094     case IDENTIFIER_NODE:
16095       if (IDENTIFIER_CONV_OP_P (t))
16096         {
16097           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16098           return make_conv_op_name (new_type);
16099         }
16100       else
16101         return t;
16102
16103     case CONSTRUCTOR:
16104       /* This is handled by tsubst_copy_and_build.  */
16105       gcc_unreachable ();
16106
16107     case VA_ARG_EXPR:
16108       {
16109         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16110         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16111         return build_x_va_arg (EXPR_LOCATION (t), op0, type);
16112       }
16113
16114     case CLEANUP_POINT_EXPR:
16115       /* We shouldn't have built any of these during initial template
16116          generation.  Instead, they should be built during instantiation
16117          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
16118       gcc_unreachable ();
16119
16120     case OFFSET_REF:
16121       {
16122         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16123         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16124         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16125         r = build2 (code, type, op0, op1);
16126         PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
16127         if (!mark_used (TREE_OPERAND (r, 1), complain)
16128             && !(complain & tf_error))
16129           return error_mark_node;
16130         return r;
16131       }
16132
16133     case EXPR_PACK_EXPANSION:
16134       error ("invalid use of pack expansion expression");
16135       return error_mark_node;
16136
16137     case NONTYPE_ARGUMENT_PACK:
16138       error ("use %<...%> to expand argument pack");
16139       return error_mark_node;
16140
16141     case VOID_CST:
16142       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
16143       return t;
16144
16145     case INTEGER_CST:
16146     case REAL_CST:
16147     case STRING_CST:
16148     case COMPLEX_CST:
16149       {
16150         /* Instantiate any typedefs in the type.  */
16151         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16152         r = fold_convert (type, t);
16153         gcc_assert (TREE_CODE (r) == code);
16154         return r;
16155       }
16156
16157     case PTRMEM_CST:
16158       /* These can sometimes show up in a partial instantiation, but never
16159          involve template parms.  */
16160       gcc_assert (!uses_template_parms (t));
16161       return t;
16162
16163     case UNARY_LEFT_FOLD_EXPR:
16164       return tsubst_unary_left_fold (t, args, complain, in_decl);
16165     case UNARY_RIGHT_FOLD_EXPR:
16166       return tsubst_unary_right_fold (t, args, complain, in_decl);
16167     case BINARY_LEFT_FOLD_EXPR:
16168       return tsubst_binary_left_fold (t, args, complain, in_decl);
16169     case BINARY_RIGHT_FOLD_EXPR:
16170       return tsubst_binary_right_fold (t, args, complain, in_decl);
16171     case PREDICT_EXPR:
16172       return t;
16173
16174     case DEBUG_BEGIN_STMT:
16175       /* ??? There's no point in copying it for now, but maybe some
16176          day it will contain more information, such as a pointer back
16177          to the containing function, inlined copy or so.  */
16178       return t;
16179
16180     default:
16181       /* We shouldn't get here, but keep going if !flag_checking.  */
16182       if (flag_checking)
16183         gcc_unreachable ();
16184       return t;
16185     }
16186 }
16187
16188 /* Helper function for tsubst_omp_clauses, used for instantiation of
16189    OMP_CLAUSE_DECL of clauses.  */
16190
16191 static tree
16192 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
16193                         tree in_decl, tree *iterator_cache)
16194 {
16195   if (decl == NULL_TREE)
16196     return NULL_TREE;
16197
16198   /* Handle OpenMP iterators.  */
16199   if (TREE_CODE (decl) == TREE_LIST
16200       && TREE_PURPOSE (decl)
16201       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
16202     {
16203       tree ret;
16204       if (iterator_cache[0] == TREE_PURPOSE (decl))
16205         ret = iterator_cache[1];
16206       else
16207         {
16208           tree *tp = &ret;
16209           begin_scope (sk_omp, NULL);
16210           for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
16211             {
16212               *tp = copy_node (it);
16213               TREE_VEC_ELT (*tp, 0)
16214                 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
16215               TREE_VEC_ELT (*tp, 1)
16216                 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
16217                                /*integral_constant_expression_p=*/false);
16218               TREE_VEC_ELT (*tp, 2)
16219                 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
16220                                /*integral_constant_expression_p=*/false);
16221               TREE_VEC_ELT (*tp, 3)
16222                 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
16223                                /*integral_constant_expression_p=*/false);
16224               TREE_CHAIN (*tp) = NULL_TREE;
16225               tp = &TREE_CHAIN (*tp);
16226             }
16227           TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
16228           iterator_cache[0] = TREE_PURPOSE (decl);
16229           iterator_cache[1] = ret;
16230         }
16231       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
16232                                                            args, complain,
16233                                                            in_decl, NULL));
16234     }
16235
16236   /* Handle an OpenMP array section represented as a TREE_LIST (or
16237      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
16238      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
16239      TREE_LIST.  We can handle it exactly the same as an array section
16240      (purpose, value, and a chain), even though the nomenclature
16241      (low_bound, length, etc) is different.  */
16242   if (TREE_CODE (decl) == TREE_LIST)
16243     {
16244       tree low_bound
16245         = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
16246                        /*integral_constant_expression_p=*/false);
16247       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
16248                                  /*integral_constant_expression_p=*/false);
16249       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
16250                                            in_decl, NULL);
16251       if (TREE_PURPOSE (decl) == low_bound
16252           && TREE_VALUE (decl) == length
16253           && TREE_CHAIN (decl) == chain)
16254         return decl;
16255       tree ret = tree_cons (low_bound, length, chain);
16256       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
16257         = OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
16258       return ret;
16259     }
16260   tree ret = tsubst_expr (decl, args, complain, in_decl,
16261                           /*integral_constant_expression_p=*/false);
16262   /* Undo convert_from_reference tsubst_expr could have called.  */
16263   if (decl
16264       && REFERENCE_REF_P (ret)
16265       && !REFERENCE_REF_P (decl))
16266     ret = TREE_OPERAND (ret, 0);
16267   return ret;
16268 }
16269
16270 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
16271
16272 static tree
16273 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
16274                     tree args, tsubst_flags_t complain, tree in_decl)
16275 {
16276   tree new_clauses = NULL_TREE, nc, oc;
16277   tree linear_no_step = NULL_TREE;
16278   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
16279
16280   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
16281     {
16282       nc = copy_node (oc);
16283       OMP_CLAUSE_CHAIN (nc) = new_clauses;
16284       new_clauses = nc;
16285
16286       switch (OMP_CLAUSE_CODE (nc))
16287         {
16288         case OMP_CLAUSE_LASTPRIVATE:
16289           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16290             {
16291               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16292               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16293                            in_decl, /*integral_constant_expression_p=*/false);
16294               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16295                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16296             }
16297           /* FALLTHRU */
16298         case OMP_CLAUSE_PRIVATE:
16299         case OMP_CLAUSE_SHARED:
16300         case OMP_CLAUSE_FIRSTPRIVATE:
16301         case OMP_CLAUSE_COPYIN:
16302         case OMP_CLAUSE_COPYPRIVATE:
16303         case OMP_CLAUSE_UNIFORM:
16304         case OMP_CLAUSE_DEPEND:
16305         case OMP_CLAUSE_FROM:
16306         case OMP_CLAUSE_TO:
16307         case OMP_CLAUSE_MAP:
16308         case OMP_CLAUSE_NONTEMPORAL:
16309         case OMP_CLAUSE_USE_DEVICE_PTR:
16310         case OMP_CLAUSE_USE_DEVICE_ADDR:
16311         case OMP_CLAUSE_IS_DEVICE_PTR:
16312         case OMP_CLAUSE_INCLUSIVE:
16313         case OMP_CLAUSE_EXCLUSIVE:
16314           OMP_CLAUSE_DECL (nc)
16315             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16316                                       in_decl, iterator_cache);
16317           break;
16318         case OMP_CLAUSE_TILE:
16319         case OMP_CLAUSE_IF:
16320         case OMP_CLAUSE_NUM_THREADS:
16321         case OMP_CLAUSE_SCHEDULE:
16322         case OMP_CLAUSE_COLLAPSE:
16323         case OMP_CLAUSE_FINAL:
16324         case OMP_CLAUSE_DEVICE:
16325         case OMP_CLAUSE_DIST_SCHEDULE:
16326         case OMP_CLAUSE_NUM_TEAMS:
16327         case OMP_CLAUSE_THREAD_LIMIT:
16328         case OMP_CLAUSE_SAFELEN:
16329         case OMP_CLAUSE_SIMDLEN:
16330         case OMP_CLAUSE_NUM_TASKS:
16331         case OMP_CLAUSE_GRAINSIZE:
16332         case OMP_CLAUSE_PRIORITY:
16333         case OMP_CLAUSE_ORDERED:
16334         case OMP_CLAUSE_HINT:
16335         case OMP_CLAUSE_NUM_GANGS:
16336         case OMP_CLAUSE_NUM_WORKERS:
16337         case OMP_CLAUSE_VECTOR_LENGTH:
16338         case OMP_CLAUSE_WORKER:
16339         case OMP_CLAUSE_VECTOR:
16340         case OMP_CLAUSE_ASYNC:
16341         case OMP_CLAUSE_WAIT:
16342           OMP_CLAUSE_OPERAND (nc, 0)
16343             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16344                            in_decl, /*integral_constant_expression_p=*/false);
16345           break;
16346         case OMP_CLAUSE_REDUCTION:
16347         case OMP_CLAUSE_IN_REDUCTION:
16348         case OMP_CLAUSE_TASK_REDUCTION:
16349           if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16350             {
16351               tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16352               if (TREE_CODE (placeholder) == SCOPE_REF)
16353                 {
16354                   tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16355                                        complain, in_decl);
16356                   OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16357                     = build_qualified_name (NULL_TREE, scope,
16358                                             TREE_OPERAND (placeholder, 1),
16359                                             false);
16360                 }
16361               else
16362                 gcc_assert (identifier_p (placeholder));
16363             }
16364           OMP_CLAUSE_DECL (nc)
16365             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16366                                       in_decl, NULL);
16367           break;
16368         case OMP_CLAUSE_GANG:
16369         case OMP_CLAUSE_ALIGNED:
16370           OMP_CLAUSE_DECL (nc)
16371             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16372                                       in_decl, NULL);
16373           OMP_CLAUSE_OPERAND (nc, 1)
16374             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16375                            in_decl, /*integral_constant_expression_p=*/false);
16376           break;
16377         case OMP_CLAUSE_LINEAR:
16378           OMP_CLAUSE_DECL (nc)
16379             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16380                                       in_decl, NULL);
16381           if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16382             {
16383               gcc_assert (!linear_no_step);
16384               linear_no_step = nc;
16385             }
16386           else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16387             OMP_CLAUSE_LINEAR_STEP (nc)
16388               = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16389                                         complain, in_decl, NULL);
16390           else
16391             OMP_CLAUSE_LINEAR_STEP (nc)
16392               = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16393                              in_decl,
16394                              /*integral_constant_expression_p=*/false);
16395           break;
16396         case OMP_CLAUSE_NOWAIT:
16397         case OMP_CLAUSE_DEFAULT:
16398         case OMP_CLAUSE_UNTIED:
16399         case OMP_CLAUSE_MERGEABLE:
16400         case OMP_CLAUSE_INBRANCH:
16401         case OMP_CLAUSE_NOTINBRANCH:
16402         case OMP_CLAUSE_PROC_BIND:
16403         case OMP_CLAUSE_FOR:
16404         case OMP_CLAUSE_PARALLEL:
16405         case OMP_CLAUSE_SECTIONS:
16406         case OMP_CLAUSE_TASKGROUP:
16407         case OMP_CLAUSE_NOGROUP:
16408         case OMP_CLAUSE_THREADS:
16409         case OMP_CLAUSE_SIMD:
16410         case OMP_CLAUSE_DEFAULTMAP:
16411         case OMP_CLAUSE_ORDER:
16412         case OMP_CLAUSE_BIND:
16413         case OMP_CLAUSE_INDEPENDENT:
16414         case OMP_CLAUSE_AUTO:
16415         case OMP_CLAUSE_SEQ:
16416         case OMP_CLAUSE_IF_PRESENT:
16417         case OMP_CLAUSE_FINALIZE:
16418           break;
16419         default:
16420           gcc_unreachable ();
16421         }
16422       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16423         switch (OMP_CLAUSE_CODE (nc))
16424           {
16425           case OMP_CLAUSE_SHARED:
16426           case OMP_CLAUSE_PRIVATE:
16427           case OMP_CLAUSE_FIRSTPRIVATE:
16428           case OMP_CLAUSE_LASTPRIVATE:
16429           case OMP_CLAUSE_COPYPRIVATE:
16430           case OMP_CLAUSE_LINEAR:
16431           case OMP_CLAUSE_REDUCTION:
16432           case OMP_CLAUSE_IN_REDUCTION:
16433           case OMP_CLAUSE_TASK_REDUCTION:
16434           case OMP_CLAUSE_USE_DEVICE_PTR:
16435           case OMP_CLAUSE_USE_DEVICE_ADDR:
16436           case OMP_CLAUSE_IS_DEVICE_PTR:
16437           case OMP_CLAUSE_INCLUSIVE:
16438           case OMP_CLAUSE_EXCLUSIVE:
16439             /* tsubst_expr on SCOPE_REF results in returning
16440                finish_non_static_data_member result.  Undo that here.  */
16441             if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16442                 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16443                     == IDENTIFIER_NODE))
16444               {
16445                 tree t = OMP_CLAUSE_DECL (nc);
16446                 tree v = t;
16447                 while (v)
16448                   switch (TREE_CODE (v))
16449                     {
16450                     case COMPONENT_REF:
16451                     case MEM_REF:
16452                     case INDIRECT_REF:
16453                     CASE_CONVERT:
16454                     case POINTER_PLUS_EXPR:
16455                       v = TREE_OPERAND (v, 0);
16456                       continue;
16457                     case PARM_DECL:
16458                       if (DECL_CONTEXT (v) == current_function_decl
16459                           && DECL_ARTIFICIAL (v)
16460                           && DECL_NAME (v) == this_identifier)
16461                         OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16462                       /* FALLTHRU */
16463                     default:
16464                       v = NULL_TREE;
16465                       break;
16466                     }
16467               }
16468             else if (VAR_P (OMP_CLAUSE_DECL (oc))
16469                      && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16470                      && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16471                      && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16472                      && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16473               {
16474                 tree decl = OMP_CLAUSE_DECL (nc);
16475                 if (VAR_P (decl))
16476                   {
16477                     retrofit_lang_decl (decl);
16478                     DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16479                   }
16480               }
16481             break;
16482           default:
16483             break;
16484           }
16485     }
16486
16487   new_clauses = nreverse (new_clauses);
16488   if (ort != C_ORT_OMP_DECLARE_SIMD)
16489     {
16490       new_clauses = finish_omp_clauses (new_clauses, ort);
16491       if (linear_no_step)
16492         for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16493           if (nc == linear_no_step)
16494             {
16495               OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16496               break;
16497             }
16498     }
16499   return new_clauses;
16500 }
16501
16502 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
16503
16504 static tree
16505 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16506                           tree in_decl)
16507 {
16508 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16509
16510   tree purpose, value, chain;
16511
16512   if (t == NULL)
16513     return t;
16514
16515   if (TREE_CODE (t) != TREE_LIST)
16516     return tsubst_copy_and_build (t, args, complain, in_decl,
16517                                   /*function_p=*/false,
16518                                   /*integral_constant_expression_p=*/false);
16519
16520   if (t == void_list_node)
16521     return t;
16522
16523   purpose = TREE_PURPOSE (t);
16524   if (purpose)
16525     purpose = RECUR (purpose);
16526   value = TREE_VALUE (t);
16527   if (value)
16528     {
16529       if (TREE_CODE (value) != LABEL_DECL)
16530         value = RECUR (value);
16531       else
16532         {
16533           value = lookup_label (DECL_NAME (value));
16534           gcc_assert (TREE_CODE (value) == LABEL_DECL);
16535           TREE_USED (value) = 1;
16536         }
16537     }
16538   chain = TREE_CHAIN (t);
16539   if (chain && chain != void_type_node)
16540     chain = RECUR (chain);
16541   return tree_cons (purpose, value, chain);
16542 #undef RECUR
16543 }
16544
16545 /* Used to temporarily communicate the list of #pragma omp parallel
16546    clauses to #pragma omp for instantiation if they are combined
16547    together.  */
16548
16549 static tree *omp_parallel_combined_clauses;
16550
16551 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
16552                                  tree *, unsigned int *);
16553
16554 /* Substitute one OMP_FOR iterator.  */
16555
16556 static bool
16557 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
16558                          tree initv, tree condv, tree incrv, tree *clauses,
16559                          tree args, tsubst_flags_t complain, tree in_decl,
16560                          bool integral_constant_expression_p)
16561 {
16562 #define RECUR(NODE)                             \
16563   tsubst_expr ((NODE), args, complain, in_decl, \
16564                integral_constant_expression_p)
16565   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
16566   bool ret = false;
16567
16568   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16569   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16570
16571   decl = TREE_OPERAND (init, 0);
16572   init = TREE_OPERAND (init, 1);
16573   tree decl_expr = NULL_TREE;
16574   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
16575   if (range_for)
16576     {
16577       bool decomp = false;
16578       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
16579         {
16580           tree v = DECL_VALUE_EXPR (decl);
16581           if (TREE_CODE (v) == ARRAY_REF
16582               && VAR_P (TREE_OPERAND (v, 0))
16583               && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
16584             {
16585               tree decomp_first = NULL_TREE;
16586               unsigned decomp_cnt = 0;
16587               tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
16588               maybe_push_decl (d);
16589               d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
16590                                        in_decl, &decomp_first, &decomp_cnt);
16591               decomp = true;
16592               if (d == error_mark_node)
16593                 decl = error_mark_node;
16594               else
16595                 for (unsigned int i = 0; i < decomp_cnt; i++)
16596                   {
16597                     if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
16598                       {
16599                         tree v = build_nt (ARRAY_REF, d,
16600                                            size_int (decomp_cnt - i - 1),
16601                                            NULL_TREE, NULL_TREE);
16602                         SET_DECL_VALUE_EXPR (decomp_first, v);
16603                         DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
16604                       }
16605                     fit_decomposition_lang_decl (decomp_first, d);
16606                     decomp_first = DECL_CHAIN (decomp_first);
16607                   }
16608             }
16609         }
16610       decl = tsubst_decl (decl, args, complain);
16611       if (!decomp)
16612         maybe_push_decl (decl);
16613     }
16614   else if (init && TREE_CODE (init) == DECL_EXPR)
16615     {
16616       /* We need to jump through some hoops to handle declarations in the
16617          init-statement, since we might need to handle auto deduction,
16618          but we need to keep control of initialization.  */
16619       decl_expr = init;
16620       init = DECL_INITIAL (DECL_EXPR_DECL (init));
16621       decl = tsubst_decl (decl, args, complain);
16622     }
16623   else
16624     {
16625       if (TREE_CODE (decl) == SCOPE_REF)
16626         {
16627           decl = RECUR (decl);
16628           if (TREE_CODE (decl) == COMPONENT_REF)
16629             {
16630               tree v = decl;
16631               while (v)
16632                 switch (TREE_CODE (v))
16633                   {
16634                   case COMPONENT_REF:
16635                   case MEM_REF:
16636                   case INDIRECT_REF:
16637                   CASE_CONVERT:
16638                   case POINTER_PLUS_EXPR:
16639                     v = TREE_OPERAND (v, 0);
16640                     continue;
16641                   case PARM_DECL:
16642                     if (DECL_CONTEXT (v) == current_function_decl
16643                         && DECL_ARTIFICIAL (v)
16644                         && DECL_NAME (v) == this_identifier)
16645                       {
16646                         decl = TREE_OPERAND (decl, 1);
16647                         decl = omp_privatize_field (decl, false);
16648                       }
16649                     /* FALLTHRU */
16650                   default:
16651                     v = NULL_TREE;
16652                     break;
16653                   }
16654             }
16655         }
16656       else
16657         decl = RECUR (decl);
16658     }
16659   init = RECUR (init);
16660
16661   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16662     {
16663       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16664       if (TREE_CODE (o) == TREE_LIST)
16665         TREE_VEC_ELT (orig_declv, i)
16666           = tree_cons (RECUR (TREE_PURPOSE (o)),
16667                        RECUR (TREE_VALUE (o)),
16668                        NULL_TREE);
16669       else
16670         TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16671     }
16672
16673   if (range_for)
16674     {
16675       tree this_pre_body = NULL_TREE;
16676       tree orig_init = NULL_TREE;
16677       tree orig_decl = NULL_TREE;
16678       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
16679                                 orig_init, cond, incr);
16680       if (orig_decl)
16681         {
16682           if (orig_declv == NULL_TREE)
16683             orig_declv = copy_node (declv);
16684           TREE_VEC_ELT (orig_declv, i) = orig_decl;
16685           ret = true;
16686         }
16687       else if (orig_declv)
16688         TREE_VEC_ELT (orig_declv, i) = decl;
16689     }
16690
16691   tree auto_node = type_uses_auto (TREE_TYPE (decl));
16692   if (!range_for && auto_node && init)
16693     TREE_TYPE (decl)
16694       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16695
16696   gcc_assert (!type_dependent_expression_p (decl));
16697
16698   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
16699     {
16700       if (decl_expr)
16701         {
16702           /* Declare the variable, but don't let that initialize it.  */
16703           tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16704           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16705           RECUR (decl_expr);
16706           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16707         }
16708
16709       if (!range_for)
16710         {
16711           cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16712           incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16713           if (TREE_CODE (incr) == MODIFY_EXPR)
16714             {
16715               tree lhs = RECUR (TREE_OPERAND (incr, 0));
16716               tree rhs = RECUR (TREE_OPERAND (incr, 1));
16717               incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16718                                           NOP_EXPR, rhs, complain);
16719             }
16720           else
16721             incr = RECUR (incr);
16722           if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
16723             TREE_VEC_ELT (orig_declv, i) = decl;
16724         }
16725       TREE_VEC_ELT (declv, i) = decl;
16726       TREE_VEC_ELT (initv, i) = init;
16727       TREE_VEC_ELT (condv, i) = cond;
16728       TREE_VEC_ELT (incrv, i) = incr;
16729       return ret;
16730     }
16731
16732   if (decl_expr)
16733     {
16734       /* Declare and initialize the variable.  */
16735       RECUR (decl_expr);
16736       init = NULL_TREE;
16737     }
16738   else if (init)
16739     {
16740       tree *pc;
16741       int j;
16742       for (j = ((omp_parallel_combined_clauses == NULL
16743                 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
16744         {
16745           for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16746             {
16747               if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16748                   && OMP_CLAUSE_DECL (*pc) == decl)
16749                 break;
16750               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16751                        && OMP_CLAUSE_DECL (*pc) == decl)
16752                 {
16753                   if (j)
16754                     break;
16755                   /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
16756                   tree c = *pc;
16757                   *pc = OMP_CLAUSE_CHAIN (c);
16758                   OMP_CLAUSE_CHAIN (c) = *clauses;
16759                   *clauses = c;
16760                 }
16761               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16762                        && OMP_CLAUSE_DECL (*pc) == decl)
16763                 {
16764                   error ("iteration variable %qD should not be firstprivate",
16765                          decl);
16766                   *pc = OMP_CLAUSE_CHAIN (*pc);
16767                 }
16768               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16769                        && OMP_CLAUSE_DECL (*pc) == decl)
16770                 {
16771                   error ("iteration variable %qD should not be reduction",
16772                          decl);
16773                   *pc = OMP_CLAUSE_CHAIN (*pc);
16774                 }
16775               else
16776                 pc = &OMP_CLAUSE_CHAIN (*pc);
16777             }
16778           if (*pc)
16779             break;
16780         }
16781       if (*pc == NULL_TREE)
16782         {
16783           tree c = build_omp_clause (input_location,
16784                                      TREE_CODE (t) == OMP_LOOP
16785                                      ? OMP_CLAUSE_LASTPRIVATE
16786                                      : OMP_CLAUSE_PRIVATE);
16787           OMP_CLAUSE_DECL (c) = decl;
16788           c = finish_omp_clauses (c, C_ORT_OMP);
16789           if (c)
16790             {
16791               OMP_CLAUSE_CHAIN (c) = *clauses;
16792               *clauses = c;
16793             }
16794         }
16795     }
16796   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16797   if (COMPARISON_CLASS_P (cond))
16798     {
16799       tree op0 = RECUR (TREE_OPERAND (cond, 0));
16800       tree op1 = RECUR (TREE_OPERAND (cond, 1));
16801       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16802     }
16803   else
16804     cond = RECUR (cond);
16805   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16806   switch (TREE_CODE (incr))
16807     {
16808     case PREINCREMENT_EXPR:
16809     case PREDECREMENT_EXPR:
16810     case POSTINCREMENT_EXPR:
16811     case POSTDECREMENT_EXPR:
16812       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16813                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16814       break;
16815     case MODIFY_EXPR:
16816       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16817           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16818         {
16819           tree rhs = TREE_OPERAND (incr, 1);
16820           tree lhs = RECUR (TREE_OPERAND (incr, 0));
16821           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16822           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16823           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16824                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16825                                  rhs0, rhs1));
16826         }
16827       else
16828         incr = RECUR (incr);
16829       break;
16830     case MODOP_EXPR:
16831       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16832           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16833         {
16834           tree lhs = RECUR (TREE_OPERAND (incr, 0));
16835           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16836                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16837                                  TREE_TYPE (decl), lhs,
16838                                  RECUR (TREE_OPERAND (incr, 2))));
16839         }
16840       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16841                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16842                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16843         {
16844           tree rhs = TREE_OPERAND (incr, 2);
16845           tree lhs = RECUR (TREE_OPERAND (incr, 0));
16846           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16847           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16848           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16849                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16850                                  rhs0, rhs1));
16851         }
16852       else
16853         incr = RECUR (incr);
16854       break;
16855     default:
16856       incr = RECUR (incr);
16857       break;
16858     }
16859
16860   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
16861     TREE_VEC_ELT (orig_declv, i) = decl;
16862   TREE_VEC_ELT (declv, i) = decl;
16863   TREE_VEC_ELT (initv, i) = init;
16864   TREE_VEC_ELT (condv, i) = cond;
16865   TREE_VEC_ELT (incrv, i) = incr;
16866   return false;
16867 #undef RECUR
16868 }
16869
16870 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16871    of OMP_TARGET's body.  */
16872
16873 static tree
16874 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16875 {
16876   *walk_subtrees = 0;
16877   switch (TREE_CODE (*tp))
16878     {
16879     case OMP_TEAMS:
16880       return *tp;
16881     case BIND_EXPR:
16882     case STATEMENT_LIST:
16883       *walk_subtrees = 1;
16884       break;
16885     default:
16886       break;
16887     }
16888   return NULL_TREE;
16889 }
16890
16891 /* Helper function for tsubst_expr.  For decomposition declaration
16892    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16893    also the corresponding decls representing the identifiers
16894    of the decomposition declaration.  Return DECL if successful
16895    or error_mark_node otherwise, set *FIRST to the first decl
16896    in the list chained through DECL_CHAIN and *CNT to the number
16897    of such decls.  */
16898
16899 static tree
16900 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16901                      tsubst_flags_t complain, tree in_decl, tree *first,
16902                      unsigned int *cnt)
16903 {
16904   tree decl2, decl3, prev = decl;
16905   *cnt = 0;
16906   gcc_assert (DECL_NAME (decl) == NULL_TREE);
16907   for (decl2 = DECL_CHAIN (pattern_decl);
16908        decl2
16909        && VAR_P (decl2)
16910        && DECL_DECOMPOSITION_P (decl2)
16911        && DECL_NAME (decl2);
16912        decl2 = DECL_CHAIN (decl2))
16913     {
16914       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16915         {
16916           gcc_assert (errorcount);
16917           return error_mark_node;
16918         }
16919       (*cnt)++;
16920       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16921       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16922       tree v = DECL_VALUE_EXPR (decl2);
16923       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16924       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16925       decl3 = tsubst (decl2, args, complain, in_decl);
16926       SET_DECL_VALUE_EXPR (decl2, v);
16927       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16928       if (VAR_P (decl3))
16929         DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16930       else
16931         {
16932           gcc_assert (errorcount);
16933           decl = error_mark_node;
16934           continue;
16935         }
16936       maybe_push_decl (decl3);
16937       if (error_operand_p (decl3))
16938         decl = error_mark_node;
16939       else if (decl != error_mark_node
16940                && DECL_CHAIN (decl3) != prev
16941                && decl != prev)
16942         {
16943           gcc_assert (errorcount);
16944           decl = error_mark_node;
16945         }
16946       else
16947         prev = decl3;
16948     }
16949   *first = prev;
16950   return decl;
16951 }
16952
16953 /* Return the proper local_specialization for init-capture pack DECL.  */
16954
16955 static tree
16956 lookup_init_capture_pack (tree decl)
16957 {
16958   /* We handle normal pack captures by forwarding to the specialization of the
16959      captured parameter.  We can't do that for pack init-captures; we need them
16960      to have their own local_specialization.  We created the individual
16961      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
16962      when we process the DECL_EXPR for the pack init-capture in the template.
16963      So, how do we find them?  We don't know the capture proxy pack when
16964      building the individual resulting proxies, and we don't know the
16965      individual proxies when instantiating the pack.  What we have in common is
16966      the FIELD_DECL.
16967
16968      So...when we instantiate the FIELD_DECL, we stick the result in
16969      local_specializations.  Then at the DECL_EXPR we look up that result, see
16970      how many elements it has, synthesize the names, and look them up.  */
16971
16972   tree cname = DECL_NAME (decl);
16973   tree val = DECL_VALUE_EXPR (decl);
16974   tree field = TREE_OPERAND (val, 1);
16975   gcc_assert (TREE_CODE (field) == FIELD_DECL);
16976   tree fpack = retrieve_local_specialization (field);
16977   if (fpack == error_mark_node)
16978     return error_mark_node;
16979
16980   int len = 1;
16981   tree vec = NULL_TREE;
16982   tree r = NULL_TREE;
16983   if (TREE_CODE (fpack) == TREE_VEC)
16984     {
16985       len = TREE_VEC_LENGTH (fpack);
16986       vec = make_tree_vec (len);
16987       r = make_node (NONTYPE_ARGUMENT_PACK);
16988       SET_ARGUMENT_PACK_ARGS (r, vec);
16989     }
16990   for (int i = 0; i < len; ++i)
16991     {
16992       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
16993       tree elt = lookup_name_real (ename, 0, 0, true, 0, LOOKUP_NORMAL);
16994       if (vec)
16995         TREE_VEC_ELT (vec, i) = elt;
16996       else
16997         r = elt;
16998     }
16999   return r;
17000 }
17001
17002 /* Like tsubst_copy for expressions, etc. but also does semantic
17003    processing.  */
17004
17005 tree
17006 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
17007              bool integral_constant_expression_p)
17008 {
17009 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
17010 #define RECUR(NODE)                             \
17011   tsubst_expr ((NODE), args, complain, in_decl, \
17012                integral_constant_expression_p)
17013
17014   tree stmt, tmp;
17015   tree r;
17016   location_t loc;
17017
17018   if (t == NULL_TREE || t == error_mark_node)
17019     return t;
17020
17021   loc = input_location;
17022   if (location_t eloc = cp_expr_location (t))
17023     input_location = eloc;
17024   if (STATEMENT_CODE_P (TREE_CODE (t)))
17025     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
17026
17027   switch (TREE_CODE (t))
17028     {
17029     case STATEMENT_LIST:
17030       {
17031         tree_stmt_iterator i;
17032         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
17033           RECUR (tsi_stmt (i));
17034         break;
17035       }
17036
17037     case CTOR_INITIALIZER:
17038       finish_mem_initializers (tsubst_initializer_list
17039                                (TREE_OPERAND (t, 0), args));
17040       break;
17041
17042     case RETURN_EXPR:
17043       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
17044       break;
17045
17046     case EXPR_STMT:
17047       tmp = RECUR (EXPR_STMT_EXPR (t));
17048       if (EXPR_STMT_STMT_EXPR_RESULT (t))
17049         finish_stmt_expr_expr (tmp, cur_stmt_expr);
17050       else
17051         finish_expr_stmt (tmp);
17052       break;
17053
17054     case USING_STMT:
17055       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
17056       break;
17057
17058     case DECL_EXPR:
17059       {
17060         tree decl, pattern_decl;
17061         tree init;
17062
17063         pattern_decl = decl = DECL_EXPR_DECL (t);
17064         if (TREE_CODE (decl) == LABEL_DECL)
17065           finish_label_decl (DECL_NAME (decl));
17066         else if (TREE_CODE (decl) == USING_DECL)
17067           {
17068             tree scope = USING_DECL_SCOPE (decl);
17069             tree name = DECL_NAME (decl);
17070
17071             scope = tsubst (scope, args, complain, in_decl);
17072             finish_nonmember_using_decl (scope, name);
17073           }
17074         else if (is_capture_proxy (decl)
17075                  && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
17076           {
17077             /* We're in tsubst_lambda_expr, we've already inserted a new
17078                capture proxy, so look it up and register it.  */
17079             tree inst;
17080             if (!DECL_PACK_P (decl))
17081               {
17082                 inst = lookup_name_real (DECL_NAME (decl), /*prefer_type*/0,
17083                                          /*nonclass*/1, /*block_p=*/true,
17084                                          /*ns_only*/0, LOOKUP_HIDDEN);
17085                 gcc_assert (inst != decl && is_capture_proxy (inst));
17086               }
17087             else if (is_normal_capture_proxy (decl))
17088               {
17089                 inst = (retrieve_local_specialization
17090                         (DECL_CAPTURED_VARIABLE (decl)));
17091                 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
17092               }
17093             else
17094               inst = lookup_init_capture_pack (decl);
17095
17096             register_local_specialization (inst, decl);
17097             break;
17098           }
17099         else if (DECL_PRETTY_FUNCTION_P (decl))
17100           decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
17101                                   DECL_NAME (decl),
17102                                   true/*DECL_PRETTY_FUNCTION_P (decl)*/);
17103         else if (DECL_IMPLICIT_TYPEDEF_P (decl)
17104                  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
17105           /* Don't copy the old closure; we'll create a new one in
17106              tsubst_lambda_expr.  */
17107           break;
17108         else
17109           {
17110             init = DECL_INITIAL (decl);
17111             decl = tsubst (decl, args, complain, in_decl);
17112             if (decl != error_mark_node)
17113               {
17114                 /* By marking the declaration as instantiated, we avoid
17115                    trying to instantiate it.  Since instantiate_decl can't
17116                    handle local variables, and since we've already done
17117                    all that needs to be done, that's the right thing to
17118                    do.  */
17119                 if (VAR_P (decl))
17120                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17121                 if (VAR_P (decl) && !DECL_NAME (decl)
17122                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
17123                   /* Anonymous aggregates are a special case.  */
17124                   finish_anon_union (decl);
17125                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
17126                   {
17127                     DECL_CONTEXT (decl) = current_function_decl;
17128                     if (DECL_NAME (decl) == this_identifier)
17129                       {
17130                         tree lam = DECL_CONTEXT (current_function_decl);
17131                         lam = CLASSTYPE_LAMBDA_EXPR (lam);
17132                         LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
17133                       }
17134                     insert_capture_proxy (decl);
17135                   }
17136                 else if (DECL_IMPLICIT_TYPEDEF_P (t))
17137                   /* We already did a pushtag.  */;
17138                 else if (TREE_CODE (decl) == FUNCTION_DECL
17139                          && DECL_OMP_DECLARE_REDUCTION_P (decl)
17140                          && DECL_FUNCTION_SCOPE_P (pattern_decl))
17141                   {
17142                     DECL_CONTEXT (decl) = NULL_TREE;
17143                     pushdecl (decl);
17144                     DECL_CONTEXT (decl) = current_function_decl;
17145                     cp_check_omp_declare_reduction (decl);
17146                   }
17147                 else
17148                   {
17149                     int const_init = false;
17150                     unsigned int cnt = 0;
17151                     tree first = NULL_TREE, ndecl = error_mark_node;
17152                     maybe_push_decl (decl);
17153
17154                     if (VAR_P (decl)
17155                         && DECL_DECOMPOSITION_P (decl)
17156                         && TREE_TYPE (pattern_decl) != error_mark_node)
17157                       ndecl = tsubst_decomp_names (decl, pattern_decl, args,
17158                                                    complain, in_decl, &first,
17159                                                    &cnt);
17160
17161                     init = tsubst_init (init, decl, args, complain, in_decl);
17162
17163                     if (VAR_P (decl))
17164                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
17165                                     (pattern_decl));
17166
17167                     if (ndecl != error_mark_node)
17168                       cp_maybe_mangle_decomp (ndecl, first, cnt);
17169
17170                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
17171
17172                     if (ndecl != error_mark_node)
17173                       cp_finish_decomp (ndecl, first, cnt);
17174                   }
17175               }
17176           }
17177
17178         break;
17179       }
17180
17181     case FOR_STMT:
17182       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
17183       RECUR (FOR_INIT_STMT (t));
17184       finish_init_stmt (stmt);
17185       tmp = RECUR (FOR_COND (t));
17186       finish_for_cond (tmp, stmt, false, 0);
17187       tmp = RECUR (FOR_EXPR (t));
17188       finish_for_expr (tmp, stmt);
17189       {
17190         bool prev = note_iteration_stmt_body_start ();
17191         RECUR (FOR_BODY (t));
17192         note_iteration_stmt_body_end (prev);
17193       }
17194       finish_for_stmt (stmt);
17195       break;
17196
17197     case RANGE_FOR_STMT:
17198       {
17199         /* Construct another range_for, if this is not a final
17200            substitution (for inside inside a generic lambda of a
17201            template).  Otherwise convert to a regular for.  */
17202         tree decl, expr;
17203         stmt = (processing_template_decl
17204                 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
17205                 : begin_for_stmt (NULL_TREE, NULL_TREE));
17206         RECUR (RANGE_FOR_INIT_STMT (t));
17207         decl = RANGE_FOR_DECL (t);
17208         decl = tsubst (decl, args, complain, in_decl);
17209         maybe_push_decl (decl);
17210         expr = RECUR (RANGE_FOR_EXPR (t));
17211
17212         tree decomp_first = NULL_TREE;
17213         unsigned decomp_cnt = 0;
17214         if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
17215           decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
17216                                       complain, in_decl,
17217                                       &decomp_first, &decomp_cnt);
17218
17219         if (processing_template_decl)
17220           {
17221             RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
17222             RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
17223             finish_range_for_decl (stmt, decl, expr);
17224             if (decomp_first && decl != error_mark_node)
17225               cp_finish_decomp (decl, decomp_first, decomp_cnt);
17226           }
17227         else
17228           {
17229             unsigned short unroll = (RANGE_FOR_UNROLL (t)
17230                                      ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
17231             stmt = cp_convert_range_for (stmt, decl, expr,
17232                                          decomp_first, decomp_cnt,
17233                                          RANGE_FOR_IVDEP (t), unroll);
17234           }
17235
17236         bool prev = note_iteration_stmt_body_start ();
17237         RECUR (RANGE_FOR_BODY (t));
17238         note_iteration_stmt_body_end (prev);
17239         finish_for_stmt (stmt);
17240       }
17241       break;
17242
17243     case WHILE_STMT:
17244       stmt = begin_while_stmt ();
17245       tmp = RECUR (WHILE_COND (t));
17246       finish_while_stmt_cond (tmp, stmt, false, 0);
17247       {
17248         bool prev = note_iteration_stmt_body_start ();
17249         RECUR (WHILE_BODY (t));
17250         note_iteration_stmt_body_end (prev);
17251       }
17252       finish_while_stmt (stmt);
17253       break;
17254
17255     case DO_STMT:
17256       stmt = begin_do_stmt ();
17257       {
17258         bool prev = note_iteration_stmt_body_start ();
17259         RECUR (DO_BODY (t));
17260         note_iteration_stmt_body_end (prev);
17261       }
17262       finish_do_body (stmt);
17263       tmp = RECUR (DO_COND (t));
17264       finish_do_stmt (tmp, stmt, false, 0);
17265       break;
17266
17267     case IF_STMT:
17268       stmt = begin_if_stmt ();
17269       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
17270       if (IF_STMT_CONSTEXPR_P (t))
17271         args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
17272       tmp = RECUR (IF_COND (t));
17273       tmp = finish_if_stmt_cond (tmp, stmt);
17274       if (IF_STMT_CONSTEXPR_P (t)
17275           && instantiation_dependent_expression_p (tmp))
17276         {
17277           /* We're partially instantiating a generic lambda, but the condition
17278              of the constexpr if is still dependent.  Don't substitute into the
17279              branches now, just remember the template arguments.  */
17280           do_poplevel (IF_SCOPE (stmt));
17281           IF_COND (stmt) = IF_COND (t);
17282           THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
17283           ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
17284           IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
17285           add_stmt (stmt);
17286           break;
17287         }
17288       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
17289         /* Don't instantiate the THEN_CLAUSE. */;
17290       else
17291         {
17292           tree folded = fold_non_dependent_expr (tmp, complain);
17293           bool inhibit = integer_zerop (folded);
17294           if (inhibit)
17295             ++c_inhibit_evaluation_warnings;
17296           RECUR (THEN_CLAUSE (t));
17297           if (inhibit)
17298             --c_inhibit_evaluation_warnings;
17299         }
17300       finish_then_clause (stmt);
17301
17302       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
17303         /* Don't instantiate the ELSE_CLAUSE. */;
17304       else if (ELSE_CLAUSE (t))
17305         {
17306           tree folded = fold_non_dependent_expr (tmp, complain);
17307           bool inhibit = integer_nonzerop (folded);
17308           begin_else_clause (stmt);
17309           if (inhibit)
17310             ++c_inhibit_evaluation_warnings;
17311           RECUR (ELSE_CLAUSE (t));
17312           if (inhibit)
17313             --c_inhibit_evaluation_warnings;
17314           finish_else_clause (stmt);
17315         }
17316
17317       finish_if_stmt (stmt);
17318       break;
17319
17320     case BIND_EXPR:
17321       if (BIND_EXPR_BODY_BLOCK (t))
17322         stmt = begin_function_body ();
17323       else
17324         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
17325                                     ? BCS_TRY_BLOCK : 0);
17326
17327       RECUR (BIND_EXPR_BODY (t));
17328
17329       if (BIND_EXPR_BODY_BLOCK (t))
17330         finish_function_body (stmt);
17331       else
17332         finish_compound_stmt (stmt);
17333       break;
17334
17335     case BREAK_STMT:
17336       finish_break_stmt ();
17337       break;
17338
17339     case CONTINUE_STMT:
17340       finish_continue_stmt ();
17341       break;
17342
17343     case SWITCH_STMT:
17344       stmt = begin_switch_stmt ();
17345       tmp = RECUR (SWITCH_STMT_COND (t));
17346       finish_switch_cond (tmp, stmt);
17347       RECUR (SWITCH_STMT_BODY (t));
17348       finish_switch_stmt (stmt);
17349       break;
17350
17351     case CASE_LABEL_EXPR:
17352       {
17353         tree decl = CASE_LABEL (t);
17354         tree low = RECUR (CASE_LOW (t));
17355         tree high = RECUR (CASE_HIGH (t));
17356         tree l = finish_case_label (EXPR_LOCATION (t), low, high);
17357         if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
17358           {
17359             tree label = CASE_LABEL (l);
17360             FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
17361             if (DECL_ATTRIBUTES (decl) != NULL_TREE)
17362               cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
17363           }
17364       }
17365       break;
17366
17367     case LABEL_EXPR:
17368       {
17369         tree decl = LABEL_EXPR_LABEL (t);
17370         tree label;
17371
17372         label = finish_label_stmt (DECL_NAME (decl));
17373         if (TREE_CODE (label) == LABEL_DECL)
17374           FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
17375         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
17376           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
17377       }
17378       break;
17379
17380     case GOTO_EXPR:
17381       tmp = GOTO_DESTINATION (t);
17382       if (TREE_CODE (tmp) != LABEL_DECL)
17383         /* Computed goto's must be tsubst'd into.  On the other hand,
17384            non-computed gotos must not be; the identifier in question
17385            will have no binding.  */
17386         tmp = RECUR (tmp);
17387       else
17388         tmp = DECL_NAME (tmp);
17389       finish_goto_stmt (tmp);
17390       break;
17391
17392     case ASM_EXPR:
17393       {
17394         tree string = RECUR (ASM_STRING (t));
17395         tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
17396                                                  complain, in_decl);
17397         tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
17398                                                 complain, in_decl);
17399         tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
17400                                                   complain, in_decl);
17401         tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
17402                                                 complain, in_decl);
17403         tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
17404                                outputs, inputs, clobbers, labels,
17405                                ASM_INLINE_P (t));
17406         tree asm_expr = tmp;
17407         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
17408           asm_expr = TREE_OPERAND (asm_expr, 0);
17409         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
17410       }
17411       break;
17412
17413     case TRY_BLOCK:
17414       if (CLEANUP_P (t))
17415         {
17416           stmt = begin_try_block ();
17417           RECUR (TRY_STMTS (t));
17418           finish_cleanup_try_block (stmt);
17419           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
17420         }
17421       else
17422         {
17423           tree compound_stmt = NULL_TREE;
17424
17425           if (FN_TRY_BLOCK_P (t))
17426             stmt = begin_function_try_block (&compound_stmt);
17427           else
17428             stmt = begin_try_block ();
17429
17430           RECUR (TRY_STMTS (t));
17431
17432           if (FN_TRY_BLOCK_P (t))
17433             finish_function_try_block (stmt);
17434           else
17435             finish_try_block (stmt);
17436
17437           RECUR (TRY_HANDLERS (t));
17438           if (FN_TRY_BLOCK_P (t))
17439             finish_function_handler_sequence (stmt, compound_stmt);
17440           else
17441             finish_handler_sequence (stmt);
17442         }
17443       break;
17444
17445     case HANDLER:
17446       {
17447         tree decl = HANDLER_PARMS (t);
17448
17449         if (decl)
17450           {
17451             decl = tsubst (decl, args, complain, in_decl);
17452             /* Prevent instantiate_decl from trying to instantiate
17453                this variable.  We've already done all that needs to be
17454                done.  */
17455             if (decl != error_mark_node)
17456               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17457           }
17458         stmt = begin_handler ();
17459         finish_handler_parms (decl, stmt);
17460         RECUR (HANDLER_BODY (t));
17461         finish_handler (stmt);
17462       }
17463       break;
17464
17465     case TAG_DEFN:
17466       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17467       if (CLASS_TYPE_P (tmp))
17468         {
17469           /* Local classes are not independent templates; they are
17470              instantiated along with their containing function.  And this
17471              way we don't have to deal with pushing out of one local class
17472              to instantiate a member of another local class.  */
17473           /* Closures are handled by the LAMBDA_EXPR.  */
17474           gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17475           complete_type (tmp);
17476           for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17477             if ((VAR_P (fld)
17478                  || (TREE_CODE (fld) == FUNCTION_DECL
17479                      && !DECL_ARTIFICIAL (fld)))
17480                 && DECL_TEMPLATE_INSTANTIATION (fld))
17481               instantiate_decl (fld, /*defer_ok=*/false,
17482                                 /*expl_inst_class=*/false);
17483         }
17484       break;
17485
17486     case STATIC_ASSERT:
17487       {
17488         tree condition;
17489
17490         ++c_inhibit_evaluation_warnings;
17491         condition = 
17492           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
17493                        args,
17494                        complain, in_decl,
17495                        /*integral_constant_expression_p=*/true);
17496         --c_inhibit_evaluation_warnings;
17497
17498         finish_static_assert (condition,
17499                               STATIC_ASSERT_MESSAGE (t),
17500                               STATIC_ASSERT_SOURCE_LOCATION (t),
17501                               /*member_p=*/false);
17502       }
17503       break;
17504
17505     case OACC_KERNELS:
17506     case OACC_PARALLEL:
17507       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17508                                 in_decl);
17509       stmt = begin_omp_parallel ();
17510       RECUR (OMP_BODY (t));
17511       finish_omp_construct (TREE_CODE (t), stmt, tmp);
17512       break;
17513
17514     case OMP_PARALLEL:
17515       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17516       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17517                                 complain, in_decl);
17518       if (OMP_PARALLEL_COMBINED (t))
17519         omp_parallel_combined_clauses = &tmp;
17520       stmt = begin_omp_parallel ();
17521       RECUR (OMP_PARALLEL_BODY (t));
17522       gcc_assert (omp_parallel_combined_clauses == NULL);
17523       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17524         = OMP_PARALLEL_COMBINED (t);
17525       pop_omp_privatization_clauses (r);
17526       break;
17527
17528     case OMP_TASK:
17529       if (OMP_TASK_BODY (t) == NULL_TREE)
17530         {
17531           tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17532                                     complain, in_decl);
17533           t = copy_node (t);
17534           OMP_TASK_CLAUSES (t) = tmp;
17535           add_stmt (t);
17536           break;
17537         }
17538       r = push_omp_privatization_clauses (false);
17539       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17540                                 complain, in_decl);
17541       stmt = begin_omp_task ();
17542       RECUR (OMP_TASK_BODY (t));
17543       finish_omp_task (tmp, stmt);
17544       pop_omp_privatization_clauses (r);
17545       break;
17546
17547     case OMP_FOR:
17548     case OMP_LOOP:
17549     case OMP_SIMD:
17550     case OMP_DISTRIBUTE:
17551     case OMP_TASKLOOP:
17552     case OACC_LOOP:
17553       {
17554         tree clauses, body, pre_body;
17555         tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17556         tree orig_declv = NULL_TREE;
17557         tree incrv = NULL_TREE;
17558         enum c_omp_region_type ort = C_ORT_OMP;
17559         bool any_range_for = false;
17560         int i;
17561
17562         if (TREE_CODE (t) == OACC_LOOP)
17563           ort = C_ORT_ACC;
17564
17565         r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17566         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17567                                       in_decl);
17568         if (OMP_FOR_INIT (t) != NULL_TREE)
17569           {
17570             declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17571             if (OMP_FOR_ORIG_DECLS (t))
17572               orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17573             initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17574             condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17575             incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17576           }
17577
17578         keep_next_level (true);
17579         stmt = begin_omp_structured_block ();
17580
17581         pre_body = push_stmt_list ();
17582         RECUR (OMP_FOR_PRE_BODY (t));
17583         pre_body = pop_stmt_list (pre_body);
17584
17585         if (OMP_FOR_INIT (t) != NULL_TREE)
17586           for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17587             any_range_for
17588               |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
17589                                           condv, incrv, &clauses, args,
17590                                           complain, in_decl,
17591                                           integral_constant_expression_p);
17592         omp_parallel_combined_clauses = NULL;
17593
17594         if (any_range_for)
17595           {
17596             gcc_assert (orig_declv);
17597             body = begin_omp_structured_block ();
17598             for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17599               if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
17600                   && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
17601                   && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
17602                 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
17603                                          TREE_VEC_ELT (declv, i));
17604           }
17605         else
17606           body = push_stmt_list ();
17607         RECUR (OMP_FOR_BODY (t));
17608         if (any_range_for)
17609           body = finish_omp_structured_block (body);
17610         else
17611           body = pop_stmt_list (body);
17612
17613         if (OMP_FOR_INIT (t) != NULL_TREE)
17614           t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17615                               orig_declv, initv, condv, incrv, body, pre_body,
17616                               NULL, clauses);
17617         else
17618           {
17619             t = make_node (TREE_CODE (t));
17620             TREE_TYPE (t) = void_type_node;
17621             OMP_FOR_BODY (t) = body;
17622             OMP_FOR_PRE_BODY (t) = pre_body;
17623             OMP_FOR_CLAUSES (t) = clauses;
17624             SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17625             add_stmt (t);
17626           }
17627
17628         add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
17629                                         t));
17630         pop_omp_privatization_clauses (r);
17631       }
17632       break;
17633
17634     case OMP_SECTIONS:
17635       omp_parallel_combined_clauses = NULL;
17636       /* FALLTHRU */
17637     case OMP_SINGLE:
17638     case OMP_TEAMS:
17639     case OMP_CRITICAL:
17640     case OMP_TASKGROUP:
17641     case OMP_SCAN:
17642       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17643                                           && OMP_TEAMS_COMBINED (t));
17644       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17645                                 in_decl);
17646       if (TREE_CODE (t) == OMP_TEAMS)
17647         {
17648           keep_next_level (true);
17649           stmt = begin_omp_structured_block ();
17650           RECUR (OMP_BODY (t));
17651           stmt = finish_omp_structured_block (stmt);
17652         }
17653       else
17654         {
17655           stmt = push_stmt_list ();
17656           RECUR (OMP_BODY (t));
17657           stmt = pop_stmt_list (stmt);
17658         }
17659
17660       t = copy_node (t);
17661       OMP_BODY (t) = stmt;
17662       OMP_CLAUSES (t) = tmp;
17663       add_stmt (t);
17664       pop_omp_privatization_clauses (r);
17665       break;
17666
17667     case OMP_DEPOBJ:
17668       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
17669       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
17670         {
17671           enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
17672           if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
17673             {
17674               tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
17675                                         args, complain, in_decl);
17676               if (tmp == NULL_TREE)
17677                 tmp = error_mark_node;
17678             }
17679           else
17680             {
17681               kind = (enum omp_clause_depend_kind)
17682                      tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
17683               tmp = NULL_TREE;
17684             }
17685           finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
17686         }
17687       else
17688         finish_omp_depobj (EXPR_LOCATION (t), r,
17689                            OMP_CLAUSE_DEPEND_SOURCE,
17690                            OMP_DEPOBJ_CLAUSES (t));
17691       break;
17692
17693     case OACC_DATA:
17694     case OMP_TARGET_DATA:
17695     case OMP_TARGET:
17696       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17697                                 ? C_ORT_ACC : C_ORT_OMP, args, complain,
17698                                 in_decl);
17699       keep_next_level (true);
17700       stmt = begin_omp_structured_block ();
17701
17702       RECUR (OMP_BODY (t));
17703       stmt = finish_omp_structured_block (stmt);
17704
17705       t = copy_node (t);
17706       OMP_BODY (t) = stmt;
17707       OMP_CLAUSES (t) = tmp;
17708       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17709         {
17710           tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17711           if (teams)
17712             {
17713               /* For combined target teams, ensure the num_teams and
17714                  thread_limit clause expressions are evaluated on the host,
17715                  before entering the target construct.  */
17716               tree c;
17717               for (c = OMP_TEAMS_CLAUSES (teams);
17718                    c; c = OMP_CLAUSE_CHAIN (c))
17719                 if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17720                      || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17721                     && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17722                   {
17723                     tree expr = OMP_CLAUSE_OPERAND (c, 0);
17724                     expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17725                     if (expr == error_mark_node)
17726                       continue;
17727                     tmp = TARGET_EXPR_SLOT (expr);
17728                     add_stmt (expr);
17729                     OMP_CLAUSE_OPERAND (c, 0) = expr;
17730                     tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17731                                                 OMP_CLAUSE_FIRSTPRIVATE);
17732                     OMP_CLAUSE_DECL (tc) = tmp;
17733                     OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17734                     OMP_TARGET_CLAUSES (t) = tc;
17735                   }
17736             }
17737         }
17738       add_stmt (t);
17739       break;
17740
17741     case OACC_DECLARE:
17742       t = copy_node (t);
17743       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17744                                 complain, in_decl);
17745       OACC_DECLARE_CLAUSES (t) = tmp;
17746       add_stmt (t);
17747       break;
17748
17749     case OMP_TARGET_UPDATE:
17750     case OMP_TARGET_ENTER_DATA:
17751     case OMP_TARGET_EXIT_DATA:
17752       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17753                                 complain, in_decl);
17754       t = copy_node (t);
17755       OMP_STANDALONE_CLAUSES (t) = tmp;
17756       add_stmt (t);
17757       break;
17758
17759     case OACC_ENTER_DATA:
17760     case OACC_EXIT_DATA:
17761     case OACC_UPDATE:
17762       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17763                                 complain, in_decl);
17764       t = copy_node (t);
17765       OMP_STANDALONE_CLAUSES (t) = tmp;
17766       add_stmt (t);
17767       break;
17768
17769     case OMP_ORDERED:
17770       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17771                                 complain, in_decl);
17772       stmt = push_stmt_list ();
17773       RECUR (OMP_BODY (t));
17774       stmt = pop_stmt_list (stmt);
17775
17776       t = copy_node (t);
17777       OMP_BODY (t) = stmt;
17778       OMP_ORDERED_CLAUSES (t) = tmp;
17779       add_stmt (t);
17780       break;
17781
17782     case OMP_SECTION:
17783     case OMP_MASTER:
17784       stmt = push_stmt_list ();
17785       RECUR (OMP_BODY (t));
17786       stmt = pop_stmt_list (stmt);
17787
17788       t = copy_node (t);
17789       OMP_BODY (t) = stmt;
17790       add_stmt (t);
17791       break;
17792
17793     case OMP_ATOMIC:
17794       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17795       tmp = NULL_TREE;
17796       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
17797         tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
17798                                   complain, in_decl);
17799       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17800         {
17801           tree op1 = TREE_OPERAND (t, 1);
17802           tree rhs1 = NULL_TREE;
17803           tree lhs, rhs;
17804           if (TREE_CODE (op1) == COMPOUND_EXPR)
17805             {
17806               rhs1 = RECUR (TREE_OPERAND (op1, 0));
17807               op1 = TREE_OPERAND (op1, 1);
17808             }
17809           lhs = RECUR (TREE_OPERAND (op1, 0));
17810           rhs = RECUR (TREE_OPERAND (op1, 1));
17811           finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
17812                              lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
17813                              OMP_ATOMIC_MEMORY_ORDER (t));
17814         }
17815       else
17816         {
17817           tree op1 = TREE_OPERAND (t, 1);
17818           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17819           tree rhs1 = NULL_TREE;
17820           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17821           enum tree_code opcode = NOP_EXPR;
17822           if (code == OMP_ATOMIC_READ)
17823             {
17824               v = RECUR (TREE_OPERAND (op1, 0));
17825               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17826             }
17827           else if (code == OMP_ATOMIC_CAPTURE_OLD
17828                    || code == OMP_ATOMIC_CAPTURE_NEW)
17829             {
17830               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17831               v = RECUR (TREE_OPERAND (op1, 0));
17832               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17833               if (TREE_CODE (op11) == COMPOUND_EXPR)
17834                 {
17835                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
17836                   op11 = TREE_OPERAND (op11, 1);
17837                 }
17838               lhs = RECUR (TREE_OPERAND (op11, 0));
17839               rhs = RECUR (TREE_OPERAND (op11, 1));
17840               opcode = TREE_CODE (op11);
17841               if (opcode == MODIFY_EXPR)
17842                 opcode = NOP_EXPR;
17843             }
17844           else
17845             {
17846               code = OMP_ATOMIC;
17847               lhs = RECUR (TREE_OPERAND (op1, 0));
17848               rhs = RECUR (TREE_OPERAND (op1, 1));
17849             }
17850           finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
17851                              lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
17852         }
17853       break;
17854
17855     case TRANSACTION_EXPR:
17856       {
17857         int flags = 0;
17858         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17859         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17860
17861         if (TRANSACTION_EXPR_IS_STMT (t))
17862           {
17863             tree body = TRANSACTION_EXPR_BODY (t);
17864             tree noex = NULL_TREE;
17865             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17866               {
17867                 noex = MUST_NOT_THROW_COND (body);
17868                 if (noex == NULL_TREE)
17869                   noex = boolean_true_node;
17870                 body = TREE_OPERAND (body, 0);
17871               }
17872             stmt = begin_transaction_stmt (input_location, NULL, flags);
17873             RECUR (body);
17874             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17875           }
17876         else
17877           {
17878             stmt = build_transaction_expr (EXPR_LOCATION (t),
17879                                            RECUR (TRANSACTION_EXPR_BODY (t)),
17880                                            flags, NULL_TREE);
17881             RETURN (stmt);
17882           }
17883       }
17884       break;
17885
17886     case MUST_NOT_THROW_EXPR:
17887       {
17888         tree op0 = RECUR (TREE_OPERAND (t, 0));
17889         tree cond = RECUR (MUST_NOT_THROW_COND (t));
17890         RETURN (build_must_not_throw_expr (op0, cond));
17891       }
17892
17893     case EXPR_PACK_EXPANSION:
17894       error ("invalid use of pack expansion expression");
17895       RETURN (error_mark_node);
17896
17897     case NONTYPE_ARGUMENT_PACK:
17898       error ("use %<...%> to expand argument pack");
17899       RETURN (error_mark_node);
17900
17901     case COMPOUND_EXPR:
17902       tmp = RECUR (TREE_OPERAND (t, 0));
17903       if (tmp == NULL_TREE)
17904         /* If the first operand was a statement, we're done with it.  */
17905         RETURN (RECUR (TREE_OPERAND (t, 1)));
17906       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17907                                     RECUR (TREE_OPERAND (t, 1)),
17908                                     complain));
17909
17910     case ANNOTATE_EXPR:
17911       tmp = RECUR (TREE_OPERAND (t, 0));
17912       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17913                           TREE_TYPE (tmp), tmp,
17914                           RECUR (TREE_OPERAND (t, 1)),
17915                           RECUR (TREE_OPERAND (t, 2))));
17916
17917     case PREDICT_EXPR:
17918       RETURN (add_stmt (copy_node (t)));
17919
17920     default:
17921       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17922
17923       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17924                                     /*function_p=*/false,
17925                                     integral_constant_expression_p));
17926     }
17927
17928   RETURN (NULL_TREE);
17929  out:
17930   input_location = loc;
17931   return r;
17932 #undef RECUR
17933 #undef RETURN
17934 }
17935
17936 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17937    function.  For description of the body see comment above
17938    cp_parser_omp_declare_reduction_exprs.  */
17939
17940 static void
17941 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17942 {
17943   if (t == NULL_TREE || t == error_mark_node)
17944     return;
17945
17946   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17947
17948   tree_stmt_iterator tsi;
17949   int i;
17950   tree stmts[7];
17951   memset (stmts, 0, sizeof stmts);
17952   for (i = 0, tsi = tsi_start (t);
17953        i < 7 && !tsi_end_p (tsi);
17954        i++, tsi_next (&tsi))
17955     stmts[i] = tsi_stmt (tsi);
17956   gcc_assert (tsi_end_p (tsi));
17957
17958   if (i >= 3)
17959     {
17960       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17961                   && TREE_CODE (stmts[1]) == DECL_EXPR);
17962       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17963                              args, complain, in_decl);
17964       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17965                             args, complain, in_decl);
17966       DECL_CONTEXT (omp_out) = current_function_decl;
17967       DECL_CONTEXT (omp_in) = current_function_decl;
17968       keep_next_level (true);
17969       tree block = begin_omp_structured_block ();
17970       tsubst_expr (stmts[2], args, complain, in_decl, false);
17971       block = finish_omp_structured_block (block);
17972       block = maybe_cleanup_point_expr_void (block);
17973       add_decl_expr (omp_out);
17974       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17975         TREE_NO_WARNING (omp_out) = 1;
17976       add_decl_expr (omp_in);
17977       finish_expr_stmt (block);
17978     }
17979   if (i >= 6)
17980     {
17981       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17982                   && TREE_CODE (stmts[4]) == DECL_EXPR);
17983       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17984                               args, complain, in_decl);
17985       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17986                               args, complain, in_decl);
17987       DECL_CONTEXT (omp_priv) = current_function_decl;
17988       DECL_CONTEXT (omp_orig) = current_function_decl;
17989       keep_next_level (true);
17990       tree block = begin_omp_structured_block ();
17991       tsubst_expr (stmts[5], args, complain, in_decl, false);
17992       block = finish_omp_structured_block (block);
17993       block = maybe_cleanup_point_expr_void (block);
17994       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17995       add_decl_expr (omp_priv);
17996       add_decl_expr (omp_orig);
17997       finish_expr_stmt (block);
17998       if (i == 7)
17999         add_decl_expr (omp_orig);
18000     }
18001 }
18002
18003 /* T is a postfix-expression that is not being used in a function
18004    call.  Return the substituted version of T.  */
18005
18006 static tree
18007 tsubst_non_call_postfix_expression (tree t, tree args,
18008                                     tsubst_flags_t complain,
18009                                     tree in_decl)
18010 {
18011   if (TREE_CODE (t) == SCOPE_REF)
18012     t = tsubst_qualified_id (t, args, complain, in_decl,
18013                              /*done=*/false, /*address_p=*/false);
18014   else
18015     t = tsubst_copy_and_build (t, args, complain, in_decl,
18016                                /*function_p=*/false,
18017                                /*integral_constant_expression_p=*/false);
18018
18019   return t;
18020 }
18021
18022 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
18023    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
18024    dependent init-capture.  */
18025
18026 static void
18027 prepend_one_capture (tree field, tree init, tree &list,
18028                      tsubst_flags_t complain)
18029 {
18030   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
18031     {
18032       tree type = NULL_TREE;
18033       if (!init)
18034         {
18035           if (complain & tf_error)
18036             error ("empty initializer in lambda init-capture");
18037           init = error_mark_node;
18038         }
18039       else if (TREE_CODE (init) == TREE_LIST)
18040         init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
18041       if (!type)
18042         type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
18043       TREE_TYPE (field) = type;
18044       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
18045     }
18046   list = tree_cons (field, init, list);
18047 }
18048
18049 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
18050    instantiation context.  Instantiating a pack expansion containing a lambda
18051    might result in multiple lambdas all based on the same lambda in the
18052    template.  */
18053
18054 tree
18055 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18056 {
18057   tree oldfn = lambda_function (t);
18058   in_decl = oldfn;
18059
18060   tree r = build_lambda_expr ();
18061
18062   LAMBDA_EXPR_LOCATION (r)
18063     = LAMBDA_EXPR_LOCATION (t);
18064   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
18065     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
18066   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
18067   LAMBDA_EXPR_INSTANTIATED (r) = true;
18068
18069   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
18070     /* A lambda in a default argument outside a class gets no
18071        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
18072        tsubst_default_argument calls start_lambda_scope, so we need to
18073        specifically ignore it here, and use the global scope.  */
18074     record_null_lambda_scope (r);
18075   else
18076     record_lambda_scope (r);
18077
18078   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
18079               && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
18080
18081   vec<tree,va_gc>* field_packs = NULL;
18082
18083   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
18084        cap = TREE_CHAIN (cap))
18085     {
18086       tree ofield = TREE_PURPOSE (cap);
18087       if (PACK_EXPANSION_P (ofield))
18088         ofield = PACK_EXPANSION_PATTERN (ofield);
18089       tree field = tsubst_decl (ofield, args, complain);
18090
18091       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
18092         {
18093           /* Remember these for when we've pushed local_specializations.  */
18094           vec_safe_push (field_packs, ofield);
18095           vec_safe_push (field_packs, field);
18096         }
18097
18098       if (field == error_mark_node)
18099         return error_mark_node;
18100
18101       tree init = TREE_VALUE (cap);
18102       if (PACK_EXPANSION_P (init))
18103         init = tsubst_pack_expansion (init, args, complain, in_decl);
18104       else
18105         init = tsubst_copy_and_build (init, args, complain, in_decl,
18106                                       /*fn*/false, /*constexpr*/false);
18107
18108       if (TREE_CODE (field) == TREE_VEC)
18109         {
18110           int len = TREE_VEC_LENGTH (field);
18111           gcc_assert (TREE_CODE (init) == TREE_VEC
18112                       && TREE_VEC_LENGTH (init) == len);
18113           for (int i = 0; i < len; ++i)
18114             prepend_one_capture (TREE_VEC_ELT (field, i),
18115                                  TREE_VEC_ELT (init, i),
18116                                  LAMBDA_EXPR_CAPTURE_LIST (r),
18117                                  complain);
18118         }
18119       else
18120         {
18121           prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
18122                                complain);
18123
18124           if (id_equal (DECL_NAME (field), "__this"))
18125             LAMBDA_EXPR_THIS_CAPTURE (r) = field;
18126         }
18127     }
18128
18129   tree type = begin_lambda_type (r);
18130   if (type == error_mark_node)
18131     return error_mark_node;
18132
18133   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
18134   determine_visibility (TYPE_NAME (type));
18135
18136   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
18137
18138   tree oldtmpl = (generic_lambda_fn_p (oldfn)
18139                   ? DECL_TI_TEMPLATE (oldfn)
18140                   : NULL_TREE);
18141
18142   tree fntype = static_fn_type (oldfn);
18143   if (oldtmpl)
18144     ++processing_template_decl;
18145   fntype = tsubst (fntype, args, complain, in_decl);
18146   if (oldtmpl)
18147     --processing_template_decl;
18148
18149   if (fntype == error_mark_node)
18150     r = error_mark_node;
18151   else
18152     {
18153       /* The body of a lambda-expression is not a subexpression of the
18154          enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
18155          which would be skipped if cp_unevaluated_operand.  */
18156       cp_evaluated ev;
18157
18158       /* Fix the type of 'this'.  */
18159       fntype = build_memfn_type (fntype, type,
18160                                  type_memfn_quals (fntype),
18161                                  type_memfn_rqual (fntype));
18162       tree fn, tmpl;
18163       if (oldtmpl)
18164         {
18165           tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
18166           fn = DECL_TEMPLATE_RESULT (tmpl);
18167           finish_member_declaration (tmpl);
18168         }
18169       else
18170         {
18171           tmpl = NULL_TREE;
18172           fn = tsubst_function_decl (oldfn, args, complain, fntype);
18173           finish_member_declaration (fn);
18174         }
18175
18176       /* Let finish_function set this.  */
18177       DECL_DECLARED_CONSTEXPR_P (fn) = false;
18178
18179       bool nested = cfun;
18180       if (nested)
18181         push_function_context ();
18182       else
18183         /* Still increment function_depth so that we don't GC in the
18184            middle of an expression.  */
18185         ++function_depth;
18186
18187       local_specialization_stack s (lss_copy);
18188
18189       tree body = start_lambda_function (fn, r);
18190
18191       /* Now record them for lookup_init_capture_pack.  */
18192       int fplen = vec_safe_length (field_packs);
18193       for (int i = 0; i < fplen; )
18194         {
18195           tree pack = (*field_packs)[i++];
18196           tree inst = (*field_packs)[i++];
18197           register_local_specialization (inst, pack);
18198         }
18199       release_tree_vector (field_packs);
18200
18201       register_parameter_specializations (oldfn, fn);
18202
18203       if (oldtmpl)
18204         {
18205           /* We might not partially instantiate some parts of the function, so
18206              copy these flags from the original template.  */
18207           language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
18208           current_function_returns_value = ol->returns_value;
18209           current_function_returns_null = ol->returns_null;
18210           current_function_returns_abnormally = ol->returns_abnormally;
18211           current_function_infinite_loop = ol->infinite_loop;
18212         }
18213
18214       /* [temp.deduct] A lambda-expression appearing in a function type or a
18215          template parameter is not considered part of the immediate context for
18216          the purposes of template argument deduction. */
18217       complain = tf_warning_or_error;
18218
18219       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
18220                    /*constexpr*/false);
18221
18222       finish_lambda_function (body);
18223
18224       if (nested)
18225         pop_function_context ();
18226       else
18227         --function_depth;
18228
18229       /* The capture list was built up in reverse order; fix that now.  */
18230       LAMBDA_EXPR_CAPTURE_LIST (r)
18231         = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
18232
18233       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
18234
18235       maybe_add_lambda_conv_op (type);
18236     }
18237
18238   finish_struct (type, /*attr*/NULL_TREE);
18239
18240   insert_pending_capture_proxies ();
18241
18242   return r;
18243 }
18244
18245 /* Like tsubst but deals with expressions and performs semantic
18246    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
18247
18248 tree
18249 tsubst_copy_and_build (tree t,
18250                        tree args,
18251                        tsubst_flags_t complain,
18252                        tree in_decl,
18253                        bool function_p,
18254                        bool integral_constant_expression_p)
18255 {
18256 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
18257 #define RECUR(NODE)                                             \
18258   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
18259                          /*function_p=*/false,                  \
18260                          integral_constant_expression_p)
18261
18262   tree retval, op1;
18263   location_t loc;
18264
18265   if (t == NULL_TREE || t == error_mark_node)
18266     return t;
18267
18268   loc = input_location;
18269   if (location_t eloc = cp_expr_location (t))
18270     input_location = eloc;
18271
18272   /* N3276 decltype magic only applies to calls at the top level or on the
18273      right side of a comma.  */
18274   tsubst_flags_t decltype_flag = (complain & tf_decltype);
18275   complain &= ~tf_decltype;
18276
18277   switch (TREE_CODE (t))
18278     {
18279     case USING_DECL:
18280       t = DECL_NAME (t);
18281       /* Fall through.  */
18282     case IDENTIFIER_NODE:
18283       {
18284         tree decl;
18285         cp_id_kind idk;
18286         bool non_integral_constant_expression_p;
18287         const char *error_msg;
18288
18289         if (IDENTIFIER_CONV_OP_P (t))
18290           {
18291             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18292             t = make_conv_op_name (new_type);
18293           }
18294
18295         /* Look up the name.  */
18296         decl = lookup_name (t);
18297
18298         /* By convention, expressions use ERROR_MARK_NODE to indicate
18299            failure, not NULL_TREE.  */
18300         if (decl == NULL_TREE)
18301           decl = error_mark_node;
18302
18303         decl = finish_id_expression (t, decl, NULL_TREE,
18304                                      &idk,
18305                                      integral_constant_expression_p,
18306           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
18307                                      &non_integral_constant_expression_p,
18308                                      /*template_p=*/false,
18309                                      /*done=*/true,
18310                                      /*address_p=*/false,
18311                                      /*template_arg_p=*/false,
18312                                      &error_msg,
18313                                      input_location);
18314         if (error_msg)
18315           error (error_msg);
18316         if (!function_p && identifier_p (decl))
18317           {
18318             if (complain & tf_error)
18319               unqualified_name_lookup_error (decl);
18320             decl = error_mark_node;
18321           }
18322         RETURN (decl);
18323       }
18324
18325     case TEMPLATE_ID_EXPR:
18326       {
18327         tree object;
18328         tree templ = RECUR (TREE_OPERAND (t, 0));
18329         tree targs = TREE_OPERAND (t, 1);
18330
18331         if (targs)
18332           targs = tsubst_template_args (targs, args, complain, in_decl);
18333         if (targs == error_mark_node)
18334           RETURN (error_mark_node);
18335
18336         if (TREE_CODE (templ) == SCOPE_REF)
18337           {
18338             tree name = TREE_OPERAND (templ, 1);
18339             tree tid = lookup_template_function (name, targs);
18340             TREE_OPERAND (templ, 1) = tid;
18341             RETURN (templ);
18342           }
18343
18344         if (variable_template_p (templ))
18345           RETURN (lookup_and_finish_template_variable (templ, targs, complain));
18346
18347         if (TREE_CODE (templ) == COMPONENT_REF)
18348           {
18349             object = TREE_OPERAND (templ, 0);
18350             templ = TREE_OPERAND (templ, 1);
18351           }
18352         else
18353           object = NULL_TREE;
18354         templ = lookup_template_function (templ, targs);
18355
18356         if (object)
18357           RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
18358                          object, templ, NULL_TREE));
18359         else
18360           RETURN (baselink_for_fns (templ));
18361       }
18362
18363     case INDIRECT_REF:
18364       {
18365         tree r = RECUR (TREE_OPERAND (t, 0));
18366
18367         if (REFERENCE_REF_P (t))
18368           {
18369             /* A type conversion to reference type will be enclosed in
18370                such an indirect ref, but the substitution of the cast
18371                will have also added such an indirect ref.  */
18372             r = convert_from_reference (r);
18373           }
18374         else
18375           r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
18376                                     complain|decltype_flag);
18377
18378         if (REF_PARENTHESIZED_P (t))
18379           r = force_paren_expr (r);
18380
18381         RETURN (r);
18382       }
18383
18384     case NOP_EXPR:
18385       {
18386         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18387         tree op0 = RECUR (TREE_OPERAND (t, 0));
18388         RETURN (build_nop (type, op0));
18389       }
18390
18391     case IMPLICIT_CONV_EXPR:
18392       {
18393         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18394         tree expr = RECUR (TREE_OPERAND (t, 0));
18395         if (dependent_type_p (type) || type_dependent_expression_p (expr))
18396           {
18397             retval = copy_node (t);
18398             TREE_TYPE (retval) = type;
18399             TREE_OPERAND (retval, 0) = expr;
18400             RETURN (retval);
18401           }
18402         if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
18403           /* We'll pass this to convert_nontype_argument again, we don't need
18404              to actually perform any conversion here.  */
18405           RETURN (expr);
18406         int flags = LOOKUP_IMPLICIT;
18407         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
18408           flags = LOOKUP_NORMAL;
18409         if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
18410           flags |= LOOKUP_NO_NARROWING;
18411         RETURN (perform_implicit_conversion_flags (type, expr, complain,
18412                                                   flags));
18413       }
18414
18415     case CONVERT_EXPR:
18416       {
18417         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18418         tree op0 = RECUR (TREE_OPERAND (t, 0));
18419         if (op0 == error_mark_node)
18420           RETURN (error_mark_node);
18421         RETURN (build1 (CONVERT_EXPR, type, op0));
18422       }
18423
18424     case CAST_EXPR:
18425     case REINTERPRET_CAST_EXPR:
18426     case CONST_CAST_EXPR:
18427     case DYNAMIC_CAST_EXPR:
18428     case STATIC_CAST_EXPR:
18429       {
18430         tree type;
18431         tree op, r = NULL_TREE;
18432
18433         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18434         if (integral_constant_expression_p
18435             && !cast_valid_in_integral_constant_expression_p (type))
18436           {
18437             if (complain & tf_error)
18438               error ("a cast to a type other than an integral or "
18439                      "enumeration type cannot appear in a constant-expression");
18440             RETURN (error_mark_node);
18441           }
18442
18443         op = RECUR (TREE_OPERAND (t, 0));
18444
18445         warning_sentinel s(warn_useless_cast);
18446         warning_sentinel s2(warn_ignored_qualifiers);
18447         switch (TREE_CODE (t))
18448           {
18449           case CAST_EXPR:
18450             r = build_functional_cast (type, op, complain);
18451             break;
18452           case REINTERPRET_CAST_EXPR:
18453             r = build_reinterpret_cast (type, op, complain);
18454             break;
18455           case CONST_CAST_EXPR:
18456             r = build_const_cast (type, op, complain);
18457             break;
18458           case DYNAMIC_CAST_EXPR:
18459             r = build_dynamic_cast (type, op, complain);
18460             break;
18461           case STATIC_CAST_EXPR:
18462             r = build_static_cast (type, op, complain);
18463             break;
18464           default:
18465             gcc_unreachable ();
18466           }
18467
18468         RETURN (r);
18469       }
18470
18471     case POSTDECREMENT_EXPR:
18472     case POSTINCREMENT_EXPR:
18473       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18474                                                 args, complain, in_decl);
18475       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
18476                                 complain|decltype_flag));
18477
18478     case PREDECREMENT_EXPR:
18479     case PREINCREMENT_EXPR:
18480     case NEGATE_EXPR:
18481     case BIT_NOT_EXPR:
18482     case ABS_EXPR:
18483     case TRUTH_NOT_EXPR:
18484     case UNARY_PLUS_EXPR:  /* Unary + */
18485     case REALPART_EXPR:
18486     case IMAGPART_EXPR:
18487       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
18488                                 RECUR (TREE_OPERAND (t, 0)),
18489                                 complain|decltype_flag));
18490
18491     case FIX_TRUNC_EXPR:
18492       gcc_unreachable ();
18493
18494     case ADDR_EXPR:
18495       op1 = TREE_OPERAND (t, 0);
18496       if (TREE_CODE (op1) == LABEL_DECL)
18497         RETURN (finish_label_address_expr (DECL_NAME (op1),
18498                                           EXPR_LOCATION (op1)));
18499       if (TREE_CODE (op1) == SCOPE_REF)
18500         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
18501                                    /*done=*/true, /*address_p=*/true);
18502       else
18503         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
18504                                                   in_decl);
18505       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
18506                                 complain|decltype_flag));
18507
18508     case PLUS_EXPR:
18509     case MINUS_EXPR:
18510     case MULT_EXPR:
18511     case TRUNC_DIV_EXPR:
18512     case CEIL_DIV_EXPR:
18513     case FLOOR_DIV_EXPR:
18514     case ROUND_DIV_EXPR:
18515     case EXACT_DIV_EXPR:
18516     case BIT_AND_EXPR:
18517     case BIT_IOR_EXPR:
18518     case BIT_XOR_EXPR:
18519     case TRUNC_MOD_EXPR:
18520     case FLOOR_MOD_EXPR:
18521     case TRUTH_ANDIF_EXPR:
18522     case TRUTH_ORIF_EXPR:
18523     case TRUTH_AND_EXPR:
18524     case TRUTH_OR_EXPR:
18525     case RSHIFT_EXPR:
18526     case LSHIFT_EXPR:
18527     case RROTATE_EXPR:
18528     case LROTATE_EXPR:
18529     case EQ_EXPR:
18530     case NE_EXPR:
18531     case MAX_EXPR:
18532     case MIN_EXPR:
18533     case LE_EXPR:
18534     case GE_EXPR:
18535     case LT_EXPR:
18536     case GT_EXPR:
18537     case MEMBER_REF:
18538     case DOTSTAR_EXPR:
18539       {
18540         warning_sentinel s1(warn_type_limits);
18541         warning_sentinel s2(warn_div_by_zero);
18542         warning_sentinel s3(warn_logical_op);
18543         warning_sentinel s4(warn_tautological_compare);
18544         tree op0 = RECUR (TREE_OPERAND (t, 0));
18545         tree op1 = RECUR (TREE_OPERAND (t, 1));
18546         tree r = build_x_binary_op
18547           (input_location, TREE_CODE (t),
18548            op0,
18549            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
18550             ? ERROR_MARK
18551             : TREE_CODE (TREE_OPERAND (t, 0))),
18552            op1,
18553            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
18554             ? ERROR_MARK
18555             : TREE_CODE (TREE_OPERAND (t, 1))),
18556            /*overload=*/NULL,
18557            complain|decltype_flag);
18558         if (EXPR_P (r) && TREE_NO_WARNING (t))
18559           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18560
18561         RETURN (r);
18562       }
18563
18564     case POINTER_PLUS_EXPR:
18565       {
18566         tree op0 = RECUR (TREE_OPERAND (t, 0));
18567         tree op1 = RECUR (TREE_OPERAND (t, 1));
18568         RETURN (fold_build_pointer_plus (op0, op1));
18569       }
18570
18571     case SCOPE_REF:
18572       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18573                                   /*address_p=*/false));
18574     case ARRAY_REF:
18575       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18576                                                 args, complain, in_decl);
18577       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18578                                  RECUR (TREE_OPERAND (t, 1)),
18579                                  complain|decltype_flag));
18580
18581     case SIZEOF_EXPR:
18582       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18583           || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18584         RETURN (tsubst_copy (t, args, complain, in_decl));
18585       /* Fall through */
18586
18587     case ALIGNOF_EXPR:
18588       {
18589         tree r;
18590
18591         op1 = TREE_OPERAND (t, 0);
18592         if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18593           op1 = TREE_TYPE (op1);
18594         bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18595                             && ALIGNOF_EXPR_STD_P (t));
18596         if (!args)
18597           {
18598             /* When there are no ARGS, we are trying to evaluate a
18599                non-dependent expression from the parser.  Trying to do
18600                the substitutions may not work.  */
18601             if (!TYPE_P (op1))
18602               op1 = TREE_TYPE (op1);
18603           }
18604         else
18605           {
18606             ++cp_unevaluated_operand;
18607             ++c_inhibit_evaluation_warnings;
18608             if (TYPE_P (op1))
18609               op1 = tsubst (op1, args, complain, in_decl);
18610             else
18611               op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18612                                            /*function_p=*/false,
18613                                            /*integral_constant_expression_p=*/
18614                                            false);
18615             --cp_unevaluated_operand;
18616             --c_inhibit_evaluation_warnings;
18617           }
18618         if (TYPE_P (op1))
18619           r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18620                                           complain & tf_error);
18621         else
18622           r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18623                                           complain & tf_error);
18624         if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18625           {
18626             if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18627               {
18628                 if (!processing_template_decl && TYPE_P (op1))
18629                   {
18630                     r = build_min (SIZEOF_EXPR, size_type_node,
18631                                    build1 (NOP_EXPR, op1, error_mark_node));
18632                     SIZEOF_EXPR_TYPE_P (r) = 1;
18633                   }
18634                 else
18635                   r = build_min (SIZEOF_EXPR, size_type_node, op1);
18636                 TREE_SIDE_EFFECTS (r) = 0;
18637                 TREE_READONLY (r) = 1;
18638               }
18639             SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18640           }
18641         RETURN (r);
18642       }
18643
18644     case AT_ENCODE_EXPR:
18645       {
18646         op1 = TREE_OPERAND (t, 0);
18647         ++cp_unevaluated_operand;
18648         ++c_inhibit_evaluation_warnings;
18649         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18650                                      /*function_p=*/false,
18651                                      /*integral_constant_expression_p=*/false);
18652         --cp_unevaluated_operand;
18653         --c_inhibit_evaluation_warnings;
18654         RETURN (objc_build_encode_expr (op1));
18655       }
18656
18657     case NOEXCEPT_EXPR:
18658       op1 = TREE_OPERAND (t, 0);
18659       ++cp_unevaluated_operand;
18660       ++c_inhibit_evaluation_warnings;
18661       ++cp_noexcept_operand;
18662       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18663                                    /*function_p=*/false,
18664                                    /*integral_constant_expression_p=*/false);
18665       --cp_unevaluated_operand;
18666       --c_inhibit_evaluation_warnings;
18667       --cp_noexcept_operand;
18668       RETURN (finish_noexcept_expr (op1, complain));
18669
18670     case MODOP_EXPR:
18671       {
18672         warning_sentinel s(warn_div_by_zero);
18673         tree lhs = RECUR (TREE_OPERAND (t, 0));
18674         tree rhs = RECUR (TREE_OPERAND (t, 2));
18675         tree r = build_x_modify_expr
18676           (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18677            complain|decltype_flag);
18678         /* TREE_NO_WARNING must be set if either the expression was
18679            parenthesized or it uses an operator such as >>= rather
18680            than plain assignment.  In the former case, it was already
18681            set and must be copied.  In the latter case,
18682            build_x_modify_expr sets it and it must not be reset
18683            here.  */
18684         if (TREE_NO_WARNING (t))
18685           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18686
18687         RETURN (r);
18688       }
18689
18690     case ARROW_EXPR:
18691       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18692                                                 args, complain, in_decl);
18693       /* Remember that there was a reference to this entity.  */
18694       if (DECL_P (op1)
18695           && !mark_used (op1, complain) && !(complain & tf_error))
18696         RETURN (error_mark_node);
18697       RETURN (build_x_arrow (input_location, op1, complain));
18698
18699     case NEW_EXPR:
18700       {
18701         tree placement = RECUR (TREE_OPERAND (t, 0));
18702         tree init = RECUR (TREE_OPERAND (t, 3));
18703         vec<tree, va_gc> *placement_vec;
18704         vec<tree, va_gc> *init_vec;
18705         tree ret;
18706
18707         if (placement == NULL_TREE)
18708           placement_vec = NULL;
18709         else
18710           {
18711             placement_vec = make_tree_vector ();
18712             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18713               vec_safe_push (placement_vec, TREE_VALUE (placement));
18714           }
18715
18716         /* If there was an initializer in the original tree, but it
18717            instantiated to an empty list, then we should pass a
18718            non-NULL empty vector to tell build_new that it was an
18719            empty initializer() rather than no initializer.  This can
18720            only happen when the initializer is a pack expansion whose
18721            parameter packs are of length zero.  */
18722         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18723           init_vec = NULL;
18724         else
18725           {
18726             init_vec = make_tree_vector ();
18727             if (init == void_node)
18728               gcc_assert (init_vec != NULL);
18729             else
18730               {
18731                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
18732                   vec_safe_push (init_vec, TREE_VALUE (init));
18733               }
18734           }
18735
18736         /* Avoid passing an enclosing decl to valid_array_size_p.  */
18737         in_decl = NULL_TREE;
18738
18739         tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18740         tree op2 = RECUR (TREE_OPERAND (t, 2));
18741         ret = build_new (&placement_vec, op1, op2, &init_vec,
18742                          NEW_EXPR_USE_GLOBAL (t),
18743                          complain);
18744
18745         if (placement_vec != NULL)
18746           release_tree_vector (placement_vec);
18747         if (init_vec != NULL)
18748           release_tree_vector (init_vec);
18749
18750         RETURN (ret);
18751       }
18752
18753     case DELETE_EXPR:
18754       {
18755         tree op0 = RECUR (TREE_OPERAND (t, 0));
18756         tree op1 = RECUR (TREE_OPERAND (t, 1));
18757         RETURN (delete_sanity (op0, op1,
18758                                DELETE_EXPR_USE_VEC (t),
18759                                DELETE_EXPR_USE_GLOBAL (t),
18760                                complain));
18761       }
18762
18763     case COMPOUND_EXPR:
18764       {
18765         tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18766                                           complain & ~tf_decltype, in_decl,
18767                                           /*function_p=*/false,
18768                                           integral_constant_expression_p);
18769         RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18770                                        op0,
18771                                        RECUR (TREE_OPERAND (t, 1)),
18772                                        complain|decltype_flag));
18773       }
18774
18775     case CALL_EXPR:
18776       {
18777         tree function;
18778         unsigned int nargs, i;
18779         bool qualified_p;
18780         bool koenig_p;
18781         tree ret;
18782
18783         function = CALL_EXPR_FN (t);
18784         /* Internal function with no arguments.  */
18785         if (function == NULL_TREE && call_expr_nargs (t) == 0)
18786           RETURN (t);
18787
18788         /* When we parsed the expression, we determined whether or
18789            not Koenig lookup should be performed.  */
18790         koenig_p = KOENIG_LOOKUP_P (t);
18791         if (function == NULL_TREE)
18792           {
18793             koenig_p = false;
18794             qualified_p = false;
18795           }
18796         else if (TREE_CODE (function) == SCOPE_REF)
18797           {
18798             qualified_p = true;
18799             function = tsubst_qualified_id (function, args, complain, in_decl,
18800                                             /*done=*/false,
18801                                             /*address_p=*/false);
18802           }
18803         else if (koenig_p && identifier_p (function))
18804           {
18805             /* Do nothing; calling tsubst_copy_and_build on an identifier
18806                would incorrectly perform unqualified lookup again.
18807
18808                Note that we can also have an IDENTIFIER_NODE if the earlier
18809                unqualified lookup found a member function; in that case
18810                koenig_p will be false and we do want to do the lookup
18811                again to find the instantiated member function.
18812
18813                FIXME but doing that causes c++/15272, so we need to stop
18814                using IDENTIFIER_NODE in that situation.  */
18815             qualified_p = false;
18816           }
18817         else
18818           {
18819             if (TREE_CODE (function) == COMPONENT_REF)
18820               {
18821                 tree op = TREE_OPERAND (function, 1);
18822
18823                 qualified_p = (TREE_CODE (op) == SCOPE_REF
18824                                || (BASELINK_P (op)
18825                                    && BASELINK_QUALIFIED_P (op)));
18826               }
18827             else
18828               qualified_p = false;
18829
18830             if (TREE_CODE (function) == ADDR_EXPR
18831                 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18832               /* Avoid error about taking the address of a constructor.  */
18833               function = TREE_OPERAND (function, 0);
18834
18835             function = tsubst_copy_and_build (function, args, complain,
18836                                               in_decl,
18837                                               !qualified_p,
18838                                               integral_constant_expression_p);
18839
18840             if (BASELINK_P (function))
18841               qualified_p = true;
18842           }
18843
18844         nargs = call_expr_nargs (t);
18845         releasing_vec call_args;
18846         for (i = 0; i < nargs; ++i)
18847           {
18848             tree arg = CALL_EXPR_ARG (t, i);
18849
18850             if (!PACK_EXPANSION_P (arg))
18851               vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18852             else
18853               {
18854                 /* Expand the pack expansion and push each entry onto
18855                    CALL_ARGS.  */
18856                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18857                 if (TREE_CODE (arg) == TREE_VEC)
18858                   {
18859                     unsigned int len, j;
18860
18861                     len = TREE_VEC_LENGTH (arg);
18862                     for (j = 0; j < len; ++j)
18863                       {
18864                         tree value = TREE_VEC_ELT (arg, j);
18865                         if (value != NULL_TREE)
18866                           value = convert_from_reference (value);
18867                         vec_safe_push (call_args, value);
18868                       }
18869                   }
18870                 else
18871                   {
18872                     /* A partial substitution.  Add one entry.  */
18873                     vec_safe_push (call_args, arg);
18874                   }
18875               }
18876           }
18877
18878         /* Stripped-down processing for a call in a thunk.  Specifically, in
18879            the thunk template for a generic lambda.  */
18880         if (CALL_FROM_THUNK_P (t))
18881           {
18882             /* Now that we've expanded any packs, the number of call args
18883                might be different.  */
18884             unsigned int cargs = call_args->length ();
18885             tree thisarg = NULL_TREE;
18886             if (TREE_CODE (function) == COMPONENT_REF)
18887               {
18888                 thisarg = TREE_OPERAND (function, 0);
18889                 if (TREE_CODE (thisarg) == INDIRECT_REF)
18890                   thisarg = TREE_OPERAND (thisarg, 0);
18891                 function = TREE_OPERAND (function, 1);
18892                 if (TREE_CODE (function) == BASELINK)
18893                   function = BASELINK_FUNCTIONS (function);
18894               }
18895             /* We aren't going to do normal overload resolution, so force the
18896                template-id to resolve.  */
18897             function = resolve_nondeduced_context (function, complain);
18898             for (unsigned i = 0; i < cargs; ++i)
18899               {
18900                 /* In a thunk, pass through args directly, without any
18901                    conversions.  */
18902                 tree arg = (*call_args)[i];
18903                 while (TREE_CODE (arg) != PARM_DECL)
18904                   arg = TREE_OPERAND (arg, 0);
18905                 (*call_args)[i] = arg;
18906               }
18907             if (thisarg)
18908               {
18909                 /* If there are no other args, just push 'this'.  */
18910                 if (cargs == 0)
18911                   vec_safe_push (call_args, thisarg);
18912                 else
18913                   {
18914                     /* Otherwise, shift the other args over to make room.  */
18915                     tree last = (*call_args)[cargs - 1];
18916                     vec_safe_push (call_args, last);
18917                     for (int i = cargs - 1; i > 0; --i)
18918                       (*call_args)[i] = (*call_args)[i - 1];
18919                     (*call_args)[0] = thisarg;
18920                   }
18921               }
18922             ret = build_call_a (function, call_args->length (),
18923                                 call_args->address ());
18924             /* The thunk location is not interesting.  */
18925             SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
18926             CALL_FROM_THUNK_P (ret) = true;
18927             if (CLASS_TYPE_P (TREE_TYPE (ret)))
18928               CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
18929
18930             RETURN (ret);
18931           }
18932
18933         /* We do not perform argument-dependent lookup if normal
18934            lookup finds a non-function, in accordance with the
18935            expected resolution of DR 218.  */
18936         if (koenig_p
18937             && ((is_overloaded_fn (function)
18938                  /* If lookup found a member function, the Koenig lookup is
18939                     not appropriate, even if an unqualified-name was used
18940                     to denote the function.  */
18941                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18942                 || identifier_p (function))
18943             /* Only do this when substitution turns a dependent call
18944                into a non-dependent call.  */
18945             && type_dependent_expression_p_push (t)
18946             && !any_type_dependent_arguments_p (call_args))
18947           function = perform_koenig_lookup (function, call_args, tf_none);
18948
18949         if (function != NULL_TREE
18950             && identifier_p (function)
18951             && !any_type_dependent_arguments_p (call_args))
18952           {
18953             if (koenig_p && (complain & tf_warning_or_error))
18954               {
18955                 /* For backwards compatibility and good diagnostics, try
18956                    the unqualified lookup again if we aren't in SFINAE
18957                    context.  */
18958                 tree unq = (tsubst_copy_and_build
18959                             (function, args, complain, in_decl, true,
18960                              integral_constant_expression_p));
18961                 if (unq == error_mark_node)
18962                   RETURN (error_mark_node);
18963
18964                 if (unq != function)
18965                   {
18966                     /* In a lambda fn, we have to be careful to not
18967                        introduce new this captures.  Legacy code can't
18968                        be using lambdas anyway, so it's ok to be
18969                        stricter.  */
18970                     bool in_lambda = (current_class_type
18971                                       && LAMBDA_TYPE_P (current_class_type));
18972                     char const *const msg
18973                       = G_("%qD was not declared in this scope, "
18974                            "and no declarations were found by "
18975                            "argument-dependent lookup at the point "
18976                            "of instantiation");
18977
18978                     bool diag = true;
18979                     if (in_lambda)
18980                       error_at (cp_expr_loc_or_input_loc (t),
18981                                 msg, function);
18982                     else
18983                       diag = permerror (cp_expr_loc_or_input_loc (t),
18984                                         msg, function);
18985                     if (diag)
18986                       {
18987                         tree fn = unq;
18988
18989                         if (INDIRECT_REF_P (fn))
18990                           fn = TREE_OPERAND (fn, 0);
18991                         if (is_overloaded_fn (fn))
18992                           fn = get_first_fn (fn);
18993
18994                         if (!DECL_P (fn))
18995                           /* Can't say anything more.  */;
18996                         else if (DECL_CLASS_SCOPE_P (fn))
18997                           {
18998                             location_t loc = cp_expr_loc_or_input_loc (t);
18999                             inform (loc,
19000                                     "declarations in dependent base %qT are "
19001                                     "not found by unqualified lookup",
19002                                     DECL_CLASS_CONTEXT (fn));
19003                             if (current_class_ptr)
19004                               inform (loc,
19005                                       "use %<this->%D%> instead", function);
19006                             else
19007                               inform (loc,
19008                                       "use %<%T::%D%> instead",
19009                                       current_class_name, function);
19010                           }
19011                         else
19012                           inform (DECL_SOURCE_LOCATION (fn),
19013                                   "%qD declared here, later in the "
19014                                   "translation unit", fn);
19015                         if (in_lambda)
19016                           RETURN (error_mark_node);
19017                       }
19018
19019                     function = unq;
19020                   }
19021               }
19022             if (identifier_p (function))
19023               {
19024                 if (complain & tf_error)
19025                   unqualified_name_lookup_error (function);
19026                 RETURN (error_mark_node);
19027               }
19028           }
19029
19030         /* Remember that there was a reference to this entity.  */
19031         if (function != NULL_TREE
19032             && DECL_P (function)
19033             && !mark_used (function, complain) && !(complain & tf_error))
19034           RETURN (error_mark_node);
19035
19036         /* Put back tf_decltype for the actual call.  */
19037         complain |= decltype_flag;
19038
19039         if (function == NULL_TREE)
19040           switch (CALL_EXPR_IFN (t))
19041             {
19042             case IFN_LAUNDER:
19043               gcc_assert (nargs == 1);
19044               if (vec_safe_length (call_args) != 1)
19045                 {
19046                   error_at (cp_expr_loc_or_input_loc (t),
19047                             "wrong number of arguments to "
19048                             "%<__builtin_launder%>");
19049                   ret = error_mark_node;
19050                 }
19051               else
19052                 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
19053                                               (*call_args)[0], complain);
19054               break;
19055
19056             case IFN_VEC_CONVERT:
19057               gcc_assert (nargs == 1);
19058               if (vec_safe_length (call_args) != 1)
19059                 {
19060                   error_at (cp_expr_loc_or_input_loc (t),
19061                             "wrong number of arguments to "
19062                             "%<__builtin_convertvector%>");
19063                   ret = error_mark_node;
19064                   break;
19065                 }
19066               ret = cp_build_vec_convert ((*call_args)[0], input_location,
19067                                           tsubst (TREE_TYPE (t), args,
19068                                                   complain, in_decl),
19069                                           complain);
19070               if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
19071                 RETURN (ret);
19072               break;
19073
19074             default:
19075               /* Unsupported internal function with arguments.  */
19076               gcc_unreachable ();
19077             }
19078         else if (TREE_CODE (function) == OFFSET_REF
19079                  || TREE_CODE (function) == DOTSTAR_EXPR
19080                  || TREE_CODE (function) == MEMBER_REF)
19081           ret = build_offset_ref_call_from_tree (function, &call_args,
19082                                                  complain);
19083         else if (TREE_CODE (function) == COMPONENT_REF)
19084           {
19085             tree instance = TREE_OPERAND (function, 0);
19086             tree fn = TREE_OPERAND (function, 1);
19087
19088             if (processing_template_decl
19089                 && (type_dependent_expression_p (instance)
19090                     || (!BASELINK_P (fn)
19091                         && TREE_CODE (fn) != FIELD_DECL)
19092                     || type_dependent_expression_p (fn)
19093                     || any_type_dependent_arguments_p (call_args)))
19094               ret = build_min_nt_call_vec (function, call_args);
19095             else if (!BASELINK_P (fn))
19096               ret = finish_call_expr (function, &call_args,
19097                                        /*disallow_virtual=*/false,
19098                                        /*koenig_p=*/false,
19099                                        complain);
19100             else
19101               ret = (build_new_method_call
19102                       (instance, fn,
19103                        &call_args, NULL_TREE,
19104                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
19105                        /*fn_p=*/NULL,
19106                        complain));
19107           }
19108         else
19109           ret = finish_call_expr (function, &call_args,
19110                                   /*disallow_virtual=*/qualified_p,
19111                                   koenig_p,
19112                                   complain);
19113
19114         if (ret != error_mark_node)
19115           {
19116             bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
19117             bool ord = CALL_EXPR_ORDERED_ARGS (t);
19118             bool rev = CALL_EXPR_REVERSE_ARGS (t);
19119             if (op || ord || rev)
19120               {
19121                 function = extract_call_expr (ret);
19122                 CALL_EXPR_OPERATOR_SYNTAX (function) = op;
19123                 CALL_EXPR_ORDERED_ARGS (function) = ord;
19124                 CALL_EXPR_REVERSE_ARGS (function) = rev;
19125               }
19126           }
19127
19128         RETURN (ret);
19129       }
19130
19131     case COND_EXPR:
19132       {
19133         tree cond = RECUR (TREE_OPERAND (t, 0));
19134         cond = mark_rvalue_use (cond);
19135         tree folded_cond = fold_non_dependent_expr (cond, complain);
19136         tree exp1, exp2;
19137
19138         if (TREE_CODE (folded_cond) == INTEGER_CST)
19139           {
19140             if (integer_zerop (folded_cond))
19141               {
19142                 ++c_inhibit_evaluation_warnings;
19143                 exp1 = RECUR (TREE_OPERAND (t, 1));
19144                 --c_inhibit_evaluation_warnings;
19145                 exp2 = RECUR (TREE_OPERAND (t, 2));
19146               }
19147             else
19148               {
19149                 exp1 = RECUR (TREE_OPERAND (t, 1));
19150                 ++c_inhibit_evaluation_warnings;
19151                 exp2 = RECUR (TREE_OPERAND (t, 2));
19152                 --c_inhibit_evaluation_warnings;
19153               }
19154             cond = folded_cond;
19155           }
19156         else
19157           {
19158             exp1 = RECUR (TREE_OPERAND (t, 1));
19159             exp2 = RECUR (TREE_OPERAND (t, 2));
19160           }
19161
19162         warning_sentinel s(warn_duplicated_branches);
19163         RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
19164                                          cond, exp1, exp2, complain));
19165       }
19166
19167     case PSEUDO_DTOR_EXPR:
19168       {
19169         tree op0 = RECUR (TREE_OPERAND (t, 0));
19170         tree op1 = RECUR (TREE_OPERAND (t, 1));
19171         tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
19172         RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
19173                                                input_location));
19174       }
19175
19176     case TREE_LIST:
19177       {
19178         tree purpose, value, chain;
19179
19180         if (t == void_list_node)
19181           RETURN (t);
19182
19183         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
19184             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
19185           {
19186             /* We have pack expansions, so expand those and
19187                create a new list out of it.  */
19188             tree purposevec = NULL_TREE;
19189             tree valuevec = NULL_TREE;
19190             tree chain;
19191             int i, len = -1;
19192
19193             /* Expand the argument expressions.  */
19194             if (TREE_PURPOSE (t))
19195               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
19196                                                  complain, in_decl);
19197             if (TREE_VALUE (t))
19198               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
19199                                                complain, in_decl);
19200
19201             /* Build the rest of the list.  */
19202             chain = TREE_CHAIN (t);
19203             if (chain && chain != void_type_node)
19204               chain = RECUR (chain);
19205
19206             /* Determine the number of arguments.  */
19207             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
19208               {
19209                 len = TREE_VEC_LENGTH (purposevec);
19210                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
19211               }
19212             else if (TREE_CODE (valuevec) == TREE_VEC)
19213               len = TREE_VEC_LENGTH (valuevec);
19214             else
19215               {
19216                 /* Since we only performed a partial substitution into
19217                    the argument pack, we only RETURN (a single list
19218                    node.  */
19219                 if (purposevec == TREE_PURPOSE (t)
19220                     && valuevec == TREE_VALUE (t)
19221                     && chain == TREE_CHAIN (t))
19222                   RETURN (t);
19223
19224                 RETURN (tree_cons (purposevec, valuevec, chain));
19225               }
19226
19227             /* Convert the argument vectors into a TREE_LIST */
19228             i = len;
19229             while (i > 0)
19230               {
19231                 /* Grab the Ith values.  */
19232                 i--;
19233                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
19234                                      : NULL_TREE;
19235                 value 
19236                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
19237                              : NULL_TREE;
19238
19239                 /* Build the list (backwards).  */
19240                 chain = tree_cons (purpose, value, chain);
19241               }
19242
19243             RETURN (chain);
19244           }
19245
19246         purpose = TREE_PURPOSE (t);
19247         if (purpose)
19248           purpose = RECUR (purpose);
19249         value = TREE_VALUE (t);
19250         if (value)
19251           value = RECUR (value);
19252         chain = TREE_CHAIN (t);
19253         if (chain && chain != void_type_node)
19254           chain = RECUR (chain);
19255         if (purpose == TREE_PURPOSE (t)
19256             && value == TREE_VALUE (t)
19257             && chain == TREE_CHAIN (t))
19258           RETURN (t);
19259         RETURN (tree_cons (purpose, value, chain));
19260       }
19261
19262     case COMPONENT_REF:
19263       {
19264         tree object;
19265         tree object_type;
19266         tree member;
19267         tree r;
19268
19269         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19270                                                      args, complain, in_decl);
19271         /* Remember that there was a reference to this entity.  */
19272         if (DECL_P (object)
19273             && !mark_used (object, complain) && !(complain & tf_error))
19274           RETURN (error_mark_node);
19275         object_type = TREE_TYPE (object);
19276
19277         member = TREE_OPERAND (t, 1);
19278         if (BASELINK_P (member))
19279           member = tsubst_baselink (member,
19280                                     non_reference (TREE_TYPE (object)),
19281                                     args, complain, in_decl);
19282         else
19283           member = tsubst_copy (member, args, complain, in_decl);
19284         if (member == error_mark_node)
19285           RETURN (error_mark_node);
19286
19287         if (TREE_CODE (member) == FIELD_DECL)
19288           {
19289             r = finish_non_static_data_member (member, object, NULL_TREE);
19290             if (TREE_CODE (r) == COMPONENT_REF)
19291               REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
19292             RETURN (r);
19293           }
19294         else if (type_dependent_expression_p (object))
19295           /* We can't do much here.  */;
19296         else if (!CLASS_TYPE_P (object_type))
19297           {
19298             if (scalarish_type_p (object_type))
19299               {
19300                 tree s = NULL_TREE;
19301                 tree dtor = member;
19302
19303                 if (TREE_CODE (dtor) == SCOPE_REF)
19304                   {
19305                     s = TREE_OPERAND (dtor, 0);
19306                     dtor = TREE_OPERAND (dtor, 1);
19307                   }
19308                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
19309                   {
19310                     dtor = TREE_OPERAND (dtor, 0);
19311                     if (TYPE_P (dtor))
19312                       RETURN (finish_pseudo_destructor_expr
19313                               (object, s, dtor, input_location));
19314                   }
19315               }
19316           }
19317         else if (TREE_CODE (member) == SCOPE_REF
19318                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
19319           {
19320             /* Lookup the template functions now that we know what the
19321                scope is.  */
19322             tree scope = TREE_OPERAND (member, 0);
19323             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
19324             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
19325             member = lookup_qualified_name (scope, tmpl,
19326                                             /*is_type_p=*/false,
19327                                             /*complain=*/false);
19328             if (BASELINK_P (member))
19329               {
19330                 BASELINK_FUNCTIONS (member)
19331                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
19332                               args);
19333                 member = (adjust_result_of_qualified_name_lookup
19334                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
19335                            object_type));
19336               }
19337             else
19338               {
19339                 qualified_name_lookup_error (scope, tmpl, member,
19340                                              input_location);
19341                 RETURN (error_mark_node);
19342               }
19343           }
19344         else if (TREE_CODE (member) == SCOPE_REF
19345                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
19346                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
19347           {
19348             if (complain & tf_error)
19349               {
19350                 if (TYPE_P (TREE_OPERAND (member, 0)))
19351                   error ("%qT is not a class or namespace",
19352                          TREE_OPERAND (member, 0));
19353                 else
19354                   error ("%qD is not a class or namespace",
19355                          TREE_OPERAND (member, 0));
19356               }
19357             RETURN (error_mark_node);
19358           }
19359
19360         r = finish_class_member_access_expr (object, member,
19361                                              /*template_p=*/false,
19362                                              complain);
19363         if (TREE_CODE (r) == COMPONENT_REF)
19364           REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
19365         RETURN (r);
19366       }
19367
19368     case THROW_EXPR:
19369       RETURN (build_throw
19370         (RECUR (TREE_OPERAND (t, 0))));
19371
19372     case CONSTRUCTOR:
19373       {
19374         vec<constructor_elt, va_gc> *n;
19375         constructor_elt *ce;
19376         unsigned HOST_WIDE_INT idx;
19377         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19378         bool process_index_p;
19379         int newlen;
19380         bool need_copy_p = false;
19381         tree r;
19382
19383         if (type == error_mark_node)
19384           RETURN (error_mark_node);
19385
19386         /* We do not want to process the index of aggregate
19387            initializers as they are identifier nodes which will be
19388            looked up by digest_init.  */
19389         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
19390
19391         if (null_member_pointer_value_p (t))
19392           {
19393             gcc_assert (same_type_p (type, TREE_TYPE (t)));
19394             RETURN (t);
19395           }
19396
19397         n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
19398         newlen = vec_safe_length (n);
19399         FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
19400           {
19401             if (ce->index && process_index_p
19402                 /* An identifier index is looked up in the type
19403                    being initialized, not the current scope.  */
19404                 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
19405               ce->index = RECUR (ce->index);
19406
19407             if (PACK_EXPANSION_P (ce->value))
19408               {
19409                 /* Substitute into the pack expansion.  */
19410                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
19411                                                   in_decl);
19412
19413                 if (ce->value == error_mark_node
19414                     || PACK_EXPANSION_P (ce->value))
19415                   ;
19416                 else if (TREE_VEC_LENGTH (ce->value) == 1)
19417                   /* Just move the argument into place.  */
19418                   ce->value = TREE_VEC_ELT (ce->value, 0);
19419                 else
19420                   {
19421                     /* Update the length of the final CONSTRUCTOR
19422                        arguments vector, and note that we will need to
19423                        copy.*/
19424                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
19425                     need_copy_p = true;
19426                   }
19427               }
19428             else
19429               ce->value = RECUR (ce->value);
19430           }
19431
19432         if (need_copy_p)
19433           {
19434             vec<constructor_elt, va_gc> *old_n = n;
19435
19436             vec_alloc (n, newlen);
19437             FOR_EACH_VEC_ELT (*old_n, idx, ce)
19438               {
19439                 if (TREE_CODE (ce->value) == TREE_VEC)
19440                   {
19441                     int i, len = TREE_VEC_LENGTH (ce->value);
19442                     for (i = 0; i < len; ++i)
19443                       CONSTRUCTOR_APPEND_ELT (n, 0,
19444                                               TREE_VEC_ELT (ce->value, i));
19445                   }
19446                 else
19447                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
19448               }
19449           }
19450
19451         r = build_constructor (init_list_type_node, n);
19452         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
19453         CONSTRUCTOR_IS_DESIGNATED_INIT (r)
19454           = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
19455
19456         if (TREE_HAS_CONSTRUCTOR (t))
19457           {
19458             fcl_t cl = fcl_functional;
19459             if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
19460               cl = fcl_c99;
19461             RETURN (finish_compound_literal (type, r, complain, cl));
19462           }
19463
19464         TREE_TYPE (r) = type;
19465         RETURN (r);
19466       }
19467
19468     case TYPEID_EXPR:
19469       {
19470         tree operand_0 = TREE_OPERAND (t, 0);
19471         if (TYPE_P (operand_0))
19472           {
19473             operand_0 = tsubst (operand_0, args, complain, in_decl);
19474             RETURN (get_typeid (operand_0, complain));
19475           }
19476         else
19477           {
19478             operand_0 = RECUR (operand_0);
19479             RETURN (build_typeid (operand_0, complain));
19480           }
19481       }
19482
19483     case VAR_DECL:
19484       if (!args)
19485         RETURN (t);
19486       /* Fall through */
19487
19488     case PARM_DECL:
19489       {
19490         tree r = tsubst_copy (t, args, complain, in_decl);
19491         /* ??? We're doing a subset of finish_id_expression here.  */
19492         if (tree wrap = maybe_get_tls_wrapper_call (r))
19493           /* Replace an evaluated use of the thread_local variable with
19494              a call to its wrapper.  */
19495           r = wrap;
19496         else if (outer_automatic_var_p (r))
19497           r = process_outer_var_ref (r, complain);
19498
19499         if (!TYPE_REF_P (TREE_TYPE (t)))
19500           /* If the original type was a reference, we'll be wrapped in
19501              the appropriate INDIRECT_REF.  */
19502           r = convert_from_reference (r);
19503         RETURN (r);
19504       }
19505
19506     case VA_ARG_EXPR:
19507       {
19508         tree op0 = RECUR (TREE_OPERAND (t, 0));
19509         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19510         RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
19511       }
19512
19513     case OFFSETOF_EXPR:
19514       {
19515         tree object_ptr
19516           = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
19517                                    in_decl, /*function_p=*/false,
19518                                    /*integral_constant_expression_p=*/false);
19519         RETURN (finish_offsetof (object_ptr,
19520                                  RECUR (TREE_OPERAND (t, 0)),
19521                                  EXPR_LOCATION (t)));
19522       }
19523
19524     case ADDRESSOF_EXPR:
19525       RETURN (cp_build_addressof (EXPR_LOCATION (t),
19526                                   RECUR (TREE_OPERAND (t, 0)), complain));
19527
19528     case TRAIT_EXPR:
19529       {
19530         tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
19531                              complain, in_decl);
19532
19533         tree type2 = TRAIT_EXPR_TYPE2 (t);
19534         if (type2 && TREE_CODE (type2) == TREE_LIST)
19535           type2 = RECUR (type2);
19536         else if (type2)
19537           type2 = tsubst (type2, args, complain, in_decl);
19538
19539         RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
19540                                    TRAIT_EXPR_KIND (t), type1, type2));
19541       }
19542
19543     case STMT_EXPR:
19544       {
19545         tree old_stmt_expr = cur_stmt_expr;
19546         tree stmt_expr = begin_stmt_expr ();
19547
19548         cur_stmt_expr = stmt_expr;
19549         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
19550                      integral_constant_expression_p);
19551         stmt_expr = finish_stmt_expr (stmt_expr, false);
19552         cur_stmt_expr = old_stmt_expr;
19553
19554         /* If the resulting list of expression statement is empty,
19555            fold it further into void_node.  */
19556         if (empty_expr_stmt_p (stmt_expr))
19557           stmt_expr = void_node;
19558
19559         RETURN (stmt_expr);
19560       }
19561
19562     case LAMBDA_EXPR:
19563       {
19564         if (complain & tf_partial)
19565           {
19566             /* We don't have a full set of template arguments yet; don't touch
19567                the lambda at all.  */
19568             gcc_assert (processing_template_decl);
19569             return t;
19570           }
19571         tree r = tsubst_lambda_expr (t, args, complain, in_decl);
19572
19573         RETURN (build_lambda_object (r));
19574       }
19575
19576     case TARGET_EXPR:
19577       /* We can get here for a constant initializer of non-dependent type.
19578          FIXME stop folding in cp_parser_initializer_clause.  */
19579       {
19580         tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
19581                                          complain);
19582         RETURN (r);
19583       }
19584
19585     case TRANSACTION_EXPR:
19586       RETURN (tsubst_expr(t, args, complain, in_decl,
19587              integral_constant_expression_p));
19588
19589     case PAREN_EXPR:
19590       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
19591
19592     case VEC_PERM_EXPR:
19593       {
19594         tree op0 = RECUR (TREE_OPERAND (t, 0));
19595         tree op1 = RECUR (TREE_OPERAND (t, 1));
19596         tree op2 = RECUR (TREE_OPERAND (t, 2));
19597         RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
19598                                        complain));
19599       }
19600
19601     case REQUIRES_EXPR:
19602       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
19603
19604     case RANGE_EXPR:
19605       /* No need to substitute further, a RANGE_EXPR will always be built
19606          with constant operands.  */
19607       RETURN (t);
19608
19609     case NON_LVALUE_EXPR:
19610     case VIEW_CONVERT_EXPR:
19611       if (location_wrapper_p (t))
19612         /* We need to do this here as well as in tsubst_copy so we get the
19613            other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
19614         RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
19615                                           EXPR_LOCATION (t)));
19616       /* fallthrough.  */
19617
19618     default:
19619       /* Handle Objective-C++ constructs, if appropriate.  */
19620       {
19621         tree subst
19622           = objcp_tsubst_copy_and_build (t, args, complain,
19623                                          in_decl, /*function_p=*/false);
19624         if (subst)
19625           RETURN (subst);
19626       }
19627       RETURN (tsubst_copy (t, args, complain, in_decl));
19628     }
19629
19630 #undef RECUR
19631 #undef RETURN
19632  out:
19633   input_location = loc;
19634   return retval;
19635 }
19636
19637 /* Verify that the instantiated ARGS are valid. For type arguments,
19638    make sure that the type's linkage is ok. For non-type arguments,
19639    make sure they are constants if they are integral or enumerations.
19640    Emit an error under control of COMPLAIN, and return TRUE on error.  */
19641
19642 static bool
19643 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
19644 {
19645   if (dependent_template_arg_p (t))
19646     return false;
19647   if (ARGUMENT_PACK_P (t))
19648     {
19649       tree vec = ARGUMENT_PACK_ARGS (t);
19650       int len = TREE_VEC_LENGTH (vec);
19651       bool result = false;
19652       int i;
19653
19654       for (i = 0; i < len; ++i)
19655         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19656           result = true;
19657       return result;
19658     }
19659   else if (TYPE_P (t))
19660     {
19661       /* [basic.link]: A name with no linkage (notably, the name
19662          of a class or enumeration declared in a local scope)
19663          shall not be used to declare an entity with linkage.
19664          This implies that names with no linkage cannot be used as
19665          template arguments
19666
19667          DR 757 relaxes this restriction for C++0x.  */
19668       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19669                  : no_linkage_check (t, /*relaxed_p=*/false));
19670
19671       if (nt)
19672         {
19673           /* DR 488 makes use of a type with no linkage cause
19674              type deduction to fail.  */
19675           if (complain & tf_error)
19676             {
19677               if (TYPE_UNNAMED_P (nt))
19678                 error ("%qT is/uses unnamed type", t);
19679               else
19680                 error ("template argument for %qD uses local type %qT",
19681                        tmpl, t);
19682             }
19683           return true;
19684         }
19685       /* In order to avoid all sorts of complications, we do not
19686          allow variably-modified types as template arguments.  */
19687       else if (variably_modified_type_p (t, NULL_TREE))
19688         {
19689           if (complain & tf_error)
19690             error ("%qT is a variably modified type", t);
19691           return true;
19692         }
19693     }
19694   /* Class template and alias template arguments should be OK.  */
19695   else if (DECL_TYPE_TEMPLATE_P (t))
19696     ;
19697   /* A non-type argument of integral or enumerated type must be a
19698      constant.  */
19699   else if (TREE_TYPE (t)
19700            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19701            && !REFERENCE_REF_P (t)
19702            && !TREE_CONSTANT (t))
19703     {
19704       if (complain & tf_error)
19705         error ("integral expression %qE is not constant", t);
19706       return true;
19707     }
19708   return false;
19709 }
19710
19711 static bool
19712 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19713 {
19714   int ix, len = DECL_NTPARMS (tmpl);
19715   bool result = false;
19716
19717   for (ix = 0; ix != len; ix++)
19718     {
19719       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19720         result = true;
19721     }
19722   if (result && (complain & tf_error))
19723     error ("  trying to instantiate %qD", tmpl);
19724   return result;
19725 }
19726
19727 /* We're out of SFINAE context now, so generate diagnostics for the access
19728    errors we saw earlier when instantiating D from TMPL and ARGS.  */
19729
19730 static void
19731 recheck_decl_substitution (tree d, tree tmpl, tree args)
19732 {
19733   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19734   tree type = TREE_TYPE (pattern);
19735   location_t loc = input_location;
19736
19737   push_access_scope (d);
19738   push_deferring_access_checks (dk_no_deferred);
19739   input_location = DECL_SOURCE_LOCATION (pattern);
19740   tsubst (type, args, tf_warning_or_error, d);
19741   input_location = loc;
19742   pop_deferring_access_checks ();
19743   pop_access_scope (d);
19744 }
19745
19746 /* Instantiate the indicated variable, function, or alias template TMPL with
19747    the template arguments in TARG_PTR.  */
19748
19749 static tree
19750 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19751 {
19752   tree targ_ptr = orig_args;
19753   tree fndecl;
19754   tree gen_tmpl;
19755   tree spec;
19756   bool access_ok = true;
19757
19758   if (tmpl == error_mark_node)
19759     return error_mark_node;
19760
19761   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19762
19763   /* If this function is a clone, handle it specially.  */
19764   if (DECL_CLONED_FUNCTION_P (tmpl))
19765     {
19766       tree spec;
19767       tree clone;
19768
19769       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19770          DECL_CLONED_FUNCTION.  */
19771       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19772                                    targ_ptr, complain);
19773       if (spec == error_mark_node)
19774         return error_mark_node;
19775
19776       /* Look for the clone.  */
19777       FOR_EACH_CLONE (clone, spec)
19778         if (DECL_NAME (clone) == DECL_NAME (tmpl))
19779           return clone;
19780       /* We should always have found the clone by now.  */
19781       gcc_unreachable ();
19782       return NULL_TREE;
19783     }
19784
19785   if (targ_ptr == error_mark_node)
19786     return error_mark_node;
19787
19788   /* Check to see if we already have this specialization.  */
19789   gen_tmpl = most_general_template (tmpl);
19790   if (TMPL_ARGS_DEPTH (targ_ptr)
19791       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19792     /* targ_ptr only has the innermost template args, so add the outer ones
19793        from tmpl, which could be either a partial instantiation or gen_tmpl (in
19794        the case of a non-dependent call within a template definition).  */
19795     targ_ptr = (add_outermost_template_args
19796                 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19797                  targ_ptr));
19798
19799   /* It would be nice to avoid hashing here and then again in tsubst_decl,
19800      but it doesn't seem to be on the hot path.  */
19801   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19802
19803   gcc_assert (tmpl == gen_tmpl
19804               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19805                   == spec)
19806               || fndecl == NULL_TREE);
19807
19808   if (spec != NULL_TREE)
19809     {
19810       if (FNDECL_HAS_ACCESS_ERRORS (spec))
19811         {
19812           if (complain & tf_error)
19813             recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19814           return error_mark_node;
19815         }
19816       return spec;
19817     }
19818
19819   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19820                                complain))
19821     return error_mark_node;
19822
19823   /* We are building a FUNCTION_DECL, during which the access of its
19824      parameters and return types have to be checked.  However this
19825      FUNCTION_DECL which is the desired context for access checking
19826      is not built yet.  We solve this chicken-and-egg problem by
19827      deferring all checks until we have the FUNCTION_DECL.  */
19828   push_deferring_access_checks (dk_deferred);
19829
19830   /* Instantiation of the function happens in the context of the function
19831      template, not the context of the overload resolution we're doing.  */
19832   push_to_top_level ();
19833   /* If there are dependent arguments, e.g. because we're doing partial
19834      ordering, make sure processing_template_decl stays set.  */
19835   if (uses_template_parms (targ_ptr))
19836     ++processing_template_decl;
19837   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19838     {
19839       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19840                                    complain, gen_tmpl, true);
19841       push_nested_class (ctx);
19842     }
19843
19844   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19845
19846   fndecl = NULL_TREE;
19847   if (VAR_P (pattern))
19848     {
19849       /* We need to determine if we're using a partial or explicit
19850          specialization now, because the type of the variable could be
19851          different.  */
19852       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19853       tree elt = most_specialized_partial_spec (tid, complain);
19854       if (elt == error_mark_node)
19855         pattern = error_mark_node;
19856       else if (elt)
19857         {
19858           tree partial_tmpl = TREE_VALUE (elt);
19859           tree partial_args = TREE_PURPOSE (elt);
19860           tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19861           fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19862         }
19863     }
19864
19865   /* Substitute template parameters to obtain the specialization.  */
19866   if (fndecl == NULL_TREE)
19867     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19868   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19869     pop_nested_class ();
19870   pop_from_top_level ();
19871
19872   if (fndecl == error_mark_node)
19873     {
19874       pop_deferring_access_checks ();
19875       return error_mark_node;
19876     }
19877
19878   /* The DECL_TI_TEMPLATE should always be the immediate parent
19879      template, not the most general template.  */
19880   DECL_TI_TEMPLATE (fndecl) = tmpl;
19881   DECL_TI_ARGS (fndecl) = targ_ptr;
19882
19883   /* Now we know the specialization, compute access previously
19884      deferred.  Do no access control for inheriting constructors,
19885      as we already checked access for the inherited constructor.  */
19886   if (!(flag_new_inheriting_ctors
19887         && DECL_INHERITED_CTOR (fndecl)))
19888     {
19889       push_access_scope (fndecl);
19890       if (!perform_deferred_access_checks (complain))
19891         access_ok = false;
19892       pop_access_scope (fndecl);
19893     }
19894   pop_deferring_access_checks ();
19895
19896   /* If we've just instantiated the main entry point for a function,
19897      instantiate all the alternate entry points as well.  We do this
19898      by cloning the instantiation of the main entry point, not by
19899      instantiating the template clones.  */
19900   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19901     clone_function_decl (fndecl, /*update_methods=*/false);
19902
19903   if (!access_ok)
19904     {
19905       if (!(complain & tf_error))
19906         {
19907           /* Remember to reinstantiate when we're out of SFINAE so the user
19908              can see the errors.  */
19909           FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19910         }
19911       return error_mark_node;
19912     }
19913   return fndecl;
19914 }
19915
19916 /* Wrapper for instantiate_template_1.  */
19917
19918 tree
19919 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19920 {
19921   tree ret;
19922   timevar_push (TV_TEMPLATE_INST);
19923   ret = instantiate_template_1 (tmpl, orig_args,  complain);
19924   timevar_pop (TV_TEMPLATE_INST);
19925   return ret;
19926 }
19927
19928 /* Instantiate the alias template TMPL with ARGS.  Also push a template
19929    instantiation level, which instantiate_template doesn't do because
19930    functions and variables have sufficient context established by the
19931    callers.  */
19932
19933 static tree
19934 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19935 {
19936   if (tmpl == error_mark_node || args == error_mark_node)
19937     return error_mark_node;
19938   if (!push_tinst_level (tmpl, args))
19939     return error_mark_node;
19940
19941   args =
19942     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19943                                      args, tmpl, complain,
19944                                      /*require_all_args=*/true,
19945                                      /*use_default_args=*/true);
19946
19947   tree r = instantiate_template (tmpl, args, complain);
19948   pop_tinst_level ();
19949
19950   return r;
19951 }
19952
19953 /* PARM is a template parameter pack for FN.  Returns true iff
19954    PARM is used in a deducible way in the argument list of FN.  */
19955
19956 static bool
19957 pack_deducible_p (tree parm, tree fn)
19958 {
19959   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19960   for (; t; t = TREE_CHAIN (t))
19961     {
19962       tree type = TREE_VALUE (t);
19963       tree packs;
19964       if (!PACK_EXPANSION_P (type))
19965         continue;
19966       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19967            packs; packs = TREE_CHAIN (packs))
19968         if (template_args_equal (TREE_VALUE (packs), parm))
19969           {
19970             /* The template parameter pack is used in a function parameter
19971                pack.  If this is the end of the parameter list, the
19972                template parameter pack is deducible.  */
19973             if (TREE_CHAIN (t) == void_list_node)
19974               return true;
19975             else
19976               /* Otherwise, not.  Well, it could be deduced from
19977                  a non-pack parameter, but doing so would end up with
19978                  a deduction mismatch, so don't bother.  */
19979               return false;
19980           }
19981     }
19982   /* The template parameter pack isn't used in any function parameter
19983      packs, but it might be used deeper, e.g. tuple<Args...>.  */
19984   return true;
19985 }
19986
19987 /* Subroutine of fn_type_unification: check non-dependent parms for
19988    convertibility.  */
19989
19990 static int
19991 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
19992                                  tree fn, unification_kind_t strict, int flags,
19993                                  struct conversion **convs, bool explain_p)
19994 {
19995   /* Non-constructor methods need to leave a conversion for 'this', which
19996      isn't included in nargs here.  */
19997   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19998                      && !DECL_CONSTRUCTOR_P (fn));
19999
20000   for (unsigned ia = 0;
20001        parms && parms != void_list_node && ia < nargs; )
20002     {
20003       tree parm = TREE_VALUE (parms);
20004
20005       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20006           && (!TREE_CHAIN (parms)
20007               || TREE_CHAIN (parms) == void_list_node))
20008         /* For a function parameter pack that occurs at the end of the
20009            parameter-declaration-list, the type A of each remaining
20010            argument of the call is compared with the type P of the
20011            declarator-id of the function parameter pack.  */
20012         break;
20013
20014       parms = TREE_CHAIN (parms);
20015
20016       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20017         /* For a function parameter pack that does not occur at the
20018            end of the parameter-declaration-list, the type of the
20019            parameter pack is a non-deduced context.  */
20020         continue;
20021
20022       if (!uses_template_parms (parm))
20023         {
20024           tree arg = args[ia];
20025           conversion **conv_p = convs ? &convs[ia+offset] : NULL;
20026           int lflags = conv_flags (ia, nargs, fn, arg, flags);
20027
20028           if (check_non_deducible_conversion (parm, arg, strict, lflags,
20029                                               conv_p, explain_p))
20030             return 1;
20031         }
20032
20033       ++ia;
20034     }
20035
20036   return 0;
20037 }
20038
20039 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
20040    NARGS elements of the arguments that are being used when calling
20041    it.  TARGS is a vector into which the deduced template arguments
20042    are placed.
20043
20044    Returns either a FUNCTION_DECL for the matching specialization of FN or
20045    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
20046    true, diagnostics will be printed to explain why it failed.
20047
20048    If FN is a conversion operator, or we are trying to produce a specific
20049    specialization, RETURN_TYPE is the return type desired.
20050
20051    The EXPLICIT_TARGS are explicit template arguments provided via a
20052    template-id.
20053
20054    The parameter STRICT is one of:
20055
20056    DEDUCE_CALL:
20057      We are deducing arguments for a function call, as in
20058      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
20059      deducing arguments for a call to the result of a conversion
20060      function template, as in [over.call.object].
20061
20062    DEDUCE_CONV:
20063      We are deducing arguments for a conversion function, as in
20064      [temp.deduct.conv].
20065
20066    DEDUCE_EXACT:
20067      We are deducing arguments when doing an explicit instantiation
20068      as in [temp.explicit], when determining an explicit specialization
20069      as in [temp.expl.spec], or when taking the address of a function
20070      template, as in [temp.deduct.funcaddr].  */
20071
20072 tree
20073 fn_type_unification (tree fn,
20074                      tree explicit_targs,
20075                      tree targs,
20076                      const tree *args,
20077                      unsigned int nargs,
20078                      tree return_type,
20079                      unification_kind_t strict,
20080                      int flags,
20081                      struct conversion **convs,
20082                      bool explain_p,
20083                      bool decltype_p)
20084 {
20085   tree parms;
20086   tree fntype;
20087   tree decl = NULL_TREE;
20088   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
20089   bool ok;
20090   static int deduction_depth;
20091   /* type_unification_real will pass back any access checks from default
20092      template argument substitution.  */
20093   vec<deferred_access_check, va_gc> *checks = NULL;
20094   /* We don't have all the template args yet.  */
20095   bool incomplete = true;
20096
20097   tree orig_fn = fn;
20098   if (flag_new_inheriting_ctors)
20099     fn = strip_inheriting_ctors (fn);
20100
20101   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
20102   tree r = error_mark_node;
20103
20104   tree full_targs = targs;
20105   if (TMPL_ARGS_DEPTH (targs)
20106       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
20107     full_targs = (add_outermost_template_args
20108                   (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
20109                    targs));
20110
20111   if (decltype_p)
20112     complain |= tf_decltype;
20113
20114   /* In C++0x, it's possible to have a function template whose type depends
20115      on itself recursively.  This is most obvious with decltype, but can also
20116      occur with enumeration scope (c++/48969).  So we need to catch infinite
20117      recursion and reject the substitution at deduction time; this function
20118      will return error_mark_node for any repeated substitution.
20119
20120      This also catches excessive recursion such as when f<N> depends on
20121      f<N-1> across all integers, and returns error_mark_node for all the
20122      substitutions back up to the initial one.
20123
20124      This is, of course, not reentrant.  */
20125   if (excessive_deduction_depth)
20126     return error_mark_node;
20127   ++deduction_depth;
20128
20129   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
20130
20131   fntype = TREE_TYPE (fn);
20132   if (explicit_targs)
20133     {
20134       /* [temp.deduct]
20135
20136          The specified template arguments must match the template
20137          parameters in kind (i.e., type, nontype, template), and there
20138          must not be more arguments than there are parameters;
20139          otherwise type deduction fails.
20140
20141          Nontype arguments must match the types of the corresponding
20142          nontype template parameters, or must be convertible to the
20143          types of the corresponding nontype parameters as specified in
20144          _temp.arg.nontype_, otherwise type deduction fails.
20145
20146          All references in the function type of the function template
20147          to the corresponding template parameters are replaced by the
20148          specified template argument values.  If a substitution in a
20149          template parameter or in the function type of the function
20150          template results in an invalid type, type deduction fails.  */
20151       int i, len = TREE_VEC_LENGTH (tparms);
20152       location_t loc = input_location;
20153       incomplete = false;
20154
20155       if (explicit_targs == error_mark_node)
20156         goto fail;
20157
20158       if (TMPL_ARGS_DEPTH (explicit_targs)
20159           < TMPL_ARGS_DEPTH (full_targs))
20160         explicit_targs = add_outermost_template_args (full_targs,
20161                                                       explicit_targs);
20162
20163       /* Adjust any explicit template arguments before entering the
20164          substitution context.  */
20165       explicit_targs
20166         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
20167                                   complain|tf_partial,
20168                                   /*require_all_args=*/false,
20169                                   /*use_default_args=*/false));
20170       if (explicit_targs == error_mark_node)
20171         goto fail;
20172
20173       /* Substitute the explicit args into the function type.  This is
20174          necessary so that, for instance, explicitly declared function
20175          arguments can match null pointed constants.  If we were given
20176          an incomplete set of explicit args, we must not do semantic
20177          processing during substitution as we could create partial
20178          instantiations.  */
20179       for (i = 0; i < len; i++)
20180         {
20181           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
20182           bool parameter_pack = false;
20183           tree targ = TREE_VEC_ELT (explicit_targs, i);
20184
20185           /* Dig out the actual parm.  */
20186           if (TREE_CODE (parm) == TYPE_DECL
20187               || TREE_CODE (parm) == TEMPLATE_DECL)
20188             {
20189               parm = TREE_TYPE (parm);
20190               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
20191             }
20192           else if (TREE_CODE (parm) == PARM_DECL)
20193             {
20194               parm = DECL_INITIAL (parm);
20195               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
20196             }
20197
20198           if (targ == NULL_TREE)
20199             /* No explicit argument for this template parameter.  */
20200             incomplete = true;
20201           else if (parameter_pack && pack_deducible_p (parm, fn))
20202             {
20203               /* Mark the argument pack as "incomplete". We could
20204                  still deduce more arguments during unification.
20205                  We remove this mark in type_unification_real.  */
20206               ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
20207               ARGUMENT_PACK_EXPLICIT_ARGS (targ)
20208                 = ARGUMENT_PACK_ARGS (targ);
20209
20210               /* We have some incomplete argument packs.  */
20211               incomplete = true;
20212             }
20213         }
20214
20215       if (incomplete)
20216         {
20217           if (!push_tinst_level (fn, explicit_targs))
20218             {
20219               excessive_deduction_depth = true;
20220               goto fail;
20221             }
20222           ++processing_template_decl;
20223           input_location = DECL_SOURCE_LOCATION (fn);
20224           /* Ignore any access checks; we'll see them again in
20225              instantiate_template and they might have the wrong
20226              access path at this point.  */
20227           push_deferring_access_checks (dk_deferred);
20228           tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
20229           fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
20230           pop_deferring_access_checks ();
20231           input_location = loc;
20232           --processing_template_decl;
20233           pop_tinst_level ();
20234
20235           if (fntype == error_mark_node)
20236             goto fail;
20237         }
20238
20239       /* Place the explicitly specified arguments in TARGS.  */
20240       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
20241       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
20242         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
20243       if (!incomplete && CHECKING_P
20244           && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20245         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
20246           (targs, NUM_TMPL_ARGS (explicit_targs));
20247     }
20248
20249   if (return_type && strict != DEDUCE_CALL)
20250     {
20251       tree *new_args = XALLOCAVEC (tree, nargs + 1);
20252       new_args[0] = return_type;
20253       memcpy (new_args + 1, args, nargs * sizeof (tree));
20254       args = new_args;
20255       ++nargs;
20256     }
20257
20258   if (!incomplete)
20259     goto deduced;
20260
20261   /* Never do unification on the 'this' parameter.  */
20262   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
20263
20264   if (return_type && strict == DEDUCE_CALL)
20265     {
20266       /* We're deducing for a call to the result of a template conversion
20267          function.  The parms we really want are in return_type.  */
20268       if (INDIRECT_TYPE_P (return_type))
20269         return_type = TREE_TYPE (return_type);
20270       parms = TYPE_ARG_TYPES (return_type);
20271     }
20272   else if (return_type)
20273     {
20274       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
20275     }
20276
20277   /* We allow incomplete unification without an error message here
20278      because the standard doesn't seem to explicitly prohibit it.  Our
20279      callers must be ready to deal with unification failures in any
20280      event.  */
20281
20282   /* If we aren't explaining yet, push tinst context so we can see where
20283      any errors (e.g. from class instantiations triggered by instantiation
20284      of default template arguments) come from.  If we are explaining, this
20285      context is redundant.  */
20286   if (!explain_p && !push_tinst_level (fn, targs))
20287     {
20288       excessive_deduction_depth = true;
20289       goto fail;
20290     }
20291
20292   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20293                                full_targs, parms, args, nargs, /*subr=*/0,
20294                                strict, &checks, explain_p);
20295   if (!explain_p)
20296     pop_tinst_level ();
20297   if (!ok)
20298     goto fail;
20299
20300   /* Now that we have bindings for all of the template arguments,
20301      ensure that the arguments deduced for the template template
20302      parameters have compatible template parameter lists.  We cannot
20303      check this property before we have deduced all template
20304      arguments, because the template parameter types of a template
20305      template parameter might depend on prior template parameters
20306      deduced after the template template parameter.  The following
20307      ill-formed example illustrates this issue:
20308
20309        template<typename T, template<T> class C> void f(C<5>, T);
20310
20311        template<int N> struct X {};
20312
20313        void g() {
20314          f(X<5>(), 5l); // error: template argument deduction fails
20315        }
20316
20317      The template parameter list of 'C' depends on the template type
20318      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
20319      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
20320      time that we deduce 'C'.  */
20321   if (!template_template_parm_bindings_ok_p
20322            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
20323     {
20324       unify_inconsistent_template_template_parameters (explain_p);
20325       goto fail;
20326     }
20327
20328   /* DR 1391: All parameters have args, now check non-dependent parms for
20329      convertibility.  */
20330   if (check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
20331                                        convs, explain_p))
20332     goto fail;
20333
20334  deduced:
20335   /* All is well so far.  Now, check:
20336
20337      [temp.deduct]
20338
20339      When all template arguments have been deduced, all uses of
20340      template parameters in nondeduced contexts are replaced with
20341      the corresponding deduced argument values.  If the
20342      substitution results in an invalid type, as described above,
20343      type deduction fails.  */
20344   if (!push_tinst_level (fn, targs))
20345     {
20346       excessive_deduction_depth = true;
20347       goto fail;
20348     }
20349
20350   /* Also collect access checks from the instantiation.  */
20351   reopen_deferring_access_checks (checks);
20352
20353   decl = instantiate_template (fn, targs, complain);
20354
20355   checks = get_deferred_access_checks ();
20356   pop_deferring_access_checks ();
20357
20358   pop_tinst_level ();
20359
20360   if (decl == error_mark_node)
20361     goto fail;
20362
20363   /* Now perform any access checks encountered during substitution.  */
20364   push_access_scope (decl);
20365   ok = perform_access_checks (checks, complain);
20366   pop_access_scope (decl);
20367   if (!ok)
20368     goto fail;
20369
20370   /* If we're looking for an exact match, check that what we got
20371      is indeed an exact match.  It might not be if some template
20372      parameters are used in non-deduced contexts.  But don't check
20373      for an exact match if we have dependent template arguments;
20374      in that case we're doing partial ordering, and we already know
20375      that we have two candidates that will provide the actual type.  */
20376   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
20377     {
20378       tree substed = TREE_TYPE (decl);
20379       unsigned int i;
20380
20381       tree sarg
20382         = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
20383       if (return_type)
20384         sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
20385       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
20386         if (!same_type_p (args[i], TREE_VALUE (sarg)))
20387           {
20388             unify_type_mismatch (explain_p, args[i],
20389                                  TREE_VALUE (sarg));
20390             goto fail;
20391           }
20392     }
20393
20394   /* After doing deduction with the inherited constructor, actually return an
20395      instantiation of the inheriting constructor.  */
20396   if (orig_fn != fn)
20397     decl = instantiate_template (orig_fn, targs, complain);
20398
20399   r = decl;
20400
20401  fail:
20402   --deduction_depth;
20403   if (excessive_deduction_depth)
20404     {
20405       if (deduction_depth == 0)
20406         /* Reset once we're all the way out.  */
20407         excessive_deduction_depth = false;
20408     }
20409
20410   return r;
20411 }
20412
20413 /* Adjust types before performing type deduction, as described in
20414    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
20415    sections are symmetric.  PARM is the type of a function parameter
20416    or the return type of the conversion function.  ARG is the type of
20417    the argument passed to the call, or the type of the value
20418    initialized with the result of the conversion function.
20419    ARG_EXPR is the original argument expression, which may be null.  */
20420
20421 static int
20422 maybe_adjust_types_for_deduction (unification_kind_t strict,
20423                                   tree* parm,
20424                                   tree* arg,
20425                                   tree arg_expr)
20426 {
20427   int result = 0;
20428
20429   switch (strict)
20430     {
20431     case DEDUCE_CALL:
20432       break;
20433
20434     case DEDUCE_CONV:
20435       /* Swap PARM and ARG throughout the remainder of this
20436          function; the handling is precisely symmetric since PARM
20437          will initialize ARG rather than vice versa.  */
20438       std::swap (parm, arg);
20439       break;
20440
20441     case DEDUCE_EXACT:
20442       /* Core issue #873: Do the DR606 thing (see below) for these cases,
20443          too, but here handle it by stripping the reference from PARM
20444          rather than by adding it to ARG.  */
20445       if (TYPE_REF_P (*parm)
20446           && TYPE_REF_IS_RVALUE (*parm)
20447           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
20448           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
20449           && TYPE_REF_P (*arg)
20450           && !TYPE_REF_IS_RVALUE (*arg))
20451         *parm = TREE_TYPE (*parm);
20452       /* Nothing else to do in this case.  */
20453       return 0;
20454
20455     default:
20456       gcc_unreachable ();
20457     }
20458
20459   if (!TYPE_REF_P (*parm))
20460     {
20461       /* [temp.deduct.call]
20462
20463          If P is not a reference type:
20464
20465          --If A is an array type, the pointer type produced by the
20466          array-to-pointer standard conversion (_conv.array_) is
20467          used in place of A for type deduction; otherwise,
20468
20469          --If A is a function type, the pointer type produced by
20470          the function-to-pointer standard conversion
20471          (_conv.func_) is used in place of A for type deduction;
20472          otherwise,
20473
20474          --If A is a cv-qualified type, the top level
20475          cv-qualifiers of A's type are ignored for type
20476          deduction.  */
20477       if (TREE_CODE (*arg) == ARRAY_TYPE)
20478         *arg = build_pointer_type (TREE_TYPE (*arg));
20479       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
20480         *arg = build_pointer_type (*arg);
20481       else
20482         *arg = TYPE_MAIN_VARIANT (*arg);
20483     }
20484
20485   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
20486      reference to a cv-unqualified template parameter that does not represent a
20487      template parameter of a class template (during class template argument
20488      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
20489      an lvalue, the type "lvalue reference to A" is used in place of A for type
20490      deduction. */
20491   if (TYPE_REF_P (*parm)
20492       && TYPE_REF_IS_RVALUE (*parm)
20493       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
20494       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
20495       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
20496       && (arg_expr ? lvalue_p (arg_expr)
20497           /* try_one_overload doesn't provide an arg_expr, but
20498              functions are always lvalues.  */
20499           : TREE_CODE (*arg) == FUNCTION_TYPE))
20500     *arg = build_reference_type (*arg);
20501
20502   /* [temp.deduct.call]
20503
20504      If P is a cv-qualified type, the top level cv-qualifiers
20505      of P's type are ignored for type deduction.  If P is a
20506      reference type, the type referred to by P is used for
20507      type deduction.  */
20508   *parm = TYPE_MAIN_VARIANT (*parm);
20509   if (TYPE_REF_P (*parm))
20510     {
20511       *parm = TREE_TYPE (*parm);
20512       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
20513     }
20514
20515   /* DR 322. For conversion deduction, remove a reference type on parm
20516      too (which has been swapped into ARG).  */
20517   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
20518     *arg = TREE_TYPE (*arg);
20519
20520   return result;
20521 }
20522
20523 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
20524    template which doesn't contain any deducible template parameters; check if
20525    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
20526    unify_one_argument.  */
20527
20528 static int
20529 check_non_deducible_conversion (tree parm, tree arg, int strict,
20530                                 int flags, struct conversion **conv_p,
20531                                 bool explain_p)
20532 {
20533   tree type;
20534
20535   if (!TYPE_P (arg))
20536     type = TREE_TYPE (arg);
20537   else
20538     type = arg;
20539
20540   if (same_type_p (parm, type))
20541     return unify_success (explain_p);
20542
20543   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
20544   if (strict == DEDUCE_CONV)
20545     {
20546       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
20547         return unify_success (explain_p);
20548     }
20549   else if (strict != DEDUCE_EXACT)
20550     {
20551       bool ok = false;
20552       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
20553       if (conv_p)
20554         /* Avoid recalculating this in add_function_candidate.  */
20555         ok = (*conv_p
20556               = good_conversion (parm, type, conv_arg, flags, complain));
20557       else
20558         ok = can_convert_arg (parm, type, conv_arg, flags, complain);
20559       if (ok)
20560         return unify_success (explain_p);
20561     }
20562
20563   if (strict == DEDUCE_EXACT)
20564     return unify_type_mismatch (explain_p, parm, arg);
20565   else
20566     return unify_arg_conversion (explain_p, parm, type, arg);
20567 }
20568
20569 static bool uses_deducible_template_parms (tree type);
20570
20571 /* Returns true iff the expression EXPR is one from which a template
20572    argument can be deduced.  In other words, if it's an undecorated
20573    use of a template non-type parameter.  */
20574
20575 static bool
20576 deducible_expression (tree expr)
20577 {
20578   /* Strip implicit conversions.  */
20579   while (CONVERT_EXPR_P (expr))
20580     expr = TREE_OPERAND (expr, 0);
20581   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
20582 }
20583
20584 /* Returns true iff the array domain DOMAIN uses a template parameter in a
20585    deducible way; that is, if it has a max value of <PARM> - 1.  */
20586
20587 static bool
20588 deducible_array_bound (tree domain)
20589 {
20590   if (domain == NULL_TREE)
20591     return false;
20592
20593   tree max = TYPE_MAX_VALUE (domain);
20594   if (TREE_CODE (max) != MINUS_EXPR)
20595     return false;
20596
20597   return deducible_expression (TREE_OPERAND (max, 0));
20598 }
20599
20600 /* Returns true iff the template arguments ARGS use a template parameter
20601    in a deducible way.  */
20602
20603 static bool
20604 deducible_template_args (tree args)
20605 {
20606   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
20607     {
20608       bool deducible;
20609       tree elt = TREE_VEC_ELT (args, i);
20610       if (ARGUMENT_PACK_P (elt))
20611         deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
20612       else
20613         {
20614           if (PACK_EXPANSION_P (elt))
20615             elt = PACK_EXPANSION_PATTERN (elt);
20616           if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
20617             deducible = true;
20618           else if (TYPE_P (elt))
20619             deducible = uses_deducible_template_parms (elt);
20620           else
20621             deducible = deducible_expression (elt);
20622         }
20623       if (deducible)
20624         return true;
20625     }
20626   return false;
20627 }
20628
20629 /* Returns true iff TYPE contains any deducible references to template
20630    parameters, as per 14.8.2.5.  */
20631
20632 static bool
20633 uses_deducible_template_parms (tree type)
20634 {
20635   if (PACK_EXPANSION_P (type))
20636     type = PACK_EXPANSION_PATTERN (type);
20637
20638   /* T
20639      cv-list T
20640      TT<T>
20641      TT<i>
20642      TT<> */
20643   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20644       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
20645     return true;
20646
20647   /* T*
20648      T&
20649      T&&  */
20650   if (INDIRECT_TYPE_P (type))
20651     return uses_deducible_template_parms (TREE_TYPE (type));
20652
20653   /* T[integer-constant ]
20654      type [i]  */
20655   if (TREE_CODE (type) == ARRAY_TYPE)
20656     return (uses_deducible_template_parms (TREE_TYPE (type))
20657             || deducible_array_bound (TYPE_DOMAIN (type)));
20658
20659   /* T type ::*
20660      type T::*
20661      T T::*
20662      T (type ::*)()
20663      type (T::*)()
20664      type (type ::*)(T)
20665      type (T::*)(T)
20666      T (type ::*)(T)
20667      T (T::*)()
20668      T (T::*)(T) */
20669   if (TYPE_PTRMEM_P (type))
20670     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
20671             || (uses_deducible_template_parms
20672                 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
20673
20674   /* template-name <T> (where template-name refers to a class template)
20675      template-name <i> (where template-name refers to a class template) */
20676   if (CLASS_TYPE_P (type)
20677       && CLASSTYPE_TEMPLATE_INFO (type)
20678       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
20679     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
20680                                     (CLASSTYPE_TI_ARGS (type)));
20681
20682   /* type (T)
20683      T()
20684      T(T)  */
20685   if (FUNC_OR_METHOD_TYPE_P (type))
20686     {
20687       if (uses_deducible_template_parms (TREE_TYPE (type)))
20688         return true;
20689       tree parm = TYPE_ARG_TYPES (type);
20690       if (TREE_CODE (type) == METHOD_TYPE)
20691         parm = TREE_CHAIN (parm);
20692       for (; parm; parm = TREE_CHAIN (parm))
20693         if (uses_deducible_template_parms (TREE_VALUE (parm)))
20694           return true;
20695     }
20696
20697   return false;
20698 }
20699
20700 /* Subroutine of type_unification_real and unify_pack_expansion to
20701    handle unification of a single P/A pair.  Parameters are as
20702    for those functions.  */
20703
20704 static int
20705 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
20706                     int subr, unification_kind_t strict,
20707                     bool explain_p)
20708 {
20709   tree arg_expr = NULL_TREE;
20710   int arg_strict;
20711
20712   if (arg == error_mark_node || parm == error_mark_node)
20713     return unify_invalid (explain_p);
20714   if (arg == unknown_type_node)
20715     /* We can't deduce anything from this, but we might get all the
20716        template args from other function args.  */
20717     return unify_success (explain_p);
20718
20719   /* Implicit conversions (Clause 4) will be performed on a function
20720      argument to convert it to the type of the corresponding function
20721      parameter if the parameter type contains no template-parameters that
20722      participate in template argument deduction.  */
20723   if (strict != DEDUCE_EXACT
20724       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
20725     /* For function parameters with no deducible template parameters,
20726        just return.  We'll check non-dependent conversions later.  */
20727     return unify_success (explain_p);
20728
20729   switch (strict)
20730     {
20731     case DEDUCE_CALL:
20732       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20733                     | UNIFY_ALLOW_MORE_CV_QUAL
20734                     | UNIFY_ALLOW_DERIVED);
20735       break;
20736
20737     case DEDUCE_CONV:
20738       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20739       break;
20740
20741     case DEDUCE_EXACT:
20742       arg_strict = UNIFY_ALLOW_NONE;
20743       break;
20744
20745     default:
20746       gcc_unreachable ();
20747     }
20748
20749   /* We only do these transformations if this is the top-level
20750      parameter_type_list in a call or declaration matching; in other
20751      situations (nested function declarators, template argument lists) we
20752      won't be comparing a type to an expression, and we don't do any type
20753      adjustments.  */
20754   if (!subr)
20755     {
20756       if (!TYPE_P (arg))
20757         {
20758           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20759           if (type_unknown_p (arg))
20760             {
20761               /* [temp.deduct.type] A template-argument can be
20762                  deduced from a pointer to function or pointer
20763                  to member function argument if the set of
20764                  overloaded functions does not contain function
20765                  templates and at most one of a set of
20766                  overloaded functions provides a unique
20767                  match.  */
20768               resolve_overloaded_unification (tparms, targs, parm,
20769                                               arg, strict,
20770                                               arg_strict, explain_p);
20771               /* If a unique match was not found, this is a
20772                  non-deduced context, so we still succeed. */
20773               return unify_success (explain_p);
20774             }
20775
20776           arg_expr = arg;
20777           arg = unlowered_expr_type (arg);
20778           if (arg == error_mark_node)
20779             return unify_invalid (explain_p);
20780         }
20781
20782       arg_strict |=
20783         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20784     }
20785   else
20786     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20787         != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20788       return unify_template_argument_mismatch (explain_p, parm, arg);
20789
20790   /* For deduction from an init-list we need the actual list.  */
20791   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20792     arg = arg_expr;
20793   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20794 }
20795
20796 /* for_each_template_parm callback that always returns 0.  */
20797
20798 static int
20799 zero_r (tree, void *)
20800 {
20801   return 0;
20802 }
20803
20804 /* for_each_template_parm any_fn callback to handle deduction of a template
20805    type argument from the type of an array bound.  */
20806
20807 static int
20808 array_deduction_r (tree t, void *data)
20809 {
20810   tree_pair_p d = (tree_pair_p)data;
20811   tree &tparms = d->purpose;
20812   tree &targs = d->value;
20813
20814   if (TREE_CODE (t) == ARRAY_TYPE)
20815     if (tree dom = TYPE_DOMAIN (t))
20816       if (tree max = TYPE_MAX_VALUE (dom))
20817         {
20818           if (TREE_CODE (max) == MINUS_EXPR)
20819             max = TREE_OPERAND (max, 0);
20820           if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20821             unify (tparms, targs, TREE_TYPE (max), size_type_node,
20822                    UNIFY_ALLOW_NONE, /*explain*/false);
20823         }
20824
20825   /* Keep walking.  */
20826   return 0;
20827 }
20828
20829 /* Try to deduce any not-yet-deduced template type arguments from the type of
20830    an array bound.  This is handled separately from unify because 14.8.2.5 says
20831    "The type of a type parameter is only deduced from an array bound if it is
20832    not otherwise deduced."  */
20833
20834 static void
20835 try_array_deduction (tree tparms, tree targs, tree parm)
20836 {
20837   tree_pair_s data = { tparms, targs };
20838   hash_set<tree> visited;
20839   for_each_template_parm (parm, zero_r, &data, &visited,
20840                           /*nondeduced*/false, array_deduction_r);
20841 }
20842
20843 /* Most parms like fn_type_unification.
20844
20845    If SUBR is 1, we're being called recursively (to unify the
20846    arguments of a function or method parameter of a function
20847    template).
20848
20849    CHECKS is a pointer to a vector of access checks encountered while
20850    substituting default template arguments.  */
20851
20852 static int
20853 type_unification_real (tree tparms,
20854                        tree full_targs,
20855                        tree xparms,
20856                        const tree *xargs,
20857                        unsigned int xnargs,
20858                        int subr,
20859                        unification_kind_t strict,
20860                        vec<deferred_access_check, va_gc> **checks,
20861                        bool explain_p)
20862 {
20863   tree parm, arg;
20864   int i;
20865   int ntparms = TREE_VEC_LENGTH (tparms);
20866   int saw_undeduced = 0;
20867   tree parms;
20868   const tree *args;
20869   unsigned int nargs;
20870   unsigned int ia;
20871
20872   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20873   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20874   gcc_assert (ntparms > 0);
20875
20876   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20877
20878   /* Reset the number of non-defaulted template arguments contained
20879      in TARGS.  */
20880   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20881
20882  again:
20883   parms = xparms;
20884   args = xargs;
20885   nargs = xnargs;
20886
20887   ia = 0;
20888   while (parms && parms != void_list_node
20889          && ia < nargs)
20890     {
20891       parm = TREE_VALUE (parms);
20892
20893       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20894           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20895         /* For a function parameter pack that occurs at the end of the
20896            parameter-declaration-list, the type A of each remaining
20897            argument of the call is compared with the type P of the
20898            declarator-id of the function parameter pack.  */
20899         break;
20900
20901       parms = TREE_CHAIN (parms);
20902
20903       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20904         /* For a function parameter pack that does not occur at the
20905            end of the parameter-declaration-list, the type of the
20906            parameter pack is a non-deduced context.  */
20907         continue;
20908
20909       arg = args[ia];
20910       ++ia;
20911
20912       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20913                               explain_p))
20914         return 1;
20915     }
20916
20917   if (parms
20918       && parms != void_list_node
20919       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20920     {
20921       /* Unify the remaining arguments with the pack expansion type.  */
20922       tree argvec;
20923       tree parmvec = make_tree_vec (1);
20924
20925       /* Allocate a TREE_VEC and copy in all of the arguments */
20926       argvec = make_tree_vec (nargs - ia);
20927       for (i = 0; ia < nargs; ++ia, ++i)
20928         TREE_VEC_ELT (argvec, i) = args[ia];
20929
20930       /* Copy the parameter into parmvec.  */
20931       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20932       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20933                                 /*subr=*/subr, explain_p))
20934         return 1;
20935
20936       /* Advance to the end of the list of parameters.  */
20937       parms = TREE_CHAIN (parms);
20938     }
20939
20940   /* Fail if we've reached the end of the parm list, and more args
20941      are present, and the parm list isn't variadic.  */
20942   if (ia < nargs && parms == void_list_node)
20943     return unify_too_many_arguments (explain_p, nargs, ia);
20944   /* Fail if parms are left and they don't have default values and
20945      they aren't all deduced as empty packs (c++/57397).  This is
20946      consistent with sufficient_parms_p.  */
20947   if (parms && parms != void_list_node
20948       && TREE_PURPOSE (parms) == NULL_TREE)
20949     {
20950       unsigned int count = nargs;
20951       tree p = parms;
20952       bool type_pack_p;
20953       do
20954         {
20955           type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20956           if (!type_pack_p)
20957             count++;
20958           p = TREE_CHAIN (p);
20959         }
20960       while (p && p != void_list_node);
20961       if (count != nargs)
20962         return unify_too_few_arguments (explain_p, ia, count,
20963                                         type_pack_p);
20964     }
20965
20966   if (!subr)
20967     {
20968       tsubst_flags_t complain = (explain_p
20969                                  ? tf_warning_or_error
20970                                  : tf_none);
20971       bool tried_array_deduction = (cxx_dialect < cxx17);
20972
20973       for (i = 0; i < ntparms; i++)
20974         {
20975           tree targ = TREE_VEC_ELT (targs, i);
20976           tree tparm = TREE_VEC_ELT (tparms, i);
20977
20978           /* Clear the "incomplete" flags on all argument packs now so that
20979              substituting them into later default arguments works.  */
20980           if (targ && ARGUMENT_PACK_P (targ))
20981             {
20982               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20983               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20984             }
20985
20986           if (targ || tparm == error_mark_node)
20987             continue;
20988           tparm = TREE_VALUE (tparm);
20989
20990           if (TREE_CODE (tparm) == TYPE_DECL
20991               && !tried_array_deduction)
20992             {
20993               try_array_deduction (tparms, targs, xparms);
20994               tried_array_deduction = true;
20995               if (TREE_VEC_ELT (targs, i))
20996                 continue;
20997             }
20998
20999           /* If this is an undeduced nontype parameter that depends on
21000              a type parameter, try another pass; its type may have been
21001              deduced from a later argument than the one from which
21002              this parameter can be deduced.  */
21003           if (TREE_CODE (tparm) == PARM_DECL
21004               && uses_template_parms (TREE_TYPE (tparm))
21005               && saw_undeduced < 2)
21006             {
21007               saw_undeduced = 1;
21008               continue;
21009             }
21010
21011           /* Core issue #226 (C++0x) [temp.deduct]:
21012
21013              If a template argument has not been deduced, its
21014              default template argument, if any, is used.
21015
21016              When we are in C++98 mode, TREE_PURPOSE will either
21017              be NULL_TREE or ERROR_MARK_NODE, so we do not need
21018              to explicitly check cxx_dialect here.  */
21019           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
21020             /* OK, there is a default argument.  Wait until after the
21021                conversion check to do substitution.  */
21022             continue;
21023
21024           /* If the type parameter is a parameter pack, then it will
21025              be deduced to an empty parameter pack.  */
21026           if (template_parameter_pack_p (tparm))
21027             {
21028               tree arg;
21029
21030               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
21031                 {
21032                   arg = make_node (NONTYPE_ARGUMENT_PACK);
21033                   TREE_CONSTANT (arg) = 1;
21034                 }
21035               else
21036                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
21037
21038               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
21039
21040               TREE_VEC_ELT (targs, i) = arg;
21041               continue;
21042             }
21043
21044           return unify_parameter_deduction_failure (explain_p, tparm);
21045         }
21046
21047       /* Now substitute into the default template arguments.  */
21048       for (i = 0; i < ntparms; i++)
21049         {
21050           tree targ = TREE_VEC_ELT (targs, i);
21051           tree tparm = TREE_VEC_ELT (tparms, i);
21052
21053           if (targ || tparm == error_mark_node)
21054             continue;
21055           tree parm = TREE_VALUE (tparm);
21056           tree arg = TREE_PURPOSE (tparm);
21057           reopen_deferring_access_checks (*checks);
21058           location_t save_loc = input_location;
21059           if (DECL_P (parm))
21060             input_location = DECL_SOURCE_LOCATION (parm);
21061
21062           if (saw_undeduced == 1
21063               && TREE_CODE (parm) == PARM_DECL
21064               && uses_template_parms (TREE_TYPE (parm)))
21065             {
21066               /* The type of this non-type parameter depends on undeduced
21067                  parameters.  Don't try to use its default argument yet,
21068                  since we might deduce an argument for it on the next pass,
21069                  but do check whether the arguments we already have cause
21070                  substitution failure, so that that happens before we try
21071                  later default arguments (78489).  */
21072               ++processing_template_decl;
21073               tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
21074                                   NULL_TREE);
21075               --processing_template_decl;
21076               if (type == error_mark_node)
21077                 arg = error_mark_node;
21078               else
21079                 arg = NULL_TREE;
21080             }
21081           else
21082             {
21083               /* Even if the call is happening in template context, getting
21084                  here means it's non-dependent, and a default argument is
21085                  considered a separate definition under [temp.decls], so we can
21086                  do this substitution without processing_template_decl.  This
21087                  is important if the default argument contains something that
21088                  might be instantiation-dependent like access (87480).  */
21089               processing_template_decl_sentinel s;
21090               tree substed = NULL_TREE;
21091               if (saw_undeduced == 1)
21092                 {
21093                   /* First instatiate in template context, in case we still
21094                      depend on undeduced template parameters.  */
21095                   ++processing_template_decl;
21096                   substed = tsubst_template_arg (arg, full_targs, complain,
21097                                                  NULL_TREE);
21098                   --processing_template_decl;
21099                   if (substed != error_mark_node
21100                       && !uses_template_parms (substed))
21101                     /* We replaced all the tparms, substitute again out of
21102                        template context.  */
21103                     substed = NULL_TREE;
21104                 }
21105               if (!substed)
21106                 substed = tsubst_template_arg (arg, full_targs, complain,
21107                                                NULL_TREE);
21108
21109               if (!uses_template_parms (substed))
21110                 arg = convert_template_argument (parm, substed, full_targs,
21111                                                  complain, i, NULL_TREE);
21112               else if (saw_undeduced == 1)
21113                 arg = NULL_TREE;
21114               else
21115                 arg = error_mark_node;
21116             }
21117
21118           input_location = save_loc;
21119           *checks = get_deferred_access_checks ();
21120           pop_deferring_access_checks ();
21121
21122           if (arg == error_mark_node)
21123             return 1;
21124           else if (arg)
21125             {
21126               TREE_VEC_ELT (targs, i) = arg;
21127               /* The position of the first default template argument,
21128                  is also the number of non-defaulted arguments in TARGS.
21129                  Record that.  */
21130               if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21131                 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
21132             }
21133         }
21134
21135       if (saw_undeduced++ == 1)
21136         goto again;
21137     }
21138
21139   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21140     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
21141
21142   return unify_success (explain_p);
21143 }
21144
21145 /* Subroutine of type_unification_real.  Args are like the variables
21146    at the call site.  ARG is an overloaded function (or template-id);
21147    we try deducing template args from each of the overloads, and if
21148    only one succeeds, we go with that.  Modifies TARGS and returns
21149    true on success.  */
21150
21151 static bool
21152 resolve_overloaded_unification (tree tparms,
21153                                 tree targs,
21154                                 tree parm,
21155                                 tree arg,
21156                                 unification_kind_t strict,
21157                                 int sub_strict,
21158                                 bool explain_p)
21159 {
21160   tree tempargs = copy_node (targs);
21161   int good = 0;
21162   tree goodfn = NULL_TREE;
21163   bool addr_p;
21164
21165   if (TREE_CODE (arg) == ADDR_EXPR)
21166     {
21167       arg = TREE_OPERAND (arg, 0);
21168       addr_p = true;
21169     }
21170   else
21171     addr_p = false;
21172
21173   if (TREE_CODE (arg) == COMPONENT_REF)
21174     /* Handle `&x' where `x' is some static or non-static member
21175        function name.  */
21176     arg = TREE_OPERAND (arg, 1);
21177
21178   if (TREE_CODE (arg) == OFFSET_REF)
21179     arg = TREE_OPERAND (arg, 1);
21180
21181   /* Strip baselink information.  */
21182   if (BASELINK_P (arg))
21183     arg = BASELINK_FUNCTIONS (arg);
21184
21185   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
21186     {
21187       /* If we got some explicit template args, we need to plug them into
21188          the affected templates before we try to unify, in case the
21189          explicit args will completely resolve the templates in question.  */
21190
21191       int ok = 0;
21192       tree expl_subargs = TREE_OPERAND (arg, 1);
21193       arg = TREE_OPERAND (arg, 0);
21194
21195       for (lkp_iterator iter (arg); iter; ++iter)
21196         {
21197           tree fn = *iter;
21198           tree subargs, elem;
21199
21200           if (TREE_CODE (fn) != TEMPLATE_DECL)
21201             continue;
21202
21203           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21204                                            expl_subargs, NULL_TREE, tf_none,
21205                                            /*require_all_args=*/true,
21206                                            /*use_default_args=*/true);
21207           if (subargs != error_mark_node
21208               && !any_dependent_template_arguments_p (subargs))
21209             {
21210               elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
21211               if (try_one_overload (tparms, targs, tempargs, parm,
21212                                     elem, strict, sub_strict, addr_p, explain_p)
21213                   && (!goodfn || !same_type_p (goodfn, elem)))
21214                 {
21215                   goodfn = elem;
21216                   ++good;
21217                 }
21218             }
21219           else if (subargs)
21220             ++ok;
21221         }
21222       /* If no templates (or more than one) are fully resolved by the
21223          explicit arguments, this template-id is a non-deduced context; it
21224          could still be OK if we deduce all template arguments for the
21225          enclosing call through other arguments.  */
21226       if (good != 1)
21227         good = ok;
21228     }
21229   else if (!OVL_P (arg))
21230     /* If ARG is, for example, "(0, &f)" then its type will be unknown
21231        -- but the deduction does not succeed because the expression is
21232        not just the function on its own.  */
21233     return false;
21234   else
21235     for (lkp_iterator iter (arg); iter; ++iter)
21236       {
21237         tree fn = *iter;
21238         if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
21239                               strict, sub_strict, addr_p, explain_p)
21240             && (!goodfn || !decls_match (goodfn, fn)))
21241           {
21242             goodfn = fn;
21243             ++good;
21244           }
21245       }
21246
21247   /* [temp.deduct.type] A template-argument can be deduced from a pointer
21248      to function or pointer to member function argument if the set of
21249      overloaded functions does not contain function templates and at most
21250      one of a set of overloaded functions provides a unique match.
21251
21252      So if we found multiple possibilities, we return success but don't
21253      deduce anything.  */
21254
21255   if (good == 1)
21256     {
21257       int i = TREE_VEC_LENGTH (targs);
21258       for (; i--; )
21259         if (TREE_VEC_ELT (tempargs, i))
21260           {
21261             tree old = TREE_VEC_ELT (targs, i);
21262             tree new_ = TREE_VEC_ELT (tempargs, i);
21263             if (new_ && old && ARGUMENT_PACK_P (old)
21264                 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
21265               /* Don't forget explicit template arguments in a pack.  */
21266               ARGUMENT_PACK_EXPLICIT_ARGS (new_)
21267                 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
21268             TREE_VEC_ELT (targs, i) = new_;
21269           }
21270     }
21271   if (good)
21272     return true;
21273
21274   return false;
21275 }
21276
21277 /* Core DR 115: In contexts where deduction is done and fails, or in
21278    contexts where deduction is not done, if a template argument list is
21279    specified and it, along with any default template arguments, identifies
21280    a single function template specialization, then the template-id is an
21281    lvalue for the function template specialization.  */
21282
21283 tree
21284 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
21285 {
21286   tree expr, offset, baselink;
21287   bool addr;
21288
21289   if (!type_unknown_p (orig_expr))
21290     return orig_expr;
21291
21292   expr = orig_expr;
21293   addr = false;
21294   offset = NULL_TREE;
21295   baselink = NULL_TREE;
21296
21297   if (TREE_CODE (expr) == ADDR_EXPR)
21298     {
21299       expr = TREE_OPERAND (expr, 0);
21300       addr = true;
21301     }
21302   if (TREE_CODE (expr) == OFFSET_REF)
21303     {
21304       offset = expr;
21305       expr = TREE_OPERAND (expr, 1);
21306     }
21307   if (BASELINK_P (expr))
21308     {
21309       baselink = expr;
21310       expr = BASELINK_FUNCTIONS (expr);
21311     }
21312
21313   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
21314     {
21315       int good = 0;
21316       tree goodfn = NULL_TREE;
21317
21318       /* If we got some explicit template args, we need to plug them into
21319          the affected templates before we try to unify, in case the
21320          explicit args will completely resolve the templates in question.  */
21321
21322       tree expl_subargs = TREE_OPERAND (expr, 1);
21323       tree arg = TREE_OPERAND (expr, 0);
21324       tree badfn = NULL_TREE;
21325       tree badargs = NULL_TREE;
21326
21327       for (lkp_iterator iter (arg); iter; ++iter)
21328         {
21329           tree fn = *iter;
21330           tree subargs, elem;
21331
21332           if (TREE_CODE (fn) != TEMPLATE_DECL)
21333             continue;
21334
21335           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21336                                            expl_subargs, NULL_TREE, tf_none,
21337                                            /*require_all_args=*/true,
21338                                            /*use_default_args=*/true);
21339           if (subargs != error_mark_node
21340               && !any_dependent_template_arguments_p (subargs))
21341             {
21342               elem = instantiate_template (fn, subargs, tf_none);
21343               if (elem == error_mark_node)
21344                 {
21345                   badfn = fn;
21346                   badargs = subargs;
21347                 }
21348               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
21349                 {
21350                   goodfn = elem;
21351                   ++good;
21352                 }
21353             }
21354         }
21355       if (good == 1)
21356         {
21357           mark_used (goodfn);
21358           expr = goodfn;
21359           if (baselink)
21360             expr = build_baselink (BASELINK_BINFO (baselink),
21361                                    BASELINK_ACCESS_BINFO (baselink),
21362                                    expr, BASELINK_OPTYPE (baselink));
21363           if (offset)
21364             {
21365               tree base
21366                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
21367               expr = build_offset_ref (base, expr, addr, complain);
21368             }
21369           if (addr)
21370             expr = cp_build_addr_expr (expr, complain);
21371           return expr;
21372         }
21373       else if (good == 0 && badargs && (complain & tf_error))
21374         /* There were no good options and at least one bad one, so let the
21375            user know what the problem is.  */
21376         instantiate_template (badfn, badargs, complain);
21377     }
21378   return orig_expr;
21379 }
21380
21381 /* As above, but error out if the expression remains overloaded.  */
21382
21383 tree
21384 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
21385 {
21386   exp = resolve_nondeduced_context (exp, complain);
21387   if (type_unknown_p (exp))
21388     {
21389       if (complain & tf_error)
21390         cxx_incomplete_type_error (exp, TREE_TYPE (exp));
21391       return error_mark_node;
21392     }
21393   return exp;
21394 }
21395
21396 /* Subroutine of resolve_overloaded_unification; does deduction for a single
21397    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
21398    different overloads deduce different arguments for a given parm.
21399    ADDR_P is true if the expression for which deduction is being
21400    performed was of the form "& fn" rather than simply "fn".
21401
21402    Returns 1 on success.  */
21403
21404 static int
21405 try_one_overload (tree tparms,
21406                   tree orig_targs,
21407                   tree targs,
21408                   tree parm,
21409                   tree arg,
21410                   unification_kind_t strict,
21411                   int sub_strict,
21412                   bool addr_p,
21413                   bool explain_p)
21414 {
21415   int nargs;
21416   tree tempargs;
21417   int i;
21418
21419   if (arg == error_mark_node)
21420     return 0;
21421
21422   /* [temp.deduct.type] A template-argument can be deduced from a pointer
21423      to function or pointer to member function argument if the set of
21424      overloaded functions does not contain function templates and at most
21425      one of a set of overloaded functions provides a unique match.
21426
21427      So if this is a template, just return success.  */
21428
21429   if (uses_template_parms (arg))
21430     return 1;
21431
21432   if (TREE_CODE (arg) == METHOD_TYPE)
21433     arg = build_ptrmemfunc_type (build_pointer_type (arg));
21434   else if (addr_p)
21435     arg = build_pointer_type (arg);
21436
21437   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
21438
21439   /* We don't copy orig_targs for this because if we have already deduced
21440      some template args from previous args, unify would complain when we
21441      try to deduce a template parameter for the same argument, even though
21442      there isn't really a conflict.  */
21443   nargs = TREE_VEC_LENGTH (targs);
21444   tempargs = make_tree_vec (nargs);
21445
21446   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
21447     return 0;
21448
21449   /* First make sure we didn't deduce anything that conflicts with
21450      explicitly specified args.  */
21451   for (i = nargs; i--; )
21452     {
21453       tree elt = TREE_VEC_ELT (tempargs, i);
21454       tree oldelt = TREE_VEC_ELT (orig_targs, i);
21455
21456       if (!elt)
21457         /*NOP*/;
21458       else if (uses_template_parms (elt))
21459         /* Since we're unifying against ourselves, we will fill in
21460            template args used in the function parm list with our own
21461            template parms.  Discard them.  */
21462         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
21463       else if (oldelt && ARGUMENT_PACK_P (oldelt))
21464         {
21465           /* Check that the argument at each index of the deduced argument pack
21466              is equivalent to the corresponding explicitly specified argument.
21467              We may have deduced more arguments than were explicitly specified,
21468              and that's OK.  */
21469
21470           /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
21471              that's wrong if we deduce the same argument pack from multiple
21472              function arguments: it's only incomplete the first time.  */
21473
21474           tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
21475           tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
21476
21477           if (TREE_VEC_LENGTH (deduced_pack)
21478               < TREE_VEC_LENGTH (explicit_pack))
21479             return 0;
21480
21481           for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
21482             if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
21483                                       TREE_VEC_ELT (deduced_pack, j)))
21484               return 0;
21485         }
21486       else if (oldelt && !template_args_equal (oldelt, elt))
21487         return 0;
21488     }
21489
21490   for (i = nargs; i--; )
21491     {
21492       tree elt = TREE_VEC_ELT (tempargs, i);
21493
21494       if (elt)
21495         TREE_VEC_ELT (targs, i) = elt;
21496     }
21497
21498   return 1;
21499 }
21500
21501 /* PARM is a template class (perhaps with unbound template
21502    parameters).  ARG is a fully instantiated type.  If ARG can be
21503    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
21504    TARGS are as for unify.  */
21505
21506 static tree
21507 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
21508                        bool explain_p)
21509 {
21510   tree copy_of_targs;
21511
21512   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21513     return NULL_TREE;
21514   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21515     /* Matches anything.  */;
21516   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
21517            != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
21518     return NULL_TREE;
21519
21520   /* We need to make a new template argument vector for the call to
21521      unify.  If we used TARGS, we'd clutter it up with the result of
21522      the attempted unification, even if this class didn't work out.
21523      We also don't want to commit ourselves to all the unifications
21524      we've already done, since unification is supposed to be done on
21525      an argument-by-argument basis.  In other words, consider the
21526      following pathological case:
21527
21528        template <int I, int J, int K>
21529        struct S {};
21530
21531        template <int I, int J>
21532        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
21533
21534        template <int I, int J, int K>
21535        void f(S<I, J, K>, S<I, I, I>);
21536
21537        void g() {
21538          S<0, 0, 0> s0;
21539          S<0, 1, 2> s2;
21540
21541          f(s0, s2);
21542        }
21543
21544      Now, by the time we consider the unification involving `s2', we
21545      already know that we must have `f<0, 0, 0>'.  But, even though
21546      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
21547      because there are two ways to unify base classes of S<0, 1, 2>
21548      with S<I, I, I>.  If we kept the already deduced knowledge, we
21549      would reject the possibility I=1.  */
21550   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
21551
21552   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21553     {
21554       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
21555         return NULL_TREE;
21556       return arg;
21557     }
21558
21559   /* If unification failed, we're done.  */
21560   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
21561              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
21562     return NULL_TREE;
21563
21564   return arg;
21565 }
21566
21567 /* Given a template type PARM and a class type ARG, find the unique
21568    base type in ARG that is an instance of PARM.  We do not examine
21569    ARG itself; only its base-classes.  If there is not exactly one
21570    appropriate base class, return NULL_TREE.  PARM may be the type of
21571    a partial specialization, as well as a plain template type.  Used
21572    by unify.  */
21573
21574 static enum template_base_result
21575 get_template_base (tree tparms, tree targs, tree parm, tree arg,
21576                    bool explain_p, tree *result)
21577 {
21578   tree rval = NULL_TREE;
21579   tree binfo;
21580
21581   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
21582
21583   binfo = TYPE_BINFO (complete_type (arg));
21584   if (!binfo)
21585     {
21586       /* The type could not be completed.  */
21587       *result = NULL_TREE;
21588       return tbr_incomplete_type;
21589     }
21590
21591   /* Walk in inheritance graph order.  The search order is not
21592      important, and this avoids multiple walks of virtual bases.  */
21593   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
21594     {
21595       tree r = try_class_unification (tparms, targs, parm,
21596                                       BINFO_TYPE (binfo), explain_p);
21597
21598       if (r)
21599         {
21600           /* If there is more than one satisfactory baseclass, then:
21601
21602                [temp.deduct.call]
21603
21604               If they yield more than one possible deduced A, the type
21605               deduction fails.
21606
21607              applies.  */
21608           if (rval && !same_type_p (r, rval))
21609             {
21610               *result = NULL_TREE;
21611               return tbr_ambiguous_baseclass;
21612             }
21613
21614           rval = r;
21615         }
21616     }
21617
21618   *result = rval;
21619   return tbr_success;
21620 }
21621
21622 /* Returns the level of DECL, which declares a template parameter.  */
21623
21624 static int
21625 template_decl_level (tree decl)
21626 {
21627   switch (TREE_CODE (decl))
21628     {
21629     case TYPE_DECL:
21630     case TEMPLATE_DECL:
21631       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
21632
21633     case PARM_DECL:
21634       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
21635
21636     default:
21637       gcc_unreachable ();
21638     }
21639   return 0;
21640 }
21641
21642 /* Decide whether ARG can be unified with PARM, considering only the
21643    cv-qualifiers of each type, given STRICT as documented for unify.
21644    Returns nonzero iff the unification is OK on that basis.  */
21645
21646 static int
21647 check_cv_quals_for_unify (int strict, tree arg, tree parm)
21648 {
21649   int arg_quals = cp_type_quals (arg);
21650   int parm_quals = cp_type_quals (parm);
21651
21652   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21653       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21654     {
21655       /*  Although a CVR qualifier is ignored when being applied to a
21656           substituted template parameter ([8.3.2]/1 for example), that
21657           does not allow us to unify "const T" with "int&" because both
21658           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
21659           It is ok when we're allowing additional CV qualifiers
21660           at the outer level [14.8.2.1]/3,1st bullet.  */
21661       if ((TYPE_REF_P (arg)
21662            || FUNC_OR_METHOD_TYPE_P (arg))
21663           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
21664         return 0;
21665
21666       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
21667           && (parm_quals & TYPE_QUAL_RESTRICT))
21668         return 0;
21669     }
21670
21671   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21672       && (arg_quals & parm_quals) != parm_quals)
21673     return 0;
21674
21675   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
21676       && (parm_quals & arg_quals) != arg_quals)
21677     return 0;
21678
21679   return 1;
21680 }
21681
21682 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
21683 void
21684 template_parm_level_and_index (tree parm, int* level, int* index)
21685 {
21686   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21687       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21688       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21689     {
21690       *index = TEMPLATE_TYPE_IDX (parm);
21691       *level = TEMPLATE_TYPE_LEVEL (parm);
21692     }
21693   else
21694     {
21695       *index = TEMPLATE_PARM_IDX (parm);
21696       *level = TEMPLATE_PARM_LEVEL (parm);
21697     }
21698 }
21699
21700 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
21701   do {                                                                  \
21702     if (unify (TP, TA, P, A, S, EP))                                    \
21703       return 1;                                                         \
21704   } while (0)
21705
21706 /* Unifies the remaining arguments in PACKED_ARGS with the pack
21707    expansion at the end of PACKED_PARMS. Returns 0 if the type
21708    deduction succeeds, 1 otherwise. STRICT is the same as in
21709    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
21710    function call argument list. We'll need to adjust the arguments to make them
21711    types. SUBR tells us if this is from a recursive call to
21712    type_unification_real, or for comparing two template argument
21713    lists. */
21714
21715 static int
21716 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
21717                       tree packed_args, unification_kind_t strict,
21718                       bool subr, bool explain_p)
21719 {
21720   tree parm
21721     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
21722   tree pattern = PACK_EXPANSION_PATTERN (parm);
21723   tree pack, packs = NULL_TREE;
21724   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
21725
21726   /* Add in any args remembered from an earlier partial instantiation.  */
21727   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21728   int levels = TMPL_ARGS_DEPTH (targs);
21729
21730   packed_args = expand_template_argument_pack (packed_args);
21731
21732   int len = TREE_VEC_LENGTH (packed_args);
21733
21734   /* Determine the parameter packs we will be deducing from the
21735      pattern, and record their current deductions.  */
21736   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21737        pack; pack = TREE_CHAIN (pack))
21738     {
21739       tree parm_pack = TREE_VALUE (pack);
21740       int idx, level;
21741
21742       /* Only template parameter packs can be deduced, not e.g. function
21743          parameter packs or __bases or __integer_pack.  */
21744       if (!TEMPLATE_PARM_P (parm_pack))
21745         continue;
21746
21747       /* Determine the index and level of this parameter pack.  */
21748       template_parm_level_and_index (parm_pack, &level, &idx);
21749       if (level < levels)
21750         continue;
21751
21752       /* Keep track of the parameter packs and their corresponding
21753          argument packs.  */
21754       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21755       TREE_TYPE (packs) = make_tree_vec (len - start);
21756     }
21757
21758   /* Loop through all of the arguments that have not yet been
21759      unified and unify each with the pattern.  */
21760   for (i = start; i < len; i++)
21761     {
21762       tree parm;
21763       bool any_explicit = false;
21764       tree arg = TREE_VEC_ELT (packed_args, i);
21765
21766       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21767          or the element of its argument pack at the current index if
21768          this argument was explicitly specified.  */
21769       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21770         {
21771           int idx, level;
21772           tree arg, pargs;
21773           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21774
21775           arg = NULL_TREE;
21776           if (TREE_VALUE (pack)
21777               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21778               && (i - start < TREE_VEC_LENGTH (pargs)))
21779             {
21780               any_explicit = true;
21781               arg = TREE_VEC_ELT (pargs, i - start);
21782             }
21783           TMPL_ARG (targs, level, idx) = arg;
21784         }
21785
21786       /* If we had explicit template arguments, substitute them into the
21787          pattern before deduction.  */
21788       if (any_explicit)
21789         {
21790           /* Some arguments might still be unspecified or dependent.  */
21791           bool dependent;
21792           ++processing_template_decl;
21793           dependent = any_dependent_template_arguments_p (targs);
21794           if (!dependent)
21795             --processing_template_decl;
21796           parm = tsubst (pattern, targs,
21797                          explain_p ? tf_warning_or_error : tf_none,
21798                          NULL_TREE);
21799           if (dependent)
21800             --processing_template_decl;
21801           if (parm == error_mark_node)
21802             return 1;
21803         }
21804       else
21805         parm = pattern;
21806
21807       /* Unify the pattern with the current argument.  */
21808       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21809                               explain_p))
21810         return 1;
21811
21812       /* For each parameter pack, collect the deduced value.  */
21813       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21814         {
21815           int idx, level;
21816           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21817
21818           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
21819             TMPL_ARG (targs, level, idx);
21820         }
21821     }
21822
21823   /* Verify that the results of unification with the parameter packs
21824      produce results consistent with what we've seen before, and make
21825      the deduced argument packs available.  */
21826   for (pack = packs; pack; pack = TREE_CHAIN (pack))
21827     {
21828       tree old_pack = TREE_VALUE (pack);
21829       tree new_args = TREE_TYPE (pack);
21830       int i, len = TREE_VEC_LENGTH (new_args);
21831       int idx, level;
21832       bool nondeduced_p = false;
21833
21834       /* By default keep the original deduced argument pack.
21835          If necessary, more specific code is going to update the
21836          resulting deduced argument later down in this function.  */
21837       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21838       TMPL_ARG (targs, level, idx) = old_pack;
21839
21840       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21841          actually deduce anything.  */
21842       for (i = 0; i < len && !nondeduced_p; ++i)
21843         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21844           nondeduced_p = true;
21845       if (nondeduced_p)
21846         continue;
21847
21848       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21849         {
21850           /* If we had fewer function args than explicit template args,
21851              just use the explicits.  */
21852           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21853           int explicit_len = TREE_VEC_LENGTH (explicit_args);
21854           if (len < explicit_len)
21855             new_args = explicit_args;
21856         }
21857
21858       if (!old_pack)
21859         {
21860           tree result;
21861           /* Build the deduced *_ARGUMENT_PACK.  */
21862           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21863             {
21864               result = make_node (NONTYPE_ARGUMENT_PACK);
21865               TREE_CONSTANT (result) = 1;
21866             }
21867           else
21868             result = cxx_make_type (TYPE_ARGUMENT_PACK);
21869
21870           SET_ARGUMENT_PACK_ARGS (result, new_args);
21871
21872           /* Note the deduced argument packs for this parameter
21873              pack.  */
21874           TMPL_ARG (targs, level, idx) = result;
21875         }
21876       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21877                && (ARGUMENT_PACK_ARGS (old_pack) 
21878                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21879         {
21880           /* We only had the explicitly-provided arguments before, but
21881              now we have a complete set of arguments.  */
21882           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21883
21884           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21885           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21886           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21887         }
21888       else
21889         {
21890           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21891           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21892
21893           if (!comp_template_args (old_args, new_args,
21894                                    &bad_old_arg, &bad_new_arg))
21895             /* Inconsistent unification of this parameter pack.  */
21896             return unify_parameter_pack_inconsistent (explain_p,
21897                                                       bad_old_arg,
21898                                                       bad_new_arg);
21899         }
21900     }
21901
21902   return unify_success (explain_p);
21903 }
21904
21905 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
21906    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
21907    parameters and return value are as for unify.  */
21908
21909 static int
21910 unify_array_domain (tree tparms, tree targs,
21911                     tree parm_dom, tree arg_dom,
21912                     bool explain_p)
21913 {
21914   tree parm_max;
21915   tree arg_max;
21916   bool parm_cst;
21917   bool arg_cst;
21918
21919   /* Our representation of array types uses "N - 1" as the
21920      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21921      not an integer constant.  We cannot unify arbitrarily
21922      complex expressions, so we eliminate the MINUS_EXPRs
21923      here.  */
21924   parm_max = TYPE_MAX_VALUE (parm_dom);
21925   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21926   if (!parm_cst)
21927     {
21928       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21929       parm_max = TREE_OPERAND (parm_max, 0);
21930     }
21931   arg_max = TYPE_MAX_VALUE (arg_dom);
21932   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21933   if (!arg_cst)
21934     {
21935       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21936          trying to unify the type of a variable with the type
21937          of a template parameter.  For example:
21938
21939            template <unsigned int N>
21940            void f (char (&) [N]);
21941            int g();
21942            void h(int i) {
21943              char a[g(i)];
21944              f(a);
21945            }
21946
21947          Here, the type of the ARG will be "int [g(i)]", and
21948          may be a SAVE_EXPR, etc.  */
21949       if (TREE_CODE (arg_max) != MINUS_EXPR)
21950         return unify_vla_arg (explain_p, arg_dom);
21951       arg_max = TREE_OPERAND (arg_max, 0);
21952     }
21953
21954   /* If only one of the bounds used a MINUS_EXPR, compensate
21955      by adding one to the other bound.  */
21956   if (parm_cst && !arg_cst)
21957     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21958                                 integer_type_node,
21959                                 parm_max,
21960                                 integer_one_node);
21961   else if (arg_cst && !parm_cst)
21962     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21963                                integer_type_node,
21964                                arg_max,
21965                                integer_one_node);
21966
21967   return unify (tparms, targs, parm_max, arg_max,
21968                 UNIFY_ALLOW_INTEGER, explain_p);
21969 }
21970
21971 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
21972
21973 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21974
21975 static pa_kind_t
21976 pa_kind (tree t)
21977 {
21978   if (PACK_EXPANSION_P (t))
21979     t = PACK_EXPANSION_PATTERN (t);
21980   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21981       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21982       || DECL_TYPE_TEMPLATE_P (t))
21983     return pa_tmpl;
21984   else if (TYPE_P (t))
21985     return pa_type;
21986   else
21987     return pa_expr;
21988 }
21989
21990 /* Deduce the value of template parameters.  TPARMS is the (innermost)
21991    set of template parameters to a template.  TARGS is the bindings
21992    for those template parameters, as determined thus far; TARGS may
21993    include template arguments for outer levels of template parameters
21994    as well.  PARM is a parameter to a template function, or a
21995    subcomponent of that parameter; ARG is the corresponding argument.
21996    This function attempts to match PARM with ARG in a manner
21997    consistent with the existing assignments in TARGS.  If more values
21998    are deduced, then TARGS is updated.
21999
22000    Returns 0 if the type deduction succeeds, 1 otherwise.  The
22001    parameter STRICT is a bitwise or of the following flags:
22002
22003      UNIFY_ALLOW_NONE:
22004        Require an exact match between PARM and ARG.
22005      UNIFY_ALLOW_MORE_CV_QUAL:
22006        Allow the deduced ARG to be more cv-qualified (by qualification
22007        conversion) than ARG.
22008      UNIFY_ALLOW_LESS_CV_QUAL:
22009        Allow the deduced ARG to be less cv-qualified than ARG.
22010      UNIFY_ALLOW_DERIVED:
22011        Allow the deduced ARG to be a template base class of ARG,
22012        or a pointer to a template base class of the type pointed to by
22013        ARG.
22014      UNIFY_ALLOW_INTEGER:
22015        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
22016        case for more information.
22017      UNIFY_ALLOW_OUTER_LEVEL:
22018        This is the outermost level of a deduction. Used to determine validity
22019        of qualification conversions. A valid qualification conversion must
22020        have const qualified pointers leading up to the inner type which
22021        requires additional CV quals, except at the outer level, where const
22022        is not required [conv.qual]. It would be normal to set this flag in
22023        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
22024      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
22025        This is the outermost level of a deduction, and PARM can be more CV
22026        qualified at this point.
22027      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
22028        This is the outermost level of a deduction, and PARM can be less CV
22029        qualified at this point.  */
22030
22031 static int
22032 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
22033        bool explain_p)
22034 {
22035   int idx;
22036   tree targ;
22037   tree tparm;
22038   int strict_in = strict;
22039   tsubst_flags_t complain = (explain_p
22040                              ? tf_warning_or_error
22041                              : tf_none);
22042
22043   /* I don't think this will do the right thing with respect to types.
22044      But the only case I've seen it in so far has been array bounds, where
22045      signedness is the only information lost, and I think that will be
22046      okay.  */
22047   while (CONVERT_EXPR_P (parm))
22048     parm = TREE_OPERAND (parm, 0);
22049
22050   if (arg == error_mark_node)
22051     return unify_invalid (explain_p);
22052   if (arg == unknown_type_node
22053       || arg == init_list_type_node)
22054     /* We can't deduce anything from this, but we might get all the
22055        template args from other function args.  */
22056     return unify_success (explain_p);
22057
22058   if (parm == any_targ_node || arg == any_targ_node)
22059     return unify_success (explain_p);
22060
22061   /* If PARM uses template parameters, then we can't bail out here,
22062      even if ARG == PARM, since we won't record unifications for the
22063      template parameters.  We might need them if we're trying to
22064      figure out which of two things is more specialized.  */
22065   if (arg == parm && !uses_template_parms (parm))
22066     return unify_success (explain_p);
22067
22068   /* Handle init lists early, so the rest of the function can assume
22069      we're dealing with a type. */
22070   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
22071     {
22072       tree elt, elttype;
22073       unsigned i;
22074       tree orig_parm = parm;
22075
22076       /* Replace T with std::initializer_list<T> for deduction.  */
22077       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22078           && flag_deduce_init_list)
22079         parm = listify (parm);
22080
22081       if (!is_std_init_list (parm)
22082           && TREE_CODE (parm) != ARRAY_TYPE)
22083         /* We can only deduce from an initializer list argument if the
22084            parameter is std::initializer_list or an array; otherwise this
22085            is a non-deduced context. */
22086         return unify_success (explain_p);
22087
22088       if (TREE_CODE (parm) == ARRAY_TYPE)
22089         elttype = TREE_TYPE (parm);
22090       else
22091         {
22092           elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
22093           /* Deduction is defined in terms of a single type, so just punt
22094              on the (bizarre) std::initializer_list<T...>.  */
22095           if (PACK_EXPANSION_P (elttype))
22096             return unify_success (explain_p);
22097         }
22098
22099       if (strict != DEDUCE_EXACT
22100           && TYPE_P (elttype)
22101           && !uses_deducible_template_parms (elttype))
22102         /* If ELTTYPE has no deducible template parms, skip deduction from
22103            the list elements.  */;
22104       else
22105         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
22106           {
22107             int elt_strict = strict;
22108
22109             if (elt == error_mark_node)
22110               return unify_invalid (explain_p);
22111
22112             if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
22113               {
22114                 tree type = TREE_TYPE (elt);
22115                 if (type == error_mark_node)
22116                   return unify_invalid (explain_p);
22117                 /* It should only be possible to get here for a call.  */
22118                 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
22119                 elt_strict |= maybe_adjust_types_for_deduction
22120                   (DEDUCE_CALL, &elttype, &type, elt);
22121                 elt = type;
22122               }
22123
22124           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
22125                                    explain_p);
22126         }
22127
22128       if (TREE_CODE (parm) == ARRAY_TYPE
22129           && deducible_array_bound (TYPE_DOMAIN (parm)))
22130         {
22131           /* Also deduce from the length of the initializer list.  */
22132           tree max = size_int (CONSTRUCTOR_NELTS (arg));
22133           tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
22134           if (idx == error_mark_node)
22135             return unify_invalid (explain_p);
22136           return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
22137                                      idx, explain_p);
22138         }
22139
22140       /* If the std::initializer_list<T> deduction worked, replace the
22141          deduced A with std::initializer_list<A>.  */
22142       if (orig_parm != parm)
22143         {
22144           idx = TEMPLATE_TYPE_IDX (orig_parm);
22145           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
22146           targ = listify (targ);
22147           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
22148         }
22149       return unify_success (explain_p);
22150     }
22151
22152   /* If parm and arg aren't the same kind of thing (template, type, or
22153      expression), fail early.  */
22154   if (pa_kind (parm) != pa_kind (arg))
22155     return unify_invalid (explain_p);
22156
22157   /* Immediately reject some pairs that won't unify because of
22158      cv-qualification mismatches.  */
22159   if (TREE_CODE (arg) == TREE_CODE (parm)
22160       && TYPE_P (arg)
22161       /* It is the elements of the array which hold the cv quals of an array
22162          type, and the elements might be template type parms. We'll check
22163          when we recurse.  */
22164       && TREE_CODE (arg) != ARRAY_TYPE
22165       /* We check the cv-qualifiers when unifying with template type
22166          parameters below.  We want to allow ARG `const T' to unify with
22167          PARM `T' for example, when computing which of two templates
22168          is more specialized, for example.  */
22169       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
22170       && !check_cv_quals_for_unify (strict_in, arg, parm))
22171     return unify_cv_qual_mismatch (explain_p, parm, arg);
22172
22173   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
22174       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
22175     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
22176   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
22177   strict &= ~UNIFY_ALLOW_DERIVED;
22178   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22179   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
22180
22181   switch (TREE_CODE (parm))
22182     {
22183     case TYPENAME_TYPE:
22184     case SCOPE_REF:
22185     case UNBOUND_CLASS_TEMPLATE:
22186       /* In a type which contains a nested-name-specifier, template
22187          argument values cannot be deduced for template parameters used
22188          within the nested-name-specifier.  */
22189       return unify_success (explain_p);
22190
22191     case TEMPLATE_TYPE_PARM:
22192     case TEMPLATE_TEMPLATE_PARM:
22193     case BOUND_TEMPLATE_TEMPLATE_PARM:
22194       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
22195       if (error_operand_p (tparm))
22196         return unify_invalid (explain_p);
22197
22198       if (TEMPLATE_TYPE_LEVEL (parm)
22199           != template_decl_level (tparm))
22200         /* The PARM is not one we're trying to unify.  Just check
22201            to see if it matches ARG.  */
22202         {
22203           if (TREE_CODE (arg) == TREE_CODE (parm)
22204               && (is_auto (parm) ? is_auto (arg)
22205                   : same_type_p (parm, arg)))
22206             return unify_success (explain_p);
22207           else
22208             return unify_type_mismatch (explain_p, parm, arg);
22209         }
22210       idx = TEMPLATE_TYPE_IDX (parm);
22211       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
22212       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
22213       if (error_operand_p (tparm))
22214         return unify_invalid (explain_p);
22215
22216       /* Check for mixed types and values.  */
22217       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22218            && TREE_CODE (tparm) != TYPE_DECL)
22219           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22220               && TREE_CODE (tparm) != TEMPLATE_DECL))
22221         gcc_unreachable ();
22222
22223       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22224         {
22225           if ((strict_in & UNIFY_ALLOW_DERIVED)
22226               && CLASS_TYPE_P (arg))
22227             {
22228               /* First try to match ARG directly.  */
22229               tree t = try_class_unification (tparms, targs, parm, arg,
22230                                               explain_p);
22231               if (!t)
22232                 {
22233                   /* Otherwise, look for a suitable base of ARG, as below.  */
22234                   enum template_base_result r;
22235                   r = get_template_base (tparms, targs, parm, arg,
22236                                          explain_p, &t);
22237                   if (!t)
22238                     return unify_no_common_base (explain_p, r, parm, arg);
22239                   arg = t;
22240                 }
22241             }
22242           /* ARG must be constructed from a template class or a template
22243              template parameter.  */
22244           else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
22245                    && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22246             return unify_template_deduction_failure (explain_p, parm, arg);
22247
22248           /* Deduce arguments T, i from TT<T> or TT<i>.  */
22249           if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
22250             return 1;
22251
22252           arg = TYPE_TI_TEMPLATE (arg);
22253
22254           /* Fall through to deduce template name.  */
22255         }
22256
22257       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22258           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22259         {
22260           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
22261
22262           /* Simple cases: Value already set, does match or doesn't.  */
22263           if (targ != NULL_TREE && template_args_equal (targ, arg))
22264             return unify_success (explain_p);
22265           else if (targ)
22266             return unify_inconsistency (explain_p, parm, targ, arg);
22267         }
22268       else
22269         {
22270           /* If PARM is `const T' and ARG is only `int', we don't have
22271              a match unless we are allowing additional qualification.
22272              If ARG is `const int' and PARM is just `T' that's OK;
22273              that binds `const int' to `T'.  */
22274           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
22275                                          arg, parm))
22276             return unify_cv_qual_mismatch (explain_p, parm, arg);
22277
22278           /* Consider the case where ARG is `const volatile int' and
22279              PARM is `const T'.  Then, T should be `volatile int'.  */
22280           arg = cp_build_qualified_type_real
22281             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
22282           if (arg == error_mark_node)
22283             return unify_invalid (explain_p);
22284
22285           /* Simple cases: Value already set, does match or doesn't.  */
22286           if (targ != NULL_TREE && same_type_p (targ, arg))
22287             return unify_success (explain_p);
22288           else if (targ)
22289             return unify_inconsistency (explain_p, parm, targ, arg);
22290
22291           /* Make sure that ARG is not a variable-sized array.  (Note
22292              that were talking about variable-sized arrays (like
22293              `int[n]'), rather than arrays of unknown size (like
22294              `int[]').)  We'll get very confused by such a type since
22295              the bound of the array is not constant, and therefore
22296              not mangleable.  Besides, such types are not allowed in
22297              ISO C++, so we can do as we please here.  We do allow
22298              them for 'auto' deduction, since that isn't ABI-exposed.  */
22299           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
22300             return unify_vla_arg (explain_p, arg);
22301
22302           /* Strip typedefs as in convert_template_argument.  */
22303           arg = canonicalize_type_argument (arg, tf_none);
22304         }
22305
22306       /* If ARG is a parameter pack or an expansion, we cannot unify
22307          against it unless PARM is also a parameter pack.  */
22308       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
22309           && !template_parameter_pack_p (parm))
22310         return unify_parameter_pack_mismatch (explain_p, parm, arg);
22311
22312       /* If the argument deduction results is a METHOD_TYPE,
22313          then there is a problem.
22314          METHOD_TYPE doesn't map to any real C++ type the result of
22315          the deduction cannot be of that type.  */
22316       if (TREE_CODE (arg) == METHOD_TYPE)
22317         return unify_method_type_error (explain_p, arg);
22318
22319       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
22320       return unify_success (explain_p);
22321
22322     case TEMPLATE_PARM_INDEX:
22323       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
22324       if (error_operand_p (tparm))
22325         return unify_invalid (explain_p);
22326
22327       if (TEMPLATE_PARM_LEVEL (parm)
22328           != template_decl_level (tparm))
22329         {
22330           /* The PARM is not one we're trying to unify.  Just check
22331              to see if it matches ARG.  */
22332           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
22333                          && cp_tree_equal (parm, arg));
22334           if (result)
22335             unify_expression_unequal (explain_p, parm, arg);
22336           return result;
22337         }
22338
22339       idx = TEMPLATE_PARM_IDX (parm);
22340       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
22341
22342       if (targ)
22343         {
22344           if ((strict & UNIFY_ALLOW_INTEGER)
22345               && TREE_TYPE (targ) && TREE_TYPE (arg)
22346               && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
22347             /* We're deducing from an array bound, the type doesn't matter.  */
22348             arg = fold_convert (TREE_TYPE (targ), arg);
22349           int x = !cp_tree_equal (targ, arg);
22350           if (x)
22351             unify_inconsistency (explain_p, parm, targ, arg);
22352           return x;
22353         }
22354
22355       /* [temp.deduct.type] If, in the declaration of a function template
22356          with a non-type template-parameter, the non-type
22357          template-parameter is used in an expression in the function
22358          parameter-list and, if the corresponding template-argument is
22359          deduced, the template-argument type shall match the type of the
22360          template-parameter exactly, except that a template-argument
22361          deduced from an array bound may be of any integral type.
22362          The non-type parameter might use already deduced type parameters.  */
22363       tparm = TREE_TYPE (parm);
22364       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
22365         /* We don't have enough levels of args to do any substitution.  This
22366            can happen in the context of -fnew-ttp-matching.  */;
22367       else
22368         {
22369           ++processing_template_decl;
22370           tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
22371           --processing_template_decl;
22372
22373           if (tree a = type_uses_auto (tparm))
22374             {
22375               tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
22376               if (tparm == error_mark_node)
22377                 return 1;
22378             }
22379         }
22380
22381       if (!TREE_TYPE (arg))
22382         /* Template-parameter dependent expression.  Just accept it for now.
22383            It will later be processed in convert_template_argument.  */
22384         ;
22385       else if (same_type_ignoring_top_level_qualifiers_p
22386                (non_reference (TREE_TYPE (arg)),
22387                 non_reference (tparm)))
22388         /* OK.  Ignore top-level quals here because a class-type template
22389            parameter object is const.  */;
22390       else if ((strict & UNIFY_ALLOW_INTEGER)
22391                && CP_INTEGRAL_TYPE_P (tparm))
22392         /* Convert the ARG to the type of PARM; the deduced non-type
22393            template argument must exactly match the types of the
22394            corresponding parameter.  */
22395         arg = fold (build_nop (tparm, arg));
22396       else if (uses_template_parms (tparm))
22397         {
22398           /* We haven't deduced the type of this parameter yet.  */
22399           if (cxx_dialect >= cxx17
22400               /* We deduce from array bounds in try_array_deduction.  */
22401               && !(strict & UNIFY_ALLOW_INTEGER))
22402             {
22403               /* Deduce it from the non-type argument.  */
22404               tree atype = TREE_TYPE (arg);
22405               RECUR_AND_CHECK_FAILURE (tparms, targs,
22406                                        tparm, atype,
22407                                        UNIFY_ALLOW_NONE, explain_p);
22408             }
22409           else
22410             /* Try again later.  */
22411             return unify_success (explain_p);
22412         }
22413       else
22414         return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
22415
22416       /* If ARG is a parameter pack or an expansion, we cannot unify
22417          against it unless PARM is also a parameter pack.  */
22418       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
22419           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
22420         return unify_parameter_pack_mismatch (explain_p, parm, arg);
22421
22422       {
22423         bool removed_attr = false;
22424         arg = strip_typedefs_expr (arg, &removed_attr);
22425       }
22426       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
22427       return unify_success (explain_p);
22428
22429     case PTRMEM_CST:
22430      {
22431         /* A pointer-to-member constant can be unified only with
22432          another constant.  */
22433       if (TREE_CODE (arg) != PTRMEM_CST)
22434         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
22435
22436       /* Just unify the class member. It would be useless (and possibly
22437          wrong, depending on the strict flags) to unify also
22438          PTRMEM_CST_CLASS, because we want to be sure that both parm and
22439          arg refer to the same variable, even if through different
22440          classes. For instance:
22441
22442          struct A { int x; };
22443          struct B : A { };
22444
22445          Unification of &A::x and &B::x must succeed.  */
22446       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
22447                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
22448      }
22449
22450     case POINTER_TYPE:
22451       {
22452         if (!TYPE_PTR_P (arg))
22453           return unify_type_mismatch (explain_p, parm, arg);
22454
22455         /* [temp.deduct.call]
22456
22457            A can be another pointer or pointer to member type that can
22458            be converted to the deduced A via a qualification
22459            conversion (_conv.qual_).
22460
22461            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
22462            This will allow for additional cv-qualification of the
22463            pointed-to types if appropriate.  */
22464
22465         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
22466           /* The derived-to-base conversion only persists through one
22467              level of pointers.  */
22468           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
22469
22470         return unify (tparms, targs, TREE_TYPE (parm),
22471                       TREE_TYPE (arg), strict, explain_p);
22472       }
22473
22474     case REFERENCE_TYPE:
22475       if (!TYPE_REF_P (arg))
22476         return unify_type_mismatch (explain_p, parm, arg);
22477       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22478                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
22479
22480     case ARRAY_TYPE:
22481       if (TREE_CODE (arg) != ARRAY_TYPE)
22482         return unify_type_mismatch (explain_p, parm, arg);
22483       if ((TYPE_DOMAIN (parm) == NULL_TREE)
22484           != (TYPE_DOMAIN (arg) == NULL_TREE))
22485         return unify_type_mismatch (explain_p, parm, arg);
22486       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22487                                strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
22488       if (TYPE_DOMAIN (parm) != NULL_TREE)
22489         return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
22490                                    TYPE_DOMAIN (arg), explain_p);
22491       return unify_success (explain_p);
22492
22493     case REAL_TYPE:
22494     case COMPLEX_TYPE:
22495     case VECTOR_TYPE:
22496     case INTEGER_TYPE:
22497     case BOOLEAN_TYPE:
22498     case ENUMERAL_TYPE:
22499     case VOID_TYPE:
22500     case NULLPTR_TYPE:
22501       if (TREE_CODE (arg) != TREE_CODE (parm))
22502         return unify_type_mismatch (explain_p, parm, arg);
22503
22504       /* We have already checked cv-qualification at the top of the
22505          function.  */
22506       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
22507         return unify_type_mismatch (explain_p, parm, arg);
22508
22509       /* As far as unification is concerned, this wins.  Later checks
22510          will invalidate it if necessary.  */
22511       return unify_success (explain_p);
22512
22513       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
22514       /* Type INTEGER_CST can come from ordinary constant template args.  */
22515     case INTEGER_CST:
22516       while (CONVERT_EXPR_P (arg))
22517         arg = TREE_OPERAND (arg, 0);
22518
22519       if (TREE_CODE (arg) != INTEGER_CST)
22520         return unify_template_argument_mismatch (explain_p, parm, arg);
22521       return (tree_int_cst_equal (parm, arg)
22522               ? unify_success (explain_p)
22523               : unify_template_argument_mismatch (explain_p, parm, arg));
22524
22525     case TREE_VEC:
22526       {
22527         int i, len, argslen;
22528         int parm_variadic_p = 0;
22529
22530         if (TREE_CODE (arg) != TREE_VEC)
22531           return unify_template_argument_mismatch (explain_p, parm, arg);
22532
22533         len = TREE_VEC_LENGTH (parm);
22534         argslen = TREE_VEC_LENGTH (arg);
22535
22536         /* Check for pack expansions in the parameters.  */
22537         for (i = 0; i < len; ++i)
22538           {
22539             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
22540               {
22541                 if (i == len - 1)
22542                   /* We can unify against something with a trailing
22543                      parameter pack.  */
22544                   parm_variadic_p = 1;
22545                 else
22546                   /* [temp.deduct.type]/9: If the template argument list of
22547                      P contains a pack expansion that is not the last
22548                      template argument, the entire template argument list
22549                      is a non-deduced context.  */
22550                   return unify_success (explain_p);
22551               }
22552           }
22553
22554         /* If we don't have enough arguments to satisfy the parameters
22555            (not counting the pack expression at the end), or we have
22556            too many arguments for a parameter list that doesn't end in
22557            a pack expression, we can't unify.  */
22558         if (parm_variadic_p
22559             ? argslen < len - parm_variadic_p
22560             : argslen != len)
22561           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
22562
22563         /* Unify all of the parameters that precede the (optional)
22564            pack expression.  */
22565         for (i = 0; i < len - parm_variadic_p; ++i)
22566           {
22567             RECUR_AND_CHECK_FAILURE (tparms, targs,
22568                                      TREE_VEC_ELT (parm, i),
22569                                      TREE_VEC_ELT (arg, i),
22570                                      UNIFY_ALLOW_NONE, explain_p);
22571           }
22572         if (parm_variadic_p)
22573           return unify_pack_expansion (tparms, targs, parm, arg,
22574                                        DEDUCE_EXACT,
22575                                        /*subr=*/true, explain_p);
22576         return unify_success (explain_p);
22577       }
22578
22579     case RECORD_TYPE:
22580     case UNION_TYPE:
22581       if (TREE_CODE (arg) != TREE_CODE (parm))
22582         return unify_type_mismatch (explain_p, parm, arg);
22583
22584       if (TYPE_PTRMEMFUNC_P (parm))
22585         {
22586           if (!TYPE_PTRMEMFUNC_P (arg))
22587             return unify_type_mismatch (explain_p, parm, arg);
22588
22589           return unify (tparms, targs,
22590                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
22591                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
22592                         strict, explain_p);
22593         }
22594       else if (TYPE_PTRMEMFUNC_P (arg))
22595         return unify_type_mismatch (explain_p, parm, arg);
22596
22597       if (CLASSTYPE_TEMPLATE_INFO (parm))
22598         {
22599           tree t = NULL_TREE;
22600
22601           if (strict_in & UNIFY_ALLOW_DERIVED)
22602             {
22603               /* First, we try to unify the PARM and ARG directly.  */
22604               t = try_class_unification (tparms, targs,
22605                                          parm, arg, explain_p);
22606
22607               if (!t)
22608                 {
22609                   /* Fallback to the special case allowed in
22610                      [temp.deduct.call]:
22611
22612                        If P is a class, and P has the form
22613                        template-id, then A can be a derived class of
22614                        the deduced A.  Likewise, if P is a pointer to
22615                        a class of the form template-id, A can be a
22616                        pointer to a derived class pointed to by the
22617                        deduced A.  */
22618                   enum template_base_result r;
22619                   r = get_template_base (tparms, targs, parm, arg,
22620                                          explain_p, &t);
22621
22622                   if (!t)
22623                     {
22624                       /* Don't give the derived diagnostic if we're
22625                          already dealing with the same template.  */
22626                       bool same_template
22627                         = (CLASSTYPE_TEMPLATE_INFO (arg)
22628                            && (CLASSTYPE_TI_TEMPLATE (parm)
22629                                == CLASSTYPE_TI_TEMPLATE (arg)));
22630                       return unify_no_common_base (explain_p && !same_template,
22631                                                    r, parm, arg);
22632                     }
22633                 }
22634             }
22635           else if (CLASSTYPE_TEMPLATE_INFO (arg)
22636                    && (CLASSTYPE_TI_TEMPLATE (parm)
22637                        == CLASSTYPE_TI_TEMPLATE (arg)))
22638             /* Perhaps PARM is something like S<U> and ARG is S<int>.
22639                Then, we should unify `int' and `U'.  */
22640             t = arg;
22641           else
22642             /* There's no chance of unification succeeding.  */
22643             return unify_type_mismatch (explain_p, parm, arg);
22644
22645           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
22646                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
22647         }
22648       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
22649         return unify_type_mismatch (explain_p, parm, arg);
22650       return unify_success (explain_p);
22651
22652     case METHOD_TYPE:
22653     case FUNCTION_TYPE:
22654       {
22655         unsigned int nargs;
22656         tree *args;
22657         tree a;
22658         unsigned int i;
22659
22660         if (TREE_CODE (arg) != TREE_CODE (parm))
22661           return unify_type_mismatch (explain_p, parm, arg);
22662
22663         /* CV qualifications for methods can never be deduced, they must
22664            match exactly.  We need to check them explicitly here,
22665            because type_unification_real treats them as any other
22666            cv-qualified parameter.  */
22667         if (TREE_CODE (parm) == METHOD_TYPE
22668             && (!check_cv_quals_for_unify
22669                 (UNIFY_ALLOW_NONE,
22670                  class_of_this_parm (arg),
22671                  class_of_this_parm (parm))))
22672           return unify_cv_qual_mismatch (explain_p, parm, arg);
22673         if (TREE_CODE (arg) == FUNCTION_TYPE
22674             && type_memfn_quals (parm) != type_memfn_quals (arg))
22675           return unify_cv_qual_mismatch (explain_p, parm, arg);
22676         if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
22677           return unify_type_mismatch (explain_p, parm, arg);
22678
22679         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
22680                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
22681
22682         nargs = list_length (TYPE_ARG_TYPES (arg));
22683         args = XALLOCAVEC (tree, nargs);
22684         for (a = TYPE_ARG_TYPES (arg), i = 0;
22685              a != NULL_TREE && a != void_list_node;
22686              a = TREE_CHAIN (a), ++i)
22687           args[i] = TREE_VALUE (a);
22688         nargs = i;
22689
22690         if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
22691                                    args, nargs, 1, DEDUCE_EXACT,
22692                                    NULL, explain_p))
22693           return 1;
22694
22695         if (flag_noexcept_type)
22696           {
22697             tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
22698             tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
22699             if (pspec == NULL_TREE) pspec = noexcept_false_spec;
22700             if (aspec == NULL_TREE) aspec = noexcept_false_spec;
22701             if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
22702                 && uses_template_parms (TREE_PURPOSE (pspec)))
22703               RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
22704                                        TREE_PURPOSE (aspec),
22705                                        UNIFY_ALLOW_NONE, explain_p);
22706             else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
22707               return unify_type_mismatch (explain_p, parm, arg);
22708           }
22709
22710         return 0;
22711       }
22712
22713     case OFFSET_TYPE:
22714       /* Unify a pointer to member with a pointer to member function, which
22715          deduces the type of the member as a function type. */
22716       if (TYPE_PTRMEMFUNC_P (arg))
22717         {
22718           /* Check top-level cv qualifiers */
22719           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
22720             return unify_cv_qual_mismatch (explain_p, parm, arg);
22721
22722           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22723                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
22724                                    UNIFY_ALLOW_NONE, explain_p);
22725
22726           /* Determine the type of the function we are unifying against. */
22727           tree fntype = static_fn_type (arg);
22728
22729           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
22730         }
22731
22732       if (TREE_CODE (arg) != OFFSET_TYPE)
22733         return unify_type_mismatch (explain_p, parm, arg);
22734       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22735                                TYPE_OFFSET_BASETYPE (arg),
22736                                UNIFY_ALLOW_NONE, explain_p);
22737       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22738                     strict, explain_p);
22739
22740     case CONST_DECL:
22741       if (DECL_TEMPLATE_PARM_P (parm))
22742         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22743       if (arg != scalar_constant_value (parm))
22744         return unify_template_argument_mismatch (explain_p, parm, arg);
22745       return unify_success (explain_p);
22746
22747     case FIELD_DECL:
22748     case TEMPLATE_DECL:
22749       /* Matched cases are handled by the ARG == PARM test above.  */
22750       return unify_template_argument_mismatch (explain_p, parm, arg);
22751
22752     case VAR_DECL:
22753       /* We might get a variable as a non-type template argument in parm if the
22754          corresponding parameter is type-dependent.  Make any necessary
22755          adjustments based on whether arg is a reference.  */
22756       if (CONSTANT_CLASS_P (arg))
22757         parm = fold_non_dependent_expr (parm, complain);
22758       else if (REFERENCE_REF_P (arg))
22759         {
22760           tree sub = TREE_OPERAND (arg, 0);
22761           STRIP_NOPS (sub);
22762           if (TREE_CODE (sub) == ADDR_EXPR)
22763             arg = TREE_OPERAND (sub, 0);
22764         }
22765       /* Now use the normal expression code to check whether they match.  */
22766       goto expr;
22767
22768     case TYPE_ARGUMENT_PACK:
22769     case NONTYPE_ARGUMENT_PACK:
22770       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22771                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22772
22773     case TYPEOF_TYPE:
22774     case DECLTYPE_TYPE:
22775     case UNDERLYING_TYPE:
22776       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22777          or UNDERLYING_TYPE nodes.  */
22778       return unify_success (explain_p);
22779
22780     case ERROR_MARK:
22781       /* Unification fails if we hit an error node.  */
22782       return unify_invalid (explain_p);
22783
22784     case INDIRECT_REF:
22785       if (REFERENCE_REF_P (parm))
22786         {
22787           bool pexp = PACK_EXPANSION_P (arg);
22788           if (pexp)
22789             arg = PACK_EXPANSION_PATTERN (arg);
22790           if (REFERENCE_REF_P (arg))
22791             arg = TREE_OPERAND (arg, 0);
22792           if (pexp)
22793             arg = make_pack_expansion (arg, complain);
22794           return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22795                         strict, explain_p);
22796         }
22797       /* FALLTHRU */
22798
22799     default:
22800       /* An unresolved overload is a nondeduced context.  */
22801       if (is_overloaded_fn (parm) || type_unknown_p (parm))
22802         return unify_success (explain_p);
22803       gcc_assert (EXPR_P (parm)
22804                   || COMPOUND_LITERAL_P (parm)
22805                   || TREE_CODE (parm) == TRAIT_EXPR);
22806     expr:
22807       /* We must be looking at an expression.  This can happen with
22808          something like:
22809
22810            template <int I>
22811            void foo(S<I>, S<I + 2>);
22812
22813          or
22814
22815            template<typename T>
22816            void foo(A<T, T{}>);
22817
22818          This is a "non-deduced context":
22819
22820            [deduct.type]
22821
22822            The non-deduced contexts are:
22823
22824            --A non-type template argument or an array bound in which
22825              a subexpression references a template parameter.
22826
22827          In these cases, we assume deduction succeeded, but don't
22828          actually infer any unifications.  */
22829
22830       if (!uses_template_parms (parm)
22831           && !template_args_equal (parm, arg))
22832         return unify_expression_unequal (explain_p, parm, arg);
22833       else
22834         return unify_success (explain_p);
22835     }
22836 }
22837 #undef RECUR_AND_CHECK_FAILURE
22838 \f
22839 /* Note that DECL can be defined in this translation unit, if
22840    required.  */
22841
22842 static void
22843 mark_definable (tree decl)
22844 {
22845   tree clone;
22846   DECL_NOT_REALLY_EXTERN (decl) = 1;
22847   FOR_EACH_CLONE (clone, decl)
22848     DECL_NOT_REALLY_EXTERN (clone) = 1;
22849 }
22850
22851 /* Called if RESULT is explicitly instantiated, or is a member of an
22852    explicitly instantiated class.  */
22853
22854 void
22855 mark_decl_instantiated (tree result, int extern_p)
22856 {
22857   SET_DECL_EXPLICIT_INSTANTIATION (result);
22858
22859   /* If this entity has already been written out, it's too late to
22860      make any modifications.  */
22861   if (TREE_ASM_WRITTEN (result))
22862     return;
22863
22864   /* For anonymous namespace we don't need to do anything.  */
22865   if (decl_anon_ns_mem_p (result))
22866     {
22867       gcc_assert (!TREE_PUBLIC (result));
22868       return;
22869     }
22870
22871   if (TREE_CODE (result) != FUNCTION_DECL)
22872     /* The TREE_PUBLIC flag for function declarations will have been
22873        set correctly by tsubst.  */
22874     TREE_PUBLIC (result) = 1;
22875
22876   /* This might have been set by an earlier implicit instantiation.  */
22877   DECL_COMDAT (result) = 0;
22878
22879   if (extern_p)
22880     DECL_NOT_REALLY_EXTERN (result) = 0;
22881   else
22882     {
22883       mark_definable (result);
22884       mark_needed (result);
22885       /* Always make artificials weak.  */
22886       if (DECL_ARTIFICIAL (result) && flag_weak)
22887         comdat_linkage (result);
22888       /* For WIN32 we also want to put explicit instantiations in
22889          linkonce sections.  */
22890       else if (TREE_PUBLIC (result))
22891         maybe_make_one_only (result);
22892       if (TREE_CODE (result) == FUNCTION_DECL
22893           && DECL_TEMPLATE_INSTANTIATED (result))
22894         /* If the function has already been instantiated, clear DECL_EXTERNAL,
22895            since start_preparsed_function wouldn't have if we had an earlier
22896            extern explicit instantiation.  */
22897         DECL_EXTERNAL (result) = 0;
22898     }
22899
22900   /* If EXTERN_P, then this function will not be emitted -- unless
22901      followed by an explicit instantiation, at which point its linkage
22902      will be adjusted.  If !EXTERN_P, then this function will be
22903      emitted here.  In neither circumstance do we want
22904      import_export_decl to adjust the linkage.  */
22905   DECL_INTERFACE_KNOWN (result) = 1;
22906 }
22907
22908 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22909    important template arguments.  If any are missing, we check whether
22910    they're important by using error_mark_node for substituting into any
22911    args that were used for partial ordering (the ones between ARGS and END)
22912    and seeing if it bubbles up.  */
22913
22914 static bool
22915 check_undeduced_parms (tree targs, tree args, tree end)
22916 {
22917   bool found = false;
22918   int i;
22919   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22920     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22921       {
22922         found = true;
22923         TREE_VEC_ELT (targs, i) = error_mark_node;
22924       }
22925   if (found)
22926     {
22927       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22928       if (substed == error_mark_node)
22929         return true;
22930     }
22931   return false;
22932 }
22933
22934 /* Given two function templates PAT1 and PAT2, return:
22935
22936    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22937    -1 if PAT2 is more specialized than PAT1.
22938    0 if neither is more specialized.
22939
22940    LEN indicates the number of parameters we should consider
22941    (defaulted parameters should not be considered).
22942
22943    The 1998 std underspecified function template partial ordering, and
22944    DR214 addresses the issue.  We take pairs of arguments, one from
22945    each of the templates, and deduce them against each other.  One of
22946    the templates will be more specialized if all the *other*
22947    template's arguments deduce against its arguments and at least one
22948    of its arguments *does* *not* deduce against the other template's
22949    corresponding argument.  Deduction is done as for class templates.
22950    The arguments used in deduction have reference and top level cv
22951    qualifiers removed.  Iff both arguments were originally reference
22952    types *and* deduction succeeds in both directions, an lvalue reference
22953    wins against an rvalue reference and otherwise the template
22954    with the more cv-qualified argument wins for that pairing (if
22955    neither is more cv-qualified, they both are equal).  Unlike regular
22956    deduction, after all the arguments have been deduced in this way,
22957    we do *not* verify the deduced template argument values can be
22958    substituted into non-deduced contexts.
22959
22960    The logic can be a bit confusing here, because we look at deduce1 and
22961    targs1 to see if pat2 is at least as specialized, and vice versa; if we
22962    can find template arguments for pat1 to make arg1 look like arg2, that
22963    means that arg2 is at least as specialized as arg1.  */
22964
22965 int
22966 more_specialized_fn (tree pat1, tree pat2, int len)
22967 {
22968   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22969   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22970   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22971   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22972   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22973   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22974   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22975   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22976   tree origs1, origs2;
22977   bool lose1 = false;
22978   bool lose2 = false;
22979
22980   /* Remove the this parameter from non-static member functions.  If
22981      one is a non-static member function and the other is not a static
22982      member function, remove the first parameter from that function
22983      also.  This situation occurs for operator functions where we
22984      locate both a member function (with this pointer) and non-member
22985      operator (with explicit first operand).  */
22986   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22987     {
22988       len--; /* LEN is the number of significant arguments for DECL1 */
22989       args1 = TREE_CHAIN (args1);
22990       if (!DECL_STATIC_FUNCTION_P (decl2))
22991         args2 = TREE_CHAIN (args2);
22992     }
22993   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22994     {
22995       args2 = TREE_CHAIN (args2);
22996       if (!DECL_STATIC_FUNCTION_P (decl1))
22997         {
22998           len--;
22999           args1 = TREE_CHAIN (args1);
23000         }
23001     }
23002
23003   /* If only one is a conversion operator, they are unordered.  */
23004   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
23005     return 0;
23006
23007   /* Consider the return type for a conversion function */
23008   if (DECL_CONV_FN_P (decl1))
23009     {
23010       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
23011       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
23012       len++;
23013     }
23014
23015   processing_template_decl++;
23016
23017   origs1 = args1;
23018   origs2 = args2;
23019
23020   while (len--
23021          /* Stop when an ellipsis is seen.  */
23022          && args1 != NULL_TREE && args2 != NULL_TREE)
23023     {
23024       tree arg1 = TREE_VALUE (args1);
23025       tree arg2 = TREE_VALUE (args2);
23026       int deduce1, deduce2;
23027       int quals1 = -1;
23028       int quals2 = -1;
23029       int ref1 = 0;
23030       int ref2 = 0;
23031
23032       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
23033           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23034         {
23035           /* When both arguments are pack expansions, we need only
23036              unify the patterns themselves.  */
23037           arg1 = PACK_EXPANSION_PATTERN (arg1);
23038           arg2 = PACK_EXPANSION_PATTERN (arg2);
23039
23040           /* This is the last comparison we need to do.  */
23041           len = 0;
23042         }
23043
23044       /* DR 1847: If a particular P contains no template-parameters that
23045          participate in template argument deduction, that P is not used to
23046          determine the ordering.  */
23047       if (!uses_deducible_template_parms (arg1)
23048           && !uses_deducible_template_parms (arg2))
23049         goto next;
23050
23051       if (TYPE_REF_P (arg1))
23052         {
23053           ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
23054           arg1 = TREE_TYPE (arg1);
23055           quals1 = cp_type_quals (arg1);
23056         }
23057
23058       if (TYPE_REF_P (arg2))
23059         {
23060           ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
23061           arg2 = TREE_TYPE (arg2);
23062           quals2 = cp_type_quals (arg2);
23063         }
23064
23065       arg1 = TYPE_MAIN_VARIANT (arg1);
23066       arg2 = TYPE_MAIN_VARIANT (arg2);
23067
23068       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
23069         {
23070           int i, len2 = remaining_arguments (args2);
23071           tree parmvec = make_tree_vec (1);
23072           tree argvec = make_tree_vec (len2);
23073           tree ta = args2;
23074
23075           /* Setup the parameter vector, which contains only ARG1.  */
23076           TREE_VEC_ELT (parmvec, 0) = arg1;
23077
23078           /* Setup the argument vector, which contains the remaining
23079              arguments.  */
23080           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
23081             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
23082
23083           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
23084                                            argvec, DEDUCE_EXACT,
23085                                            /*subr=*/true, /*explain_p=*/false)
23086                      == 0);
23087
23088           /* We cannot deduce in the other direction, because ARG1 is
23089              a pack expansion but ARG2 is not.  */
23090           deduce2 = 0;
23091         }
23092       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23093         {
23094           int i, len1 = remaining_arguments (args1);
23095           tree parmvec = make_tree_vec (1);
23096           tree argvec = make_tree_vec (len1);
23097           tree ta = args1;
23098
23099           /* Setup the parameter vector, which contains only ARG1.  */
23100           TREE_VEC_ELT (parmvec, 0) = arg2;
23101
23102           /* Setup the argument vector, which contains the remaining
23103              arguments.  */
23104           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
23105             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
23106
23107           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
23108                                            argvec, DEDUCE_EXACT,
23109                                            /*subr=*/true, /*explain_p=*/false)
23110                      == 0);
23111
23112           /* We cannot deduce in the other direction, because ARG2 is
23113              a pack expansion but ARG1 is not.*/
23114           deduce1 = 0;
23115         }
23116
23117       else
23118         {
23119           /* The normal case, where neither argument is a pack
23120              expansion.  */
23121           deduce1 = (unify (tparms1, targs1, arg1, arg2,
23122                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
23123                      == 0);
23124           deduce2 = (unify (tparms2, targs2, arg2, arg1,
23125                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
23126                      == 0);
23127         }
23128
23129       /* If we couldn't deduce arguments for tparms1 to make arg1 match
23130          arg2, then arg2 is not as specialized as arg1.  */
23131       if (!deduce1)
23132         lose2 = true;
23133       if (!deduce2)
23134         lose1 = true;
23135
23136       /* "If, for a given type, deduction succeeds in both directions
23137          (i.e., the types are identical after the transformations above)
23138          and both P and A were reference types (before being replaced with
23139          the type referred to above):
23140          - if the type from the argument template was an lvalue reference and
23141          the type from the parameter template was not, the argument type is
23142          considered to be more specialized than the other; otherwise,
23143          - if the type from the argument template is more cv-qualified
23144          than the type from the parameter template (as described above),
23145          the argument type is considered to be more specialized than the other;
23146          otherwise,
23147          - neither type is more specialized than the other."  */
23148
23149       if (deduce1 && deduce2)
23150         {
23151           if (ref1 && ref2 && ref1 != ref2)
23152             {
23153               if (ref1 > ref2)
23154                 lose1 = true;
23155               else
23156                 lose2 = true;
23157             }
23158           else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
23159             {
23160               if ((quals1 & quals2) == quals2)
23161                 lose2 = true;
23162               if ((quals1 & quals2) == quals1)
23163                 lose1 = true;
23164             }
23165         }
23166
23167       if (lose1 && lose2)
23168         /* We've failed to deduce something in either direction.
23169            These must be unordered.  */
23170         break;
23171
23172     next:
23173
23174       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
23175           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23176         /* We have already processed all of the arguments in our
23177            handing of the pack expansion type.  */
23178         len = 0;
23179
23180       args1 = TREE_CHAIN (args1);
23181       args2 = TREE_CHAIN (args2);
23182     }
23183
23184   /* "In most cases, all template parameters must have values in order for
23185      deduction to succeed, but for partial ordering purposes a template
23186      parameter may remain without a value provided it is not used in the
23187      types being used for partial ordering."
23188
23189      Thus, if we are missing any of the targs1 we need to substitute into
23190      origs1, then pat2 is not as specialized as pat1.  This can happen when
23191      there is a nondeduced context.  */
23192   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
23193     lose2 = true;
23194   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
23195     lose1 = true;
23196
23197   processing_template_decl--;
23198
23199   /* If both deductions succeed, the partial ordering selects the more
23200      constrained template.  */
23201   if (!lose1 && !lose2)
23202     {
23203       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
23204       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
23205       lose1 = !subsumes_constraints (c1, c2);
23206       lose2 = !subsumes_constraints (c2, c1);
23207     }
23208
23209   /* All things being equal, if the next argument is a pack expansion
23210      for one function but not for the other, prefer the
23211      non-variadic function.  FIXME this is bogus; see c++/41958.  */
23212   if (lose1 == lose2
23213       && args1 && TREE_VALUE (args1)
23214       && args2 && TREE_VALUE (args2))
23215     {
23216       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
23217       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
23218     }
23219
23220   if (lose1 == lose2)
23221     return 0;
23222   else if (!lose1)
23223     return 1;
23224   else
23225     return -1;
23226 }
23227
23228 /* Determine which of two partial specializations of TMPL is more
23229    specialized.
23230
23231    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
23232    to the first partial specialization.  The TREE_PURPOSE is the
23233    innermost set of template parameters for the partial
23234    specialization.  PAT2 is similar, but for the second template.
23235
23236    Return 1 if the first partial specialization is more specialized;
23237    -1 if the second is more specialized; 0 if neither is more
23238    specialized.
23239
23240    See [temp.class.order] for information about determining which of
23241    two templates is more specialized.  */
23242
23243 static int
23244 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
23245 {
23246   tree targs;
23247   int winner = 0;
23248   bool any_deductions = false;
23249
23250   tree tmpl1 = TREE_VALUE (pat1);
23251   tree tmpl2 = TREE_VALUE (pat2);
23252   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
23253   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
23254
23255   /* Just like what happens for functions, if we are ordering between
23256      different template specializations, we may encounter dependent
23257      types in the arguments, and we need our dependency check functions
23258      to behave correctly.  */
23259   ++processing_template_decl;
23260   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
23261   if (targs)
23262     {
23263       --winner;
23264       any_deductions = true;
23265     }
23266
23267   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
23268   if (targs)
23269     {
23270       ++winner;
23271       any_deductions = true;
23272     }
23273   --processing_template_decl;
23274
23275   /* If both deductions succeed, the partial ordering selects the more
23276      constrained template.  */
23277   if (!winner && any_deductions)
23278     return more_constrained (tmpl1, tmpl2);
23279
23280   /* In the case of a tie where at least one of the templates
23281      has a parameter pack at the end, the template with the most
23282      non-packed parameters wins.  */
23283   if (winner == 0
23284       && any_deductions
23285       && (template_args_variadic_p (TREE_PURPOSE (pat1))
23286           || template_args_variadic_p (TREE_PURPOSE (pat2))))
23287     {
23288       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
23289       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
23290       int len1 = TREE_VEC_LENGTH (args1);
23291       int len2 = TREE_VEC_LENGTH (args2);
23292
23293       /* We don't count the pack expansion at the end.  */
23294       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
23295         --len1;
23296       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
23297         --len2;
23298
23299       if (len1 > len2)
23300         return 1;
23301       else if (len1 < len2)
23302         return -1;
23303     }
23304
23305   return winner;
23306 }
23307
23308 /* Return the template arguments that will produce the function signature
23309    DECL from the function template FN, with the explicit template
23310    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
23311    also match.  Return NULL_TREE if no satisfactory arguments could be
23312    found.  */
23313
23314 static tree
23315 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
23316 {
23317   int ntparms = DECL_NTPARMS (fn);
23318   tree targs = make_tree_vec (ntparms);
23319   tree decl_type = TREE_TYPE (decl);
23320   tree decl_arg_types;
23321   tree *args;
23322   unsigned int nargs, ix;
23323   tree arg;
23324
23325   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
23326
23327   /* Never do unification on the 'this' parameter.  */
23328   decl_arg_types = skip_artificial_parms_for (decl,
23329                                               TYPE_ARG_TYPES (decl_type));
23330
23331   nargs = list_length (decl_arg_types);
23332   args = XALLOCAVEC (tree, nargs);
23333   for (arg = decl_arg_types, ix = 0;
23334        arg != NULL_TREE && arg != void_list_node;
23335        arg = TREE_CHAIN (arg), ++ix)
23336     args[ix] = TREE_VALUE (arg);
23337
23338   if (fn_type_unification (fn, explicit_args, targs,
23339                            args, ix,
23340                            (check_rettype || DECL_CONV_FN_P (fn)
23341                             ? TREE_TYPE (decl_type) : NULL_TREE),
23342                            DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
23343                            /*explain_p=*/false,
23344                            /*decltype*/false)
23345       == error_mark_node)
23346     return NULL_TREE;
23347
23348   return targs;
23349 }
23350
23351 /* Return the innermost template arguments that, when applied to a partial
23352    specialization SPEC_TMPL of TMPL, yield the ARGS.
23353
23354    For example, suppose we have:
23355
23356      template <class T, class U> struct S {};
23357      template <class T> struct S<T*, int> {};
23358
23359    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
23360    partial specialization and the ARGS will be {double*, int}.  The resulting
23361    vector will be {double}, indicating that `T' is bound to `double'.  */
23362
23363 static tree
23364 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
23365 {
23366   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
23367   tree spec_args
23368     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
23369   int i, ntparms = TREE_VEC_LENGTH (tparms);
23370   tree deduced_args;
23371   tree innermost_deduced_args;
23372
23373   innermost_deduced_args = make_tree_vec (ntparms);
23374   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
23375     {
23376       deduced_args = copy_node (args);
23377       SET_TMPL_ARGS_LEVEL (deduced_args,
23378                            TMPL_ARGS_DEPTH (deduced_args),
23379                            innermost_deduced_args);
23380     }
23381   else
23382     deduced_args = innermost_deduced_args;
23383
23384   bool tried_array_deduction = (cxx_dialect < cxx17);
23385  again:
23386   if (unify (tparms, deduced_args,
23387              INNERMOST_TEMPLATE_ARGS (spec_args),
23388              INNERMOST_TEMPLATE_ARGS (args),
23389              UNIFY_ALLOW_NONE, /*explain_p=*/false))
23390     return NULL_TREE;
23391
23392   for (i =  0; i < ntparms; ++i)
23393     if (! TREE_VEC_ELT (innermost_deduced_args, i))
23394       {
23395         if (!tried_array_deduction)
23396           {
23397             try_array_deduction (tparms, innermost_deduced_args,
23398                                  INNERMOST_TEMPLATE_ARGS (spec_args));
23399             tried_array_deduction = true;
23400             if (TREE_VEC_ELT (innermost_deduced_args, i))
23401               goto again;
23402           }
23403         return NULL_TREE;
23404       }
23405
23406   if (!push_tinst_level (spec_tmpl, deduced_args))
23407     {
23408       excessive_deduction_depth = true;
23409       return NULL_TREE;
23410     }
23411
23412   /* Verify that nondeduced template arguments agree with the type
23413      obtained from argument deduction.
23414
23415      For example:
23416
23417        struct A { typedef int X; };
23418        template <class T, class U> struct C {};
23419        template <class T> struct C<T, typename T::X> {};
23420
23421      Then with the instantiation `C<A, int>', we can deduce that
23422      `T' is `A' but unify () does not check whether `typename T::X'
23423      is `int'.  */
23424   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
23425
23426   if (spec_args != error_mark_node)
23427     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
23428                                        INNERMOST_TEMPLATE_ARGS (spec_args),
23429                                        tmpl, tf_none, false, false);
23430
23431   pop_tinst_level ();
23432
23433   if (spec_args == error_mark_node
23434       /* We only need to check the innermost arguments; the other
23435          arguments will always agree.  */
23436       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
23437                                      INNERMOST_TEMPLATE_ARGS (args)))
23438     return NULL_TREE;
23439
23440   /* Now that we have bindings for all of the template arguments,
23441      ensure that the arguments deduced for the template template
23442      parameters have compatible template parameter lists.  See the use
23443      of template_template_parm_bindings_ok_p in fn_type_unification
23444      for more information.  */
23445   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
23446     return NULL_TREE;
23447
23448   return deduced_args;
23449 }
23450
23451 // Compare two function templates T1 and T2 by deducing bindings
23452 // from one against the other. If both deductions succeed, compare
23453 // constraints to see which is more constrained.
23454 static int
23455 more_specialized_inst (tree t1, tree t2)
23456 {
23457   int fate = 0;
23458   int count = 0;
23459
23460   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
23461     {
23462       --fate;
23463       ++count;
23464     }
23465
23466   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
23467     {
23468       ++fate;
23469       ++count;
23470     }
23471
23472   // If both deductions succeed, then one may be more constrained.
23473   if (count == 2 && fate == 0)
23474     fate = more_constrained (t1, t2);
23475
23476   return fate;
23477 }
23478
23479 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
23480    Return the TREE_LIST node with the most specialized template, if
23481    any.  If there is no most specialized template, the error_mark_node
23482    is returned.
23483
23484    Note that this function does not look at, or modify, the
23485    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
23486    returned is one of the elements of INSTANTIATIONS, callers may
23487    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
23488    and retrieve it from the value returned.  */
23489
23490 tree
23491 most_specialized_instantiation (tree templates)
23492 {
23493   tree fn, champ;
23494
23495   ++processing_template_decl;
23496
23497   champ = templates;
23498   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
23499     {
23500       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
23501       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
23502       if (fate == -1)
23503         champ = fn;
23504       else if (!fate)
23505         {
23506           /* Equally specialized, move to next function.  If there
23507              is no next function, nothing's most specialized.  */
23508           fn = TREE_CHAIN (fn);
23509           champ = fn;
23510           if (!fn)
23511             break;
23512         }
23513     }
23514
23515   if (champ)
23516     /* Now verify that champ is better than everything earlier in the
23517        instantiation list.  */
23518     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
23519       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
23520       {
23521         champ = NULL_TREE;
23522         break;
23523       }
23524     }
23525
23526   processing_template_decl--;
23527
23528   if (!champ)
23529     return error_mark_node;
23530
23531   return champ;
23532 }
23533
23534 /* If DECL is a specialization of some template, return the most
23535    general such template.  Otherwise, returns NULL_TREE.
23536
23537    For example, given:
23538
23539      template <class T> struct S { template <class U> void f(U); };
23540
23541    if TMPL is `template <class U> void S<int>::f(U)' this will return
23542    the full template.  This function will not trace past partial
23543    specializations, however.  For example, given in addition:
23544
23545      template <class T> struct S<T*> { template <class U> void f(U); };
23546
23547    if TMPL is `template <class U> void S<int*>::f(U)' this will return
23548    `template <class T> template <class U> S<T*>::f(U)'.  */
23549
23550 tree
23551 most_general_template (tree decl)
23552 {
23553   if (TREE_CODE (decl) != TEMPLATE_DECL)
23554     {
23555       if (tree tinfo = get_template_info (decl))
23556         decl = TI_TEMPLATE (tinfo);
23557       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
23558          template friend, or a FIELD_DECL for a capture pack.  */
23559       if (TREE_CODE (decl) != TEMPLATE_DECL)
23560         return NULL_TREE;
23561     }
23562
23563   /* Look for more and more general templates.  */
23564   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
23565     {
23566       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
23567          (See cp-tree.h for details.)  */
23568       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
23569         break;
23570
23571       if (CLASS_TYPE_P (TREE_TYPE (decl))
23572           && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
23573           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
23574         break;
23575
23576       /* Stop if we run into an explicitly specialized class template.  */
23577       if (!DECL_NAMESPACE_SCOPE_P (decl)
23578           && DECL_CONTEXT (decl)
23579           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
23580         break;
23581
23582       decl = DECL_TI_TEMPLATE (decl);
23583     }
23584
23585   return decl;
23586 }
23587
23588 /* Return the most specialized of the template partial specializations
23589    which can produce TARGET, a specialization of some class or variable
23590    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
23591    a TEMPLATE_DECL node corresponding to the partial specialization, while
23592    the TREE_PURPOSE is the set of template arguments that must be
23593    substituted into the template pattern in order to generate TARGET.
23594
23595    If the choice of partial specialization is ambiguous, a diagnostic
23596    is issued, and the error_mark_node is returned.  If there are no
23597    partial specializations matching TARGET, then NULL_TREE is
23598    returned, indicating that the primary template should be used.  */
23599
23600 static tree
23601 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
23602 {
23603   tree list = NULL_TREE;
23604   tree t;
23605   tree champ;
23606   int fate;
23607   bool ambiguous_p;
23608   tree outer_args = NULL_TREE;
23609   tree tmpl, args;
23610
23611   if (TYPE_P (target))
23612     {
23613       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
23614       tmpl = TI_TEMPLATE (tinfo);
23615       args = TI_ARGS (tinfo);
23616     }
23617   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
23618     {
23619       tmpl = TREE_OPERAND (target, 0);
23620       args = TREE_OPERAND (target, 1);
23621     }
23622   else if (VAR_P (target))
23623     {
23624       tree tinfo = DECL_TEMPLATE_INFO (target);
23625       tmpl = TI_TEMPLATE (tinfo);
23626       args = TI_ARGS (tinfo);
23627     }
23628   else
23629     gcc_unreachable ();
23630
23631   tree main_tmpl = most_general_template (tmpl);
23632
23633   /* For determining which partial specialization to use, only the
23634      innermost args are interesting.  */
23635   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
23636     {
23637       outer_args = strip_innermost_template_args (args, 1);
23638       args = INNERMOST_TEMPLATE_ARGS (args);
23639     }
23640
23641   /* The caller hasn't called push_to_top_level yet, but we need
23642      get_partial_spec_bindings to be done in non-template context so that we'll
23643      fully resolve everything.  */
23644   processing_template_decl_sentinel ptds;
23645
23646   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
23647     {
23648       tree spec_args;
23649       tree spec_tmpl = TREE_VALUE (t);
23650
23651       if (outer_args)
23652         {
23653           /* Substitute in the template args from the enclosing class.  */
23654           ++processing_template_decl;
23655           spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
23656           --processing_template_decl;
23657         }
23658
23659       if (spec_tmpl == error_mark_node)
23660         return error_mark_node;
23661
23662       spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
23663       if (spec_args)
23664         {
23665           if (outer_args)
23666             spec_args = add_to_template_args (outer_args, spec_args);
23667
23668           /* Keep the candidate only if the constraints are satisfied,
23669              or if we're not compiling with concepts.  */
23670           if (!flag_concepts
23671               || constraints_satisfied_p (spec_tmpl, spec_args))
23672             {
23673               list = tree_cons (spec_args, TREE_VALUE (t), list);
23674               TREE_TYPE (list) = TREE_TYPE (t);
23675             }
23676         }
23677     }
23678
23679   if (! list)
23680     return NULL_TREE;
23681
23682   ambiguous_p = false;
23683   t = list;
23684   champ = t;
23685   t = TREE_CHAIN (t);
23686   for (; t; t = TREE_CHAIN (t))
23687     {
23688       fate = more_specialized_partial_spec (tmpl, champ, t);
23689       if (fate == 1)
23690         ;
23691       else
23692         {
23693           if (fate == 0)
23694             {
23695               t = TREE_CHAIN (t);
23696               if (! t)
23697                 {
23698                   ambiguous_p = true;
23699                   break;
23700                 }
23701             }
23702           champ = t;
23703         }
23704     }
23705
23706   if (!ambiguous_p)
23707     for (t = list; t && t != champ; t = TREE_CHAIN (t))
23708       {
23709         fate = more_specialized_partial_spec (tmpl, champ, t);
23710         if (fate != 1)
23711           {
23712             ambiguous_p = true;
23713             break;
23714           }
23715       }
23716
23717   if (ambiguous_p)
23718     {
23719       const char *str;
23720       char *spaces = NULL;
23721       if (!(complain & tf_error))
23722         return error_mark_node;
23723       if (TYPE_P (target))
23724         error ("ambiguous template instantiation for %q#T", target);
23725       else
23726         error ("ambiguous template instantiation for %q#D", target);
23727       str = ngettext ("candidate is:", "candidates are:", list_length (list));
23728       for (t = list; t; t = TREE_CHAIN (t))
23729         {
23730           tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
23731           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
23732                   "%s %#qS", spaces ? spaces : str, subst);
23733           spaces = spaces ? spaces : get_spaces (str);
23734         }
23735       free (spaces);
23736       return error_mark_node;
23737     }
23738
23739   return champ;
23740 }
23741
23742 /* Explicitly instantiate DECL.  */
23743
23744 void
23745 do_decl_instantiation (tree decl, tree storage)
23746 {
23747   tree result = NULL_TREE;
23748   int extern_p = 0;
23749
23750   if (!decl || decl == error_mark_node)
23751     /* An error occurred, for which grokdeclarator has already issued
23752        an appropriate message.  */
23753     return;
23754   else if (! DECL_LANG_SPECIFIC (decl))
23755     {
23756       error ("explicit instantiation of non-template %q#D", decl);
23757       return;
23758     }
23759   else if (DECL_DECLARED_CONCEPT_P (decl))
23760     {
23761       if (VAR_P (decl))
23762         error ("explicit instantiation of variable concept %q#D", decl);
23763       else
23764         error ("explicit instantiation of function concept %q#D", decl);
23765       return;
23766     }
23767
23768   bool var_templ = (DECL_TEMPLATE_INFO (decl)
23769                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
23770
23771   if (VAR_P (decl) && !var_templ)
23772     {
23773       /* There is an asymmetry here in the way VAR_DECLs and
23774          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
23775          the latter, the DECL we get back will be marked as a
23776          template instantiation, and the appropriate
23777          DECL_TEMPLATE_INFO will be set up.  This does not happen for
23778          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
23779          should handle VAR_DECLs as it currently handles
23780          FUNCTION_DECLs.  */
23781       if (!DECL_CLASS_SCOPE_P (decl))
23782         {
23783           error ("%qD is not a static data member of a class template", decl);
23784           return;
23785         }
23786       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23787       if (!result || !VAR_P (result))
23788         {
23789           error ("no matching template for %qD found", decl);
23790           return;
23791         }
23792       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23793         {
23794           error ("type %qT for explicit instantiation %qD does not match "
23795                  "declared type %qT", TREE_TYPE (result), decl,
23796                  TREE_TYPE (decl));
23797           return;
23798         }
23799     }
23800   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23801     {
23802       error ("explicit instantiation of %q#D", decl);
23803       return;
23804     }
23805   else
23806     result = decl;
23807
23808   /* Check for various error cases.  Note that if the explicit
23809      instantiation is valid the RESULT will currently be marked as an
23810      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23811      until we get here.  */
23812
23813   if (DECL_TEMPLATE_SPECIALIZATION (result))
23814     {
23815       /* DR 259 [temp.spec].
23816
23817          Both an explicit instantiation and a declaration of an explicit
23818          specialization shall not appear in a program unless the explicit
23819          instantiation follows a declaration of the explicit specialization.
23820
23821          For a given set of template parameters, if an explicit
23822          instantiation of a template appears after a declaration of an
23823          explicit specialization for that template, the explicit
23824          instantiation has no effect.  */
23825       return;
23826     }
23827   else if (DECL_EXPLICIT_INSTANTIATION (result))
23828     {
23829       /* [temp.spec]
23830
23831          No program shall explicitly instantiate any template more
23832          than once.
23833
23834          We check DECL_NOT_REALLY_EXTERN so as not to complain when
23835          the first instantiation was `extern' and the second is not,
23836          and EXTERN_P for the opposite case.  */
23837       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23838         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23839       /* If an "extern" explicit instantiation follows an ordinary
23840          explicit instantiation, the template is instantiated.  */
23841       if (extern_p)
23842         return;
23843     }
23844   else if (!DECL_IMPLICIT_INSTANTIATION (result))
23845     {
23846       error ("no matching template for %qD found", result);
23847       return;
23848     }
23849   else if (!DECL_TEMPLATE_INFO (result))
23850     {
23851       permerror (input_location, "explicit instantiation of non-template %q#D", result);
23852       return;
23853     }
23854
23855   if (storage == NULL_TREE)
23856     ;
23857   else if (storage == ridpointers[(int) RID_EXTERN])
23858     {
23859       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23860         pedwarn (input_location, OPT_Wpedantic,
23861                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23862                  "instantiations");
23863       extern_p = 1;
23864     }
23865   else
23866     error ("storage class %qD applied to template instantiation", storage);
23867
23868   check_explicit_instantiation_namespace (result);
23869   mark_decl_instantiated (result, extern_p);
23870   if (! extern_p)
23871     instantiate_decl (result, /*defer_ok=*/true,
23872                       /*expl_inst_class_mem_p=*/false);
23873 }
23874
23875 static void
23876 mark_class_instantiated (tree t, int extern_p)
23877 {
23878   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23879   SET_CLASSTYPE_INTERFACE_KNOWN (t);
23880   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23881   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23882   if (! extern_p)
23883     {
23884       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23885       rest_of_type_compilation (t, 1);
23886     }
23887 }
23888
23889 /* Called from do_type_instantiation through binding_table_foreach to
23890    do recursive instantiation for the type bound in ENTRY.  */
23891 static void
23892 bt_instantiate_type_proc (binding_entry entry, void *data)
23893 {
23894   tree storage = *(tree *) data;
23895
23896   if (MAYBE_CLASS_TYPE_P (entry->type)
23897       && CLASSTYPE_TEMPLATE_INFO (entry->type)
23898       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23899     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23900 }
23901
23902 /* Perform an explicit instantiation of template class T.  STORAGE, if
23903    non-null, is the RID for extern, inline or static.  COMPLAIN is
23904    nonzero if this is called from the parser, zero if called recursively,
23905    since the standard is unclear (as detailed below).  */
23906
23907 void
23908 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23909 {
23910   int extern_p = 0;
23911   int nomem_p = 0;
23912   int static_p = 0;
23913   int previous_instantiation_extern_p = 0;
23914
23915   if (TREE_CODE (t) == TYPE_DECL)
23916     t = TREE_TYPE (t);
23917
23918   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23919     {
23920       tree tmpl =
23921         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23922       if (tmpl)
23923         error ("explicit instantiation of non-class template %qD", tmpl);
23924       else
23925         error ("explicit instantiation of non-template type %qT", t);
23926       return;
23927     }
23928
23929   complete_type (t);
23930
23931   if (!COMPLETE_TYPE_P (t))
23932     {
23933       if (complain & tf_error)
23934         error ("explicit instantiation of %q#T before definition of template",
23935                t);
23936       return;
23937     }
23938
23939   if (storage != NULL_TREE)
23940     {
23941       if (!in_system_header_at (input_location))
23942         {
23943           if (storage == ridpointers[(int) RID_EXTERN])
23944             {
23945               if (cxx_dialect == cxx98)
23946                 pedwarn (input_location, OPT_Wpedantic,
23947                          "ISO C++ 1998 forbids the use of %<extern%> on "
23948                          "explicit instantiations");
23949             }
23950           else
23951             pedwarn (input_location, OPT_Wpedantic,
23952                      "ISO C++ forbids the use of %qE"
23953                      " on explicit instantiations", storage);
23954         }
23955
23956       if (storage == ridpointers[(int) RID_INLINE])
23957         nomem_p = 1;
23958       else if (storage == ridpointers[(int) RID_EXTERN])
23959         extern_p = 1;
23960       else if (storage == ridpointers[(int) RID_STATIC])
23961         static_p = 1;
23962       else
23963         {
23964           error ("storage class %qD applied to template instantiation",
23965                  storage);
23966           extern_p = 0;
23967         }
23968     }
23969
23970   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23971     {
23972       /* DR 259 [temp.spec].
23973
23974          Both an explicit instantiation and a declaration of an explicit
23975          specialization shall not appear in a program unless the explicit
23976          instantiation follows a declaration of the explicit specialization.
23977
23978          For a given set of template parameters, if an explicit
23979          instantiation of a template appears after a declaration of an
23980          explicit specialization for that template, the explicit
23981          instantiation has no effect.  */
23982       return;
23983     }
23984   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23985     {
23986       /* [temp.spec]
23987
23988          No program shall explicitly instantiate any template more
23989          than once.
23990
23991          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23992          instantiation was `extern'.  If EXTERN_P then the second is.
23993          These cases are OK.  */
23994       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23995
23996       if (!previous_instantiation_extern_p && !extern_p
23997           && (complain & tf_error))
23998         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23999
24000       /* If we've already instantiated the template, just return now.  */
24001       if (!CLASSTYPE_INTERFACE_ONLY (t))
24002         return;
24003     }
24004
24005   check_explicit_instantiation_namespace (TYPE_NAME (t));
24006   mark_class_instantiated (t, extern_p);
24007
24008   if (nomem_p)
24009     return;
24010
24011   /* In contrast to implicit instantiation, where only the
24012      declarations, and not the definitions, of members are
24013      instantiated, we have here:
24014
24015          [temp.explicit]
24016
24017          The explicit instantiation of a class template specialization
24018          implies the instantiation of all of its members not
24019          previously explicitly specialized in the translation unit
24020          containing the explicit instantiation.
24021
24022      Of course, we can't instantiate member template classes, since we
24023      don't have any arguments for them.  Note that the standard is
24024      unclear on whether the instantiation of the members are
24025      *explicit* instantiations or not.  However, the most natural
24026      interpretation is that it should be an explicit
24027      instantiation.  */
24028   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
24029     if ((VAR_P (fld)
24030          || (TREE_CODE (fld) == FUNCTION_DECL
24031              && !static_p
24032              && user_provided_p (fld)))
24033         && DECL_TEMPLATE_INSTANTIATION (fld))
24034       {
24035         mark_decl_instantiated (fld, extern_p);
24036         if (! extern_p)
24037           instantiate_decl (fld, /*defer_ok=*/true,
24038                             /*expl_inst_class_mem_p=*/true);
24039       }
24040
24041   if (CLASSTYPE_NESTED_UTDS (t))
24042     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
24043                            bt_instantiate_type_proc, &storage);
24044 }
24045
24046 /* Given a function DECL, which is a specialization of TMPL, modify
24047    DECL to be a re-instantiation of TMPL with the same template
24048    arguments.  TMPL should be the template into which tsubst'ing
24049    should occur for DECL, not the most general template.
24050
24051    One reason for doing this is a scenario like this:
24052
24053      template <class T>
24054      void f(const T&, int i);
24055
24056      void g() { f(3, 7); }
24057
24058      template <class T>
24059      void f(const T& t, const int i) { }
24060
24061    Note that when the template is first instantiated, with
24062    instantiate_template, the resulting DECL will have no name for the
24063    first parameter, and the wrong type for the second.  So, when we go
24064    to instantiate the DECL, we regenerate it.  */
24065
24066 static void
24067 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
24068 {
24069   /* The arguments used to instantiate DECL, from the most general
24070      template.  */
24071   tree code_pattern;
24072
24073   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
24074
24075   /* Make sure that we can see identifiers, and compute access
24076      correctly.  */
24077   push_access_scope (decl);
24078
24079   if (TREE_CODE (decl) == FUNCTION_DECL)
24080     {
24081       tree decl_parm;
24082       tree pattern_parm;
24083       tree specs;
24084       int args_depth;
24085       int parms_depth;
24086
24087       args_depth = TMPL_ARGS_DEPTH (args);
24088       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
24089       if (args_depth > parms_depth)
24090         args = get_innermost_template_args (args, parms_depth);
24091
24092       /* Instantiate a dynamic exception-specification.  noexcept will be
24093          handled below.  */
24094       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
24095         if (TREE_VALUE (raises))
24096           {
24097             specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
24098                                                     args, tf_error, NULL_TREE,
24099                                                     /*defer_ok*/false);
24100             if (specs && specs != error_mark_node)
24101               TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
24102                                                           specs);
24103           }
24104
24105       /* Merge parameter declarations.  */
24106       decl_parm = skip_artificial_parms_for (decl,
24107                                              DECL_ARGUMENTS (decl));
24108       pattern_parm
24109         = skip_artificial_parms_for (code_pattern,
24110                                      DECL_ARGUMENTS (code_pattern));
24111       while (decl_parm && !DECL_PACK_P (pattern_parm))
24112         {
24113           tree parm_type;
24114           tree attributes;
24115
24116           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
24117             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
24118           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
24119                               NULL_TREE);
24120           parm_type = type_decays_to (parm_type);
24121           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
24122             TREE_TYPE (decl_parm) = parm_type;
24123           attributes = DECL_ATTRIBUTES (pattern_parm);
24124           if (DECL_ATTRIBUTES (decl_parm) != attributes)
24125             {
24126               DECL_ATTRIBUTES (decl_parm) = attributes;
24127               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
24128             }
24129           decl_parm = DECL_CHAIN (decl_parm);
24130           pattern_parm = DECL_CHAIN (pattern_parm);
24131         }
24132       /* Merge any parameters that match with the function parameter
24133          pack.  */
24134       if (pattern_parm && DECL_PACK_P (pattern_parm))
24135         {
24136           int i, len;
24137           tree expanded_types;
24138           /* Expand the TYPE_PACK_EXPANSION that provides the types for
24139              the parameters in this function parameter pack.  */
24140           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
24141                                                  args, tf_error, NULL_TREE);
24142           len = TREE_VEC_LENGTH (expanded_types);
24143           for (i = 0; i < len; i++)
24144             {
24145               tree parm_type;
24146               tree attributes;
24147
24148               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
24149                 /* Rename the parameter to include the index.  */
24150                 DECL_NAME (decl_parm) = 
24151                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
24152               parm_type = TREE_VEC_ELT (expanded_types, i);
24153               parm_type = type_decays_to (parm_type);
24154               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
24155                 TREE_TYPE (decl_parm) = parm_type;
24156               attributes = DECL_ATTRIBUTES (pattern_parm);
24157               if (DECL_ATTRIBUTES (decl_parm) != attributes)
24158                 {
24159                   DECL_ATTRIBUTES (decl_parm) = attributes;
24160                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
24161                 }
24162               decl_parm = DECL_CHAIN (decl_parm);
24163             }
24164         }
24165       /* Merge additional specifiers from the CODE_PATTERN.  */
24166       if (DECL_DECLARED_INLINE_P (code_pattern)
24167           && !DECL_DECLARED_INLINE_P (decl))
24168         DECL_DECLARED_INLINE_P (decl) = 1;
24169
24170       maybe_instantiate_noexcept (decl, tf_error);
24171     }
24172   else if (VAR_P (decl))
24173     {
24174       start_lambda_scope (decl);
24175       DECL_INITIAL (decl) =
24176         tsubst_init (DECL_INITIAL (code_pattern), decl, args,
24177                      tf_error, DECL_TI_TEMPLATE (decl));
24178       finish_lambda_scope ();
24179       if (VAR_HAD_UNKNOWN_BOUND (decl))
24180         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
24181                                    tf_error, DECL_TI_TEMPLATE (decl));
24182     }
24183   else
24184     gcc_unreachable ();
24185
24186   pop_access_scope (decl);
24187 }
24188
24189 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
24190    substituted to get DECL.  */
24191
24192 tree
24193 template_for_substitution (tree decl)
24194 {
24195   tree tmpl = DECL_TI_TEMPLATE (decl);
24196
24197   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
24198      for the instantiation.  This is not always the most general
24199      template.  Consider, for example:
24200
24201         template <class T>
24202         struct S { template <class U> void f();
24203                    template <> void f<int>(); };
24204
24205      and an instantiation of S<double>::f<int>.  We want TD to be the
24206      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
24207   while (/* An instantiation cannot have a definition, so we need a
24208             more general template.  */
24209          DECL_TEMPLATE_INSTANTIATION (tmpl)
24210            /* We must also deal with friend templates.  Given:
24211
24212                 template <class T> struct S {
24213                   template <class U> friend void f() {};
24214                 };
24215
24216               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
24217               so far as the language is concerned, but that's still
24218               where we get the pattern for the instantiation from.  On
24219               other hand, if the definition comes outside the class, say:
24220
24221                 template <class T> struct S {
24222                   template <class U> friend void f();
24223                 };
24224                 template <class U> friend void f() {}
24225
24226               we don't need to look any further.  That's what the check for
24227               DECL_INITIAL is for.  */
24228           || (TREE_CODE (decl) == FUNCTION_DECL
24229               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
24230               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
24231     {
24232       /* The present template, TD, should not be a definition.  If it
24233          were a definition, we should be using it!  Note that we
24234          cannot restructure the loop to just keep going until we find
24235          a template with a definition, since that might go too far if
24236          a specialization was declared, but not defined.  */
24237
24238       /* Fetch the more general template.  */
24239       tmpl = DECL_TI_TEMPLATE (tmpl);
24240     }
24241
24242   return tmpl;
24243 }
24244
24245 /* Returns true if we need to instantiate this template instance even if we
24246    know we aren't going to emit it.  */
24247
24248 bool
24249 always_instantiate_p (tree decl)
24250 {
24251   /* We always instantiate inline functions so that we can inline them.  An
24252      explicit instantiation declaration prohibits implicit instantiation of
24253      non-inline functions.  With high levels of optimization, we would
24254      normally inline non-inline functions -- but we're not allowed to do
24255      that for "extern template" functions.  Therefore, we check
24256      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
24257   return ((TREE_CODE (decl) == FUNCTION_DECL
24258            && (DECL_DECLARED_INLINE_P (decl)
24259                || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
24260           /* And we need to instantiate static data members so that
24261              their initializers are available in integral constant
24262              expressions.  */
24263           || (VAR_P (decl)
24264               && decl_maybe_constant_var_p (decl)));
24265 }
24266
24267 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
24268    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
24269    error, true otherwise.  */
24270
24271 bool
24272 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
24273 {
24274   tree fntype, spec, noex, clone;
24275
24276   /* Don't instantiate a noexcept-specification from template context.  */
24277   if (processing_template_decl
24278       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
24279     return true;
24280
24281   if (DECL_CLONED_FUNCTION_P (fn))
24282     fn = DECL_CLONED_FUNCTION (fn);
24283
24284   tree orig_fn = NULL_TREE;
24285   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
24286      its FUNCTION_DECL for the rest of this function -- push_access_scope
24287      doesn't accept TEMPLATE_DECLs.  */
24288   if (DECL_FUNCTION_TEMPLATE_P (fn))
24289     {
24290       orig_fn = fn;
24291       fn = DECL_TEMPLATE_RESULT (fn);
24292     }
24293
24294   fntype = TREE_TYPE (fn);
24295   spec = TYPE_RAISES_EXCEPTIONS (fntype);
24296
24297   if (!spec || !TREE_PURPOSE (spec))
24298     return true;
24299
24300   noex = TREE_PURPOSE (spec);
24301
24302   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
24303     {
24304       static hash_set<tree>* fns = new hash_set<tree>;
24305       bool added = false;
24306       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
24307         {
24308           spec = get_defaulted_eh_spec (fn, complain);
24309           if (spec == error_mark_node)
24310             /* This might have failed because of an unparsed DMI, so
24311                let's try again later.  */
24312             return false;
24313         }
24314       else if (!(added = !fns->add (fn)))
24315         {
24316           /* If hash_set::add returns true, the element was already there.  */
24317           location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
24318                                             DECL_SOURCE_LOCATION (fn));
24319           error_at (loc,
24320                     "exception specification of %qD depends on itself",
24321                     fn);
24322           spec = noexcept_false_spec;
24323         }
24324       else if (push_tinst_level (fn))
24325         {
24326           push_to_top_level ();
24327           push_access_scope (fn);
24328           push_deferring_access_checks (dk_no_deferred);
24329           input_location = DECL_SOURCE_LOCATION (fn);
24330
24331           /* If needed, set current_class_ptr for the benefit of
24332              tsubst_copy/PARM_DECL.  */
24333           tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
24334           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
24335             {
24336               tree this_parm = DECL_ARGUMENTS (tdecl);
24337               current_class_ptr = NULL_TREE;
24338               current_class_ref = cp_build_fold_indirect_ref (this_parm);
24339               current_class_ptr = this_parm;
24340             }
24341
24342           /* If this function is represented by a TEMPLATE_DECL, then
24343              the deferred noexcept-specification might still contain
24344              dependent types, even after substitution.  And we need the
24345              dependency check functions to work in build_noexcept_spec.  */
24346           if (orig_fn)
24347             ++processing_template_decl;
24348
24349           /* Do deferred instantiation of the noexcept-specifier.  */
24350           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
24351                                         DEFERRED_NOEXCEPT_ARGS (noex),
24352                                         tf_warning_or_error, fn,
24353                                         /*function_p=*/false,
24354                                         /*i_c_e_p=*/true);
24355
24356           /* Build up the noexcept-specification.  */
24357           spec = build_noexcept_spec (noex, tf_warning_or_error);
24358
24359           if (orig_fn)
24360             --processing_template_decl;
24361
24362           pop_deferring_access_checks ();
24363           pop_access_scope (fn);
24364           pop_tinst_level ();
24365           pop_from_top_level ();
24366         }
24367       else
24368         spec = noexcept_false_spec;
24369
24370       if (added)
24371         fns->remove (fn);
24372
24373       if (spec == error_mark_node)
24374         {
24375           /* This failed with a hard error, so let's go with false.  */
24376           gcc_assert (seen_error ());
24377           spec = noexcept_false_spec;
24378         }
24379
24380       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
24381       if (orig_fn)
24382         TREE_TYPE (orig_fn) = TREE_TYPE (fn);
24383     }
24384
24385   FOR_EACH_CLONE (clone, fn)
24386     {
24387       if (TREE_TYPE (clone) == fntype)
24388         TREE_TYPE (clone) = TREE_TYPE (fn);
24389       else
24390         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
24391     }
24392
24393   return true;
24394 }
24395
24396 /* We're starting to process the function INST, an instantiation of PATTERN;
24397    add their parameters to local_specializations.  */
24398
24399 static void
24400 register_parameter_specializations (tree pattern, tree inst)
24401 {
24402   tree tmpl_parm = DECL_ARGUMENTS (pattern);
24403   tree spec_parm = DECL_ARGUMENTS (inst);
24404   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
24405     {
24406       register_local_specialization (spec_parm, tmpl_parm);
24407       spec_parm = skip_artificial_parms_for (inst, spec_parm);
24408       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
24409     }
24410   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
24411     {
24412       if (!DECL_PACK_P (tmpl_parm))
24413         {
24414           register_local_specialization (spec_parm, tmpl_parm);
24415           spec_parm = DECL_CHAIN (spec_parm);
24416         }
24417       else
24418         {
24419           /* Register the (value) argument pack as a specialization of
24420              TMPL_PARM, then move on.  */
24421           tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
24422           register_local_specialization (argpack, tmpl_parm);
24423         }
24424     }
24425   gcc_assert (!spec_parm);
24426 }
24427
24428 /* Produce the definition of D, a _DECL generated from a template.  If
24429    DEFER_OK is true, then we don't have to actually do the
24430    instantiation now; we just have to do it sometime.  Normally it is
24431    an error if this is an explicit instantiation but D is undefined.
24432    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
24433    instantiated class template.  */
24434
24435 tree
24436 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
24437 {
24438   tree tmpl = DECL_TI_TEMPLATE (d);
24439   tree gen_args;
24440   tree args;
24441   tree td;
24442   tree code_pattern;
24443   tree spec;
24444   tree gen_tmpl;
24445   bool pattern_defined;
24446   location_t saved_loc = input_location;
24447   int saved_unevaluated_operand = cp_unevaluated_operand;
24448   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
24449   bool external_p;
24450   bool deleted_p;
24451
24452   /* This function should only be used to instantiate templates for
24453      functions and static member variables.  */
24454   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
24455
24456   /* A concept is never instantiated. */
24457   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
24458
24459   /* Variables are never deferred; if instantiation is required, they
24460      are instantiated right away.  That allows for better code in the
24461      case that an expression refers to the value of the variable --
24462      if the variable has a constant value the referring expression can
24463      take advantage of that fact.  */
24464   if (VAR_P (d))
24465     defer_ok = false;
24466
24467   /* Don't instantiate cloned functions.  Instead, instantiate the
24468      functions they cloned.  */
24469   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
24470     d = DECL_CLONED_FUNCTION (d);
24471
24472   if (DECL_TEMPLATE_INSTANTIATED (d)
24473       || (TREE_CODE (d) == FUNCTION_DECL
24474           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
24475       || DECL_TEMPLATE_SPECIALIZATION (d))
24476     /* D has already been instantiated or explicitly specialized, so
24477        there's nothing for us to do here.
24478
24479        It might seem reasonable to check whether or not D is an explicit
24480        instantiation, and, if so, stop here.  But when an explicit
24481        instantiation is deferred until the end of the compilation,
24482        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
24483        the instantiation.  */
24484     return d;
24485
24486   /* Check to see whether we know that this template will be
24487      instantiated in some other file, as with "extern template"
24488      extension.  */
24489   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
24490
24491   /* In general, we do not instantiate such templates.  */
24492   if (external_p && !always_instantiate_p (d))
24493     return d;
24494
24495   gen_tmpl = most_general_template (tmpl);
24496   gen_args = DECL_TI_ARGS (d);
24497
24498   if (tmpl != gen_tmpl)
24499     /* We should already have the extra args.  */
24500     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
24501                 == TMPL_ARGS_DEPTH (gen_args));
24502   /* And what's in the hash table should match D.  */
24503   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
24504               || spec == NULL_TREE);
24505
24506   /* This needs to happen before any tsubsting.  */
24507   if (! push_tinst_level (d))
24508     return d;
24509
24510   timevar_push (TV_TEMPLATE_INST);
24511
24512   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
24513      for the instantiation.  */
24514   td = template_for_substitution (d);
24515   args = gen_args;
24516
24517   if (VAR_P (d))
24518     {
24519       /* Look up an explicit specialization, if any.  */
24520       tree tid = lookup_template_variable (gen_tmpl, gen_args);
24521       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
24522       if (elt && elt != error_mark_node)
24523         {
24524           td = TREE_VALUE (elt);
24525           args = TREE_PURPOSE (elt);
24526         }
24527     }
24528
24529   code_pattern = DECL_TEMPLATE_RESULT (td);
24530
24531   /* We should never be trying to instantiate a member of a class
24532      template or partial specialization.  */
24533   gcc_assert (d != code_pattern);
24534
24535   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
24536       || DECL_TEMPLATE_SPECIALIZATION (td))
24537     /* In the case of a friend template whose definition is provided
24538        outside the class, we may have too many arguments.  Drop the
24539        ones we don't need.  The same is true for specializations.  */
24540     args = get_innermost_template_args
24541       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
24542
24543   if (TREE_CODE (d) == FUNCTION_DECL)
24544     {
24545       deleted_p = DECL_DELETED_FN (code_pattern);
24546       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
24547                           && DECL_INITIAL (code_pattern) != error_mark_node)
24548                          || DECL_DEFAULTED_FN (code_pattern)
24549                          || deleted_p);
24550     }
24551   else
24552     {
24553       deleted_p = false;
24554       if (DECL_CLASS_SCOPE_P (code_pattern))
24555         pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
24556       else
24557         pattern_defined = ! DECL_EXTERNAL (code_pattern);
24558     }
24559
24560   /* We may be in the middle of deferred access check.  Disable it now.  */
24561   push_deferring_access_checks (dk_no_deferred);
24562
24563   /* Unless an explicit instantiation directive has already determined
24564      the linkage of D, remember that a definition is available for
24565      this entity.  */
24566   if (pattern_defined
24567       && !DECL_INTERFACE_KNOWN (d)
24568       && !DECL_NOT_REALLY_EXTERN (d))
24569     mark_definable (d);
24570
24571   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
24572   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
24573   input_location = DECL_SOURCE_LOCATION (d);
24574
24575   /* If D is a member of an explicitly instantiated class template,
24576      and no definition is available, treat it like an implicit
24577      instantiation.  */
24578   if (!pattern_defined && expl_inst_class_mem_p
24579       && DECL_EXPLICIT_INSTANTIATION (d))
24580     {
24581       /* Leave linkage flags alone on instantiations with anonymous
24582          visibility.  */
24583       if (TREE_PUBLIC (d))
24584         {
24585           DECL_NOT_REALLY_EXTERN (d) = 0;
24586           DECL_INTERFACE_KNOWN (d) = 0;
24587         }
24588       SET_DECL_IMPLICIT_INSTANTIATION (d);
24589     }
24590
24591   /* Defer all other templates, unless we have been explicitly
24592      forbidden from doing so.  */
24593   if (/* If there is no definition, we cannot instantiate the
24594          template.  */
24595       ! pattern_defined
24596       /* If it's OK to postpone instantiation, do so.  */
24597       || defer_ok
24598       /* If this is a static data member that will be defined
24599          elsewhere, we don't want to instantiate the entire data
24600          member, but we do want to instantiate the initializer so that
24601          we can substitute that elsewhere.  */
24602       || (external_p && VAR_P (d))
24603       /* Handle here a deleted function too, avoid generating
24604          its body (c++/61080).  */
24605       || deleted_p)
24606     {
24607       /* The definition of the static data member is now required so
24608          we must substitute the initializer.  */
24609       if (VAR_P (d)
24610           && !DECL_INITIAL (d)
24611           && DECL_INITIAL (code_pattern))
24612         {
24613           tree ns;
24614           tree init;
24615           bool const_init = false;
24616           bool enter_context = DECL_CLASS_SCOPE_P (d);
24617
24618           ns = decl_namespace_context (d);
24619           push_nested_namespace (ns);
24620           if (enter_context)
24621             push_nested_class (DECL_CONTEXT (d));
24622           init = tsubst_expr (DECL_INITIAL (code_pattern),
24623                               args,
24624                               tf_warning_or_error, NULL_TREE,
24625                               /*integral_constant_expression_p=*/false);
24626           /* If instantiating the initializer involved instantiating this
24627              again, don't call cp_finish_decl twice.  */
24628           if (!DECL_INITIAL (d))
24629             {
24630               /* Make sure the initializer is still constant, in case of
24631                  circular dependency (template/instantiate6.C). */
24632               const_init
24633                 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24634               cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
24635                               /*asmspec_tree=*/NULL_TREE,
24636                               LOOKUP_ONLYCONVERTING);
24637             }
24638           if (enter_context)
24639             pop_nested_class ();
24640           pop_nested_namespace (ns);
24641         }
24642
24643       /* We restore the source position here because it's used by
24644          add_pending_template.  */
24645       input_location = saved_loc;
24646
24647       if (at_eof && !pattern_defined
24648           && DECL_EXPLICIT_INSTANTIATION (d)
24649           && DECL_NOT_REALLY_EXTERN (d))
24650         /* [temp.explicit]
24651
24652            The definition of a non-exported function template, a
24653            non-exported member function template, or a non-exported
24654            member function or static data member of a class template
24655            shall be present in every translation unit in which it is
24656            explicitly instantiated.  */
24657         permerror (input_location,  "explicit instantiation of %qD "
24658                    "but no definition available", d);
24659
24660       /* If we're in unevaluated context, we just wanted to get the
24661          constant value; this isn't an odr use, so don't queue
24662          a full instantiation.  */
24663       if (cp_unevaluated_operand != 0)
24664         goto out;
24665       /* ??? Historically, we have instantiated inline functions, even
24666          when marked as "extern template".  */
24667       if (!(external_p && VAR_P (d)))
24668         add_pending_template (d);
24669       goto out;
24670     }
24671   /* Tell the repository that D is available in this translation unit
24672      -- and see if it is supposed to be instantiated here.  */
24673   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
24674     {
24675       /* In a PCH file, despite the fact that the repository hasn't
24676          requested instantiation in the PCH it is still possible that
24677          an instantiation will be required in a file that includes the
24678          PCH.  */
24679       if (pch_file)
24680         add_pending_template (d);
24681       /* Instantiate inline functions so that the inliner can do its
24682          job, even though we'll not be emitting a copy of this
24683          function.  */
24684       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
24685         goto out;
24686     }
24687
24688   bool push_to_top, nested;
24689   tree fn_context;
24690   fn_context = decl_function_context (d);
24691   if (LAMBDA_FUNCTION_P (d))
24692     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
24693     fn_context = NULL_TREE;
24694   nested = current_function_decl != NULL_TREE;
24695   push_to_top = !(nested && fn_context == current_function_decl);
24696
24697   vec<tree> omp_privatization_save;
24698   if (nested)
24699     save_omp_privatization_clauses (omp_privatization_save);
24700
24701   if (push_to_top)
24702     push_to_top_level ();
24703   else
24704     {
24705       gcc_assert (!processing_template_decl);
24706       push_function_context ();
24707       cp_unevaluated_operand = 0;
24708       c_inhibit_evaluation_warnings = 0;
24709     }
24710
24711   /* Mark D as instantiated so that recursive calls to
24712      instantiate_decl do not try to instantiate it again.  */
24713   DECL_TEMPLATE_INSTANTIATED (d) = 1;
24714
24715   /* Regenerate the declaration in case the template has been modified
24716      by a subsequent redeclaration.  */
24717   regenerate_decl_from_template (d, td, args);
24718
24719   /* We already set the file and line above.  Reset them now in case
24720      they changed as a result of calling regenerate_decl_from_template.  */
24721   input_location = DECL_SOURCE_LOCATION (d);
24722
24723   if (VAR_P (d))
24724     {
24725       tree init;
24726       bool const_init = false;
24727
24728       /* Clear out DECL_RTL; whatever was there before may not be right
24729          since we've reset the type of the declaration.  */
24730       SET_DECL_RTL (d, NULL);
24731       DECL_IN_AGGR_P (d) = 0;
24732
24733       /* The initializer is placed in DECL_INITIAL by
24734          regenerate_decl_from_template so we don't need to
24735          push/pop_access_scope again here.  Pull it out so that
24736          cp_finish_decl can process it.  */
24737       init = DECL_INITIAL (d);
24738       DECL_INITIAL (d) = NULL_TREE;
24739       DECL_INITIALIZED_P (d) = 0;
24740
24741       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
24742          initializer.  That function will defer actual emission until
24743          we have a chance to determine linkage.  */
24744       DECL_EXTERNAL (d) = 0;
24745
24746       /* Enter the scope of D so that access-checking works correctly.  */
24747       bool enter_context = DECL_CLASS_SCOPE_P (d);
24748       if (enter_context)
24749         push_nested_class (DECL_CONTEXT (d));
24750
24751       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24752       int flags = (TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (d))
24753                    ? LOOKUP_CONSTINIT : 0);
24754       cp_finish_decl (d, init, const_init, NULL_TREE, flags);
24755
24756       if (enter_context)
24757         pop_nested_class ();
24758
24759       if (variable_template_p (gen_tmpl))
24760         note_variable_template_instantiation (d);
24761     }
24762   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
24763     synthesize_method (d);
24764   else if (TREE_CODE (d) == FUNCTION_DECL)
24765     {
24766       /* Set up the list of local specializations.  */
24767       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
24768       tree block = NULL_TREE;
24769
24770       /* Set up context.  */
24771       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24772           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24773         block = push_stmt_list ();
24774       else
24775         start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
24776
24777       /* Some typedefs referenced from within the template code need to be
24778          access checked at template instantiation time, i.e now. These
24779          types were added to the template at parsing time. Let's get those
24780          and perform the access checks then.  */
24781       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
24782                                      args);
24783
24784       /* Create substitution entries for the parameters.  */
24785       register_parameter_specializations (code_pattern, d);
24786
24787       /* Substitute into the body of the function.  */
24788       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24789         tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
24790                         tf_warning_or_error, tmpl);
24791       else
24792         {
24793           tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
24794                        tf_warning_or_error, tmpl,
24795                        /*integral_constant_expression_p=*/false);
24796
24797           /* Set the current input_location to the end of the function
24798              so that finish_function knows where we are.  */
24799           input_location
24800             = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
24801
24802           /* Remember if we saw an infinite loop in the template.  */
24803           current_function_infinite_loop
24804             = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
24805         }
24806
24807       /* Finish the function.  */
24808       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24809           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24810         DECL_SAVED_TREE (d) = pop_stmt_list (block);
24811       else
24812         {
24813           d = finish_function (/*inline_p=*/false);
24814           expand_or_defer_fn (d);
24815         }
24816
24817       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24818         cp_check_omp_declare_reduction (d);
24819     }
24820
24821   /* We're not deferring instantiation any more.  */
24822   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24823
24824   if (push_to_top)
24825     pop_from_top_level ();
24826   else
24827     pop_function_context ();
24828
24829   if (nested)
24830     restore_omp_privatization_clauses (omp_privatization_save);
24831
24832 out:
24833   pop_deferring_access_checks ();
24834   timevar_pop (TV_TEMPLATE_INST);
24835   pop_tinst_level ();
24836   input_location = saved_loc;
24837   cp_unevaluated_operand = saved_unevaluated_operand;
24838   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24839
24840   return d;
24841 }
24842
24843 /* Run through the list of templates that we wish we could
24844    instantiate, and instantiate any we can.  RETRIES is the
24845    number of times we retry pending template instantiation.  */
24846
24847 void
24848 instantiate_pending_templates (int retries)
24849 {
24850   int reconsider;
24851   location_t saved_loc = input_location;
24852
24853   /* Instantiating templates may trigger vtable generation.  This in turn
24854      may require further template instantiations.  We place a limit here
24855      to avoid infinite loop.  */
24856   if (pending_templates && retries >= max_tinst_depth)
24857     {
24858       tree decl = pending_templates->tinst->maybe_get_node ();
24859
24860       fatal_error (input_location,
24861                    "template instantiation depth exceeds maximum of %d"
24862                    " instantiating %q+D, possibly from virtual table generation"
24863                    " (use %<-ftemplate-depth=%> to increase the maximum)",
24864                    max_tinst_depth, decl);
24865       if (TREE_CODE (decl) == FUNCTION_DECL)
24866         /* Pretend that we defined it.  */
24867         DECL_INITIAL (decl) = error_mark_node;
24868       return;
24869     }
24870
24871   do
24872     {
24873       struct pending_template **t = &pending_templates;
24874       struct pending_template *last = NULL;
24875       reconsider = 0;
24876       while (*t)
24877         {
24878           tree instantiation = reopen_tinst_level ((*t)->tinst);
24879           bool complete = false;
24880
24881           if (TYPE_P (instantiation))
24882             {
24883               if (!COMPLETE_TYPE_P (instantiation))
24884                 {
24885                   instantiate_class_template (instantiation);
24886                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24887                     for (tree fld = TYPE_FIELDS (instantiation);
24888                          fld; fld = TREE_CHAIN (fld))
24889                       if ((VAR_P (fld)
24890                            || (TREE_CODE (fld) == FUNCTION_DECL
24891                                && !DECL_ARTIFICIAL (fld)))
24892                           && DECL_TEMPLATE_INSTANTIATION (fld))
24893                         instantiate_decl (fld,
24894                                           /*defer_ok=*/false,
24895                                           /*expl_inst_class_mem_p=*/false);
24896
24897                   if (COMPLETE_TYPE_P (instantiation))
24898                     reconsider = 1;
24899                 }
24900
24901               complete = COMPLETE_TYPE_P (instantiation);
24902             }
24903           else
24904             {
24905               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24906                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24907                 {
24908                   instantiation
24909                     = instantiate_decl (instantiation,
24910                                         /*defer_ok=*/false,
24911                                         /*expl_inst_class_mem_p=*/false);
24912                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24913                     reconsider = 1;
24914                 }
24915
24916               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24917                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
24918             }
24919
24920           if (complete)
24921             {
24922               /* If INSTANTIATION has been instantiated, then we don't
24923                  need to consider it again in the future.  */
24924               struct pending_template *drop = *t;
24925               *t = (*t)->next;
24926               set_refcount_ptr (drop->tinst);
24927               pending_template_freelist ().free (drop);
24928             }
24929           else
24930             {
24931               last = *t;
24932               t = &(*t)->next;
24933             }
24934           tinst_depth = 0;
24935           set_refcount_ptr (current_tinst_level);
24936         }
24937       last_pending_template = last;
24938     }
24939   while (reconsider);
24940
24941   input_location = saved_loc;
24942 }
24943
24944 /* Substitute ARGVEC into T, which is a list of initializers for
24945    either base class or a non-static data member.  The TREE_PURPOSEs
24946    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
24947    instantiate_decl.  */
24948
24949 static tree
24950 tsubst_initializer_list (tree t, tree argvec)
24951 {
24952   tree inits = NULL_TREE;
24953   tree target_ctor = error_mark_node;
24954
24955   for (; t; t = TREE_CHAIN (t))
24956     {
24957       tree decl;
24958       tree init;
24959       tree expanded_bases = NULL_TREE;
24960       tree expanded_arguments = NULL_TREE;
24961       int i, len = 1;
24962
24963       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24964         {
24965           tree expr;
24966           tree arg;
24967
24968           /* Expand the base class expansion type into separate base
24969              classes.  */
24970           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24971                                                  tf_warning_or_error,
24972                                                  NULL_TREE);
24973           if (expanded_bases == error_mark_node)
24974             continue;
24975
24976           /* We'll be building separate TREE_LISTs of arguments for
24977              each base.  */
24978           len = TREE_VEC_LENGTH (expanded_bases);
24979           expanded_arguments = make_tree_vec (len);
24980           for (i = 0; i < len; i++)
24981             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24982
24983           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24984              expand each argument in the TREE_VALUE of t.  */
24985           expr = make_node (EXPR_PACK_EXPANSION);
24986           PACK_EXPANSION_LOCAL_P (expr) = true;
24987           PACK_EXPANSION_PARAMETER_PACKS (expr) =
24988             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24989
24990           if (TREE_VALUE (t) == void_type_node)
24991             /* VOID_TYPE_NODE is used to indicate
24992                value-initialization.  */
24993             {
24994               for (i = 0; i < len; i++)
24995                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24996             }
24997           else
24998             {
24999               /* Substitute parameter packs into each argument in the
25000                  TREE_LIST.  */
25001               in_base_initializer = 1;
25002               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
25003                 {
25004                   tree expanded_exprs;
25005
25006                   /* Expand the argument.  */
25007                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
25008                   expanded_exprs
25009                     = tsubst_pack_expansion (expr, argvec,
25010                                              tf_warning_or_error,
25011                                              NULL_TREE);
25012                   if (expanded_exprs == error_mark_node)
25013                     continue;
25014
25015                   /* Prepend each of the expanded expressions to the
25016                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
25017                   for (i = 0; i < len; i++)
25018                     {
25019                       TREE_VEC_ELT (expanded_arguments, i) =
25020                         tree_cons (NULL_TREE,
25021                                    TREE_VEC_ELT (expanded_exprs, i),
25022                                    TREE_VEC_ELT (expanded_arguments, i));
25023                     }
25024                 }
25025               in_base_initializer = 0;
25026
25027               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
25028                  since we built them backwards.  */
25029               for (i = 0; i < len; i++)
25030                 {
25031                   TREE_VEC_ELT (expanded_arguments, i) =
25032                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
25033                 }
25034             }
25035         }
25036
25037       for (i = 0; i < len; ++i)
25038         {
25039           if (expanded_bases)
25040             {
25041               decl = TREE_VEC_ELT (expanded_bases, i);
25042               decl = expand_member_init (decl);
25043               init = TREE_VEC_ELT (expanded_arguments, i);
25044             }
25045           else
25046             {
25047               tree tmp;
25048               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
25049                                   tf_warning_or_error, NULL_TREE);
25050
25051               decl = expand_member_init (decl);
25052               if (decl && !DECL_P (decl))
25053                 in_base_initializer = 1;
25054
25055               init = TREE_VALUE (t);
25056               tmp = init;
25057               if (init != void_type_node)
25058                 init = tsubst_expr (init, argvec,
25059                                     tf_warning_or_error, NULL_TREE,
25060                                     /*integral_constant_expression_p=*/false);
25061               if (init == NULL_TREE && tmp != NULL_TREE)
25062                 /* If we had an initializer but it instantiated to nothing,
25063                    value-initialize the object.  This will only occur when
25064                    the initializer was a pack expansion where the parameter
25065                    packs used in that expansion were of length zero.  */
25066                 init = void_type_node;
25067               in_base_initializer = 0;
25068             }
25069
25070           if (target_ctor != error_mark_node
25071               && init != error_mark_node)
25072             {
25073               error ("mem-initializer for %qD follows constructor delegation",
25074                      decl);
25075               return inits;
25076             }
25077           /* Look for a target constructor. */
25078           if (init != error_mark_node
25079               && decl && CLASS_TYPE_P (decl)
25080               && same_type_p (decl, current_class_type))
25081             {
25082               maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
25083               if (inits)
25084                 {
25085                   error ("constructor delegation follows mem-initializer for %qD",
25086                          TREE_PURPOSE (inits));
25087                   continue;
25088                 }
25089               target_ctor = init;
25090             }
25091
25092           if (decl)
25093             {
25094               init = build_tree_list (decl, init);
25095               TREE_CHAIN (init) = inits;
25096               inits = init;
25097             }
25098         }
25099     }
25100   return inits;
25101 }
25102
25103 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
25104
25105 static void
25106 set_current_access_from_decl (tree decl)
25107 {
25108   if (TREE_PRIVATE (decl))
25109     current_access_specifier = access_private_node;
25110   else if (TREE_PROTECTED (decl))
25111     current_access_specifier = access_protected_node;
25112   else
25113     current_access_specifier = access_public_node;
25114 }
25115
25116 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
25117    is the instantiation (which should have been created with
25118    start_enum) and ARGS are the template arguments to use.  */
25119
25120 static void
25121 tsubst_enum (tree tag, tree newtag, tree args)
25122 {
25123   tree e;
25124
25125   if (SCOPED_ENUM_P (newtag))
25126     begin_scope (sk_scoped_enum, newtag);
25127
25128   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
25129     {
25130       tree value;
25131       tree decl;
25132
25133       decl = TREE_VALUE (e);
25134       /* Note that in a template enum, the TREE_VALUE is the
25135          CONST_DECL, not the corresponding INTEGER_CST.  */
25136       value = tsubst_expr (DECL_INITIAL (decl),
25137                            args, tf_warning_or_error, NULL_TREE,
25138                            /*integral_constant_expression_p=*/true);
25139
25140       /* Give this enumeration constant the correct access.  */
25141       set_current_access_from_decl (decl);
25142
25143       /* Actually build the enumerator itself.  Here we're assuming that
25144          enumerators can't have dependent attributes.  */
25145       build_enumerator (DECL_NAME (decl), value, newtag,
25146                         DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
25147     }
25148
25149   if (SCOPED_ENUM_P (newtag))
25150     finish_scope ();
25151
25152   finish_enum_value_list (newtag);
25153   finish_enum (newtag);
25154
25155   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
25156     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
25157 }
25158
25159 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
25160    its type -- but without substituting the innermost set of template
25161    arguments.  So, innermost set of template parameters will appear in
25162    the type.  */
25163
25164 tree
25165 get_mostly_instantiated_function_type (tree decl)
25166 {
25167   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
25168   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
25169 }
25170
25171 /* Return truthvalue if we're processing a template different from
25172    the last one involved in diagnostics.  */
25173 bool
25174 problematic_instantiation_changed (void)
25175 {
25176   return current_tinst_level != last_error_tinst_level;
25177 }
25178
25179 /* Remember current template involved in diagnostics.  */
25180 void
25181 record_last_problematic_instantiation (void)
25182 {
25183   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
25184 }
25185
25186 struct tinst_level *
25187 current_instantiation (void)
25188 {
25189   return current_tinst_level;
25190 }
25191
25192 /* Return TRUE if current_function_decl is being instantiated, false
25193    otherwise.  */
25194
25195 bool
25196 instantiating_current_function_p (void)
25197 {
25198   return (current_instantiation ()
25199           && (current_instantiation ()->maybe_get_node ()
25200               == current_function_decl));
25201 }
25202
25203 /* [temp.param] Check that template non-type parm TYPE is of an allowable
25204    type.  Return false for ok, true for disallowed.  Issue error and
25205    inform messages under control of COMPLAIN.  */
25206
25207 static bool
25208 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
25209 {
25210   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
25211     return false;
25212   else if (TYPE_PTR_P (type))
25213     return false;
25214   else if (TYPE_REF_P (type)
25215            && !TYPE_REF_IS_RVALUE (type))
25216     return false;
25217   else if (TYPE_PTRMEM_P (type))
25218     return false;
25219   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
25220     return false;
25221   else if (TREE_CODE (type) == TYPENAME_TYPE)
25222     return false;
25223   else if (TREE_CODE (type) == DECLTYPE_TYPE)
25224     return false;
25225   else if (TREE_CODE (type) == NULLPTR_TYPE)
25226     return false;
25227   /* A bound template template parm could later be instantiated to have a valid
25228      nontype parm type via an alias template.  */
25229   else if (cxx_dialect >= cxx11
25230            && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
25231     return false;
25232   else if (CLASS_TYPE_P (type))
25233     {
25234       if (cxx_dialect < cxx2a)
25235         {
25236           error ("non-type template parameters of class type only available "
25237                  "with %<-std=c++2a%> or %<-std=gnu++2a%>");
25238           return true;
25239         }
25240       if (dependent_type_p (type))
25241         return false;
25242       if (!complete_type_or_else (type, NULL_TREE))
25243         return true;
25244       if (!literal_type_p (type))
25245         {
25246           error ("%qT is not a valid type for a template non-type parameter "
25247                  "because it is not literal", type);
25248           explain_non_literal_class (type);
25249           return true;
25250         }
25251       if (cp_has_mutable_p (type))
25252         {
25253           error ("%qT is not a valid type for a template non-type parameter "
25254                  "because it has a mutable member", type);
25255           return true;
25256         }
25257       /* FIXME check op<=> and strong structural equality once spaceship is
25258          implemented.  */
25259       return false;
25260     }
25261
25262   if (complain & tf_error)
25263     {
25264       if (type == error_mark_node)
25265         inform (input_location, "invalid template non-type parameter");
25266       else
25267         error ("%q#T is not a valid type for a template non-type parameter",
25268                type);
25269     }
25270   return true;
25271 }
25272
25273 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
25274    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
25275
25276 static bool
25277 dependent_type_p_r (tree type)
25278 {
25279   tree scope;
25280
25281   /* [temp.dep.type]
25282
25283      A type is dependent if it is:
25284
25285      -- a template parameter. Template template parameters are types
25286         for us (since TYPE_P holds true for them) so we handle
25287         them here.  */
25288   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
25289       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
25290     return true;
25291   /* -- a qualified-id with a nested-name-specifier which contains a
25292         class-name that names a dependent type or whose unqualified-id
25293         names a dependent type.  */
25294   if (TREE_CODE (type) == TYPENAME_TYPE)
25295     return true;
25296
25297   /* An alias template specialization can be dependent even if the
25298      resulting type is not.  */
25299   if (dependent_alias_template_spec_p (type))
25300     return true;
25301
25302   /* -- a cv-qualified type where the cv-unqualified type is
25303         dependent.
25304      No code is necessary for this bullet; the code below handles
25305      cv-qualified types, and we don't want to strip aliases with
25306      TYPE_MAIN_VARIANT because of DR 1558.  */
25307   /* -- a compound type constructed from any dependent type.  */
25308   if (TYPE_PTRMEM_P (type))
25309     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
25310             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
25311                                            (type)));
25312   else if (INDIRECT_TYPE_P (type))
25313     return dependent_type_p (TREE_TYPE (type));
25314   else if (FUNC_OR_METHOD_TYPE_P (type))
25315     {
25316       tree arg_type;
25317
25318       if (dependent_type_p (TREE_TYPE (type)))
25319         return true;
25320       for (arg_type = TYPE_ARG_TYPES (type);
25321            arg_type;
25322            arg_type = TREE_CHAIN (arg_type))
25323         if (dependent_type_p (TREE_VALUE (arg_type)))
25324           return true;
25325       if (cxx_dialect >= cxx17)
25326         /* A value-dependent noexcept-specifier makes the type dependent.  */
25327         if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
25328           if (tree noex = TREE_PURPOSE (spec))
25329             /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
25330                affect overload resolution and treating it as dependent breaks
25331                things.  Same for an unparsed noexcept expression.  */
25332             if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
25333                 && TREE_CODE (noex) != DEFERRED_PARSE
25334                 && value_dependent_expression_p (noex))
25335               return true;
25336       return false;
25337     }
25338   /* -- an array type constructed from any dependent type or whose
25339         size is specified by a constant expression that is
25340         value-dependent.
25341
25342         We checked for type- and value-dependence of the bounds in
25343         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
25344   if (TREE_CODE (type) == ARRAY_TYPE)
25345     {
25346       if (TYPE_DOMAIN (type)
25347           && dependent_type_p (TYPE_DOMAIN (type)))
25348         return true;
25349       return dependent_type_p (TREE_TYPE (type));
25350     }
25351
25352   /* -- a template-id in which either the template name is a template
25353      parameter ...  */
25354   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
25355     return true;
25356   /* ... or any of the template arguments is a dependent type or
25357         an expression that is type-dependent or value-dependent.  */
25358   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
25359            && (any_dependent_template_arguments_p
25360                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
25361     return true;
25362
25363   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
25364      dependent; if the argument of the `typeof' expression is not
25365      type-dependent, then it should already been have resolved.  */
25366   if (TREE_CODE (type) == TYPEOF_TYPE
25367       || TREE_CODE (type) == DECLTYPE_TYPE
25368       || TREE_CODE (type) == UNDERLYING_TYPE)
25369     return true;
25370
25371   /* A template argument pack is dependent if any of its packed
25372      arguments are.  */
25373   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
25374     {
25375       tree args = ARGUMENT_PACK_ARGS (type);
25376       int i, len = TREE_VEC_LENGTH (args);
25377       for (i = 0; i < len; ++i)
25378         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25379           return true;
25380     }
25381
25382   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
25383      be template parameters.  */
25384   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
25385     return true;
25386
25387   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
25388     return true;
25389
25390   /* The standard does not specifically mention types that are local
25391      to template functions or local classes, but they should be
25392      considered dependent too.  For example:
25393
25394        template <int I> void f() {
25395          enum E { a = I };
25396          S<sizeof (E)> s;
25397        }
25398
25399      The size of `E' cannot be known until the value of `I' has been
25400      determined.  Therefore, `E' must be considered dependent.  */
25401   scope = TYPE_CONTEXT (type);
25402   if (scope && TYPE_P (scope))
25403     return dependent_type_p (scope);
25404   /* Don't use type_dependent_expression_p here, as it can lead
25405      to infinite recursion trying to determine whether a lambda
25406      nested in a lambda is dependent (c++/47687).  */
25407   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
25408            && DECL_LANG_SPECIFIC (scope)
25409            && DECL_TEMPLATE_INFO (scope)
25410            && (any_dependent_template_arguments_p
25411                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
25412     return true;
25413
25414   /* Other types are non-dependent.  */
25415   return false;
25416 }
25417
25418 /* Returns TRUE if TYPE is dependent, in the sense of
25419    [temp.dep.type].  Note that a NULL type is considered dependent.  */
25420
25421 bool
25422 dependent_type_p (tree type)
25423 {
25424   /* If there are no template parameters in scope, then there can't be
25425      any dependent types.  */
25426   if (!processing_template_decl)
25427     {
25428       /* If we are not processing a template, then nobody should be
25429          providing us with a dependent type.  */
25430       gcc_assert (type);
25431       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
25432       return false;
25433     }
25434
25435   /* If the type is NULL, we have not computed a type for the entity
25436      in question; in that case, the type is dependent.  */
25437   if (!type)
25438     return true;
25439
25440   /* Erroneous types can be considered non-dependent.  */
25441   if (type == error_mark_node)
25442     return false;
25443
25444   /* Getting here with global_type_node means we improperly called this
25445      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
25446   gcc_checking_assert (type != global_type_node);
25447
25448   /* If we have not already computed the appropriate value for TYPE,
25449      do so now.  */
25450   if (!TYPE_DEPENDENT_P_VALID (type))
25451     {
25452       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
25453       TYPE_DEPENDENT_P_VALID (type) = 1;
25454     }
25455
25456   return TYPE_DEPENDENT_P (type);
25457 }
25458
25459 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
25460    lookup.  In other words, a dependent type that is not the current
25461    instantiation.  */
25462
25463 bool
25464 dependent_scope_p (tree scope)
25465 {
25466   return (scope && TYPE_P (scope) && dependent_type_p (scope)
25467           && !currently_open_class (scope));
25468 }
25469
25470 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
25471    an unknown base of 'this' (and is therefore instantiation-dependent).  */
25472
25473 static bool
25474 unknown_base_ref_p (tree t)
25475 {
25476   if (!current_class_ptr)
25477     return false;
25478
25479   tree mem = TREE_OPERAND (t, 1);
25480   if (shared_member_p (mem))
25481     return false;
25482
25483   tree cur = current_nonlambda_class_type ();
25484   if (!any_dependent_bases_p (cur))
25485     return false;
25486
25487   tree ctx = TREE_OPERAND (t, 0);
25488   if (DERIVED_FROM_P (ctx, cur))
25489     return false;
25490
25491   return true;
25492 }
25493
25494 /* T is a SCOPE_REF; return whether we need to consider it
25495     instantiation-dependent so that we can check access at instantiation
25496     time even though we know which member it resolves to.  */
25497
25498 static bool
25499 instantiation_dependent_scope_ref_p (tree t)
25500 {
25501   if (DECL_P (TREE_OPERAND (t, 1))
25502       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
25503       && !unknown_base_ref_p (t)
25504       && accessible_in_template_p (TREE_OPERAND (t, 0),
25505                                    TREE_OPERAND (t, 1)))
25506     return false;
25507   else
25508     return true;
25509 }
25510
25511 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
25512    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
25513    expression.  */
25514
25515 /* Note that this predicate is not appropriate for general expressions;
25516    only constant expressions (that satisfy potential_constant_expression)
25517    can be tested for value dependence.  */
25518
25519 bool
25520 value_dependent_expression_p (tree expression)
25521 {
25522   if (!processing_template_decl || expression == NULL_TREE)
25523     return false;
25524
25525   /* A type-dependent expression is also value-dependent.  */
25526   if (type_dependent_expression_p (expression))
25527     return true;
25528
25529   switch (TREE_CODE (expression))
25530     {
25531     case BASELINK:
25532       /* A dependent member function of the current instantiation.  */
25533       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
25534
25535     case FUNCTION_DECL:
25536       /* A dependent member function of the current instantiation.  */
25537       if (DECL_CLASS_SCOPE_P (expression)
25538           && dependent_type_p (DECL_CONTEXT (expression)))
25539         return true;
25540       break;
25541
25542     case IDENTIFIER_NODE:
25543       /* A name that has not been looked up -- must be dependent.  */
25544       return true;
25545
25546     case TEMPLATE_PARM_INDEX:
25547       /* A non-type template parm.  */
25548       return true;
25549
25550     case CONST_DECL:
25551       /* A non-type template parm.  */
25552       if (DECL_TEMPLATE_PARM_P (expression))
25553         return true;
25554       return value_dependent_expression_p (DECL_INITIAL (expression));
25555
25556     case VAR_DECL:
25557        /* A constant with literal type and is initialized
25558           with an expression that is value-dependent.  */
25559       if (DECL_DEPENDENT_INIT_P (expression)
25560           /* FIXME cp_finish_decl doesn't fold reference initializers.  */
25561           || TYPE_REF_P (TREE_TYPE (expression)))
25562         return true;
25563       if (DECL_HAS_VALUE_EXPR_P (expression))
25564         {
25565           tree value_expr = DECL_VALUE_EXPR (expression);
25566           if (value_dependent_expression_p (value_expr)
25567               /* __PRETTY_FUNCTION__ inside a template function is dependent
25568                  on the name of the function.  */
25569               || (DECL_PRETTY_FUNCTION_P (expression)
25570                   /* It might be used in a template, but not a template
25571                      function, in which case its DECL_VALUE_EXPR will be
25572                      "top level".  */
25573                   && value_expr == error_mark_node))
25574             return true;
25575         }
25576       return false;
25577
25578     case DYNAMIC_CAST_EXPR:
25579     case STATIC_CAST_EXPR:
25580     case CONST_CAST_EXPR:
25581     case REINTERPRET_CAST_EXPR:
25582     case CAST_EXPR:
25583     case IMPLICIT_CONV_EXPR:
25584       /* These expressions are value-dependent if the type to which
25585          the cast occurs is dependent or the expression being casted
25586          is value-dependent.  */
25587       {
25588         tree type = TREE_TYPE (expression);
25589
25590         if (dependent_type_p (type))
25591           return true;
25592
25593         /* A functional cast has a list of operands.  */
25594         expression = TREE_OPERAND (expression, 0);
25595         if (!expression)
25596           {
25597             /* If there are no operands, it must be an expression such
25598                as "int()". This should not happen for aggregate types
25599                because it would form non-constant expressions.  */
25600             gcc_assert (cxx_dialect >= cxx11
25601                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
25602
25603             return false;
25604           }
25605
25606         if (TREE_CODE (expression) == TREE_LIST)
25607           return any_value_dependent_elements_p (expression);
25608
25609         return value_dependent_expression_p (expression);
25610       }
25611
25612     case SIZEOF_EXPR:
25613       if (SIZEOF_EXPR_TYPE_P (expression))
25614         return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
25615       /* FALLTHRU */
25616     case ALIGNOF_EXPR:
25617     case TYPEID_EXPR:
25618       /* A `sizeof' expression is value-dependent if the operand is
25619          type-dependent or is a pack expansion.  */
25620       expression = TREE_OPERAND (expression, 0);
25621       if (PACK_EXPANSION_P (expression))
25622         return true;
25623       else if (TYPE_P (expression))
25624         return dependent_type_p (expression);
25625       return instantiation_dependent_uneval_expression_p (expression);
25626
25627     case AT_ENCODE_EXPR:
25628       /* An 'encode' expression is value-dependent if the operand is
25629          type-dependent.  */
25630       expression = TREE_OPERAND (expression, 0);
25631       return dependent_type_p (expression);
25632
25633     case NOEXCEPT_EXPR:
25634       expression = TREE_OPERAND (expression, 0);
25635       return instantiation_dependent_uneval_expression_p (expression);
25636
25637     case SCOPE_REF:
25638       /* All instantiation-dependent expressions should also be considered
25639          value-dependent.  */
25640       return instantiation_dependent_scope_ref_p (expression);
25641
25642     case COMPONENT_REF:
25643       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
25644               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
25645
25646     case NONTYPE_ARGUMENT_PACK:
25647       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
25648          is value-dependent.  */
25649       {
25650         tree values = ARGUMENT_PACK_ARGS (expression);
25651         int i, len = TREE_VEC_LENGTH (values);
25652
25653         for (i = 0; i < len; ++i)
25654           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
25655             return true;
25656
25657         return false;
25658       }
25659
25660     case TRAIT_EXPR:
25661       {
25662         tree type2 = TRAIT_EXPR_TYPE2 (expression);
25663
25664         if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
25665           return true;
25666
25667         if (!type2)
25668           return false;
25669
25670         if (TREE_CODE (type2) != TREE_LIST)
25671           return dependent_type_p (type2);
25672
25673         for (; type2; type2 = TREE_CHAIN (type2))
25674           if (dependent_type_p (TREE_VALUE (type2)))
25675             return true;
25676
25677         return false;
25678       }
25679
25680     case MODOP_EXPR:
25681       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
25682               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
25683
25684     case ARRAY_REF:
25685       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
25686               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
25687
25688     case ADDR_EXPR:
25689       {
25690         tree op = TREE_OPERAND (expression, 0);
25691         return (value_dependent_expression_p (op)
25692                 || has_value_dependent_address (op));
25693       }
25694
25695     case REQUIRES_EXPR:
25696       /* Treat all requires-expressions as value-dependent so
25697          we don't try to fold them.  */
25698       return true;
25699
25700     case TYPE_REQ:
25701       return dependent_type_p (TREE_OPERAND (expression, 0));
25702
25703     case CALL_EXPR:
25704       {
25705         if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
25706           return true;
25707         tree fn = get_callee_fndecl (expression);
25708         int i, nargs;
25709         nargs = call_expr_nargs (expression);
25710         for (i = 0; i < nargs; ++i)
25711           {
25712             tree op = CALL_EXPR_ARG (expression, i);
25713             /* In a call to a constexpr member function, look through the
25714                implicit ADDR_EXPR on the object argument so that it doesn't
25715                cause the call to be considered value-dependent.  We also
25716                look through it in potential_constant_expression.  */
25717             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
25718                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
25719                 && TREE_CODE (op) == ADDR_EXPR)
25720               op = TREE_OPERAND (op, 0);
25721             if (value_dependent_expression_p (op))
25722               return true;
25723           }
25724         return false;
25725       }
25726
25727     case TEMPLATE_ID_EXPR:
25728       return variable_concept_p (TREE_OPERAND (expression, 0));
25729
25730     case CONSTRUCTOR:
25731       {
25732         unsigned ix;
25733         tree val;
25734         if (dependent_type_p (TREE_TYPE (expression)))
25735           return true;
25736         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
25737           if (value_dependent_expression_p (val))
25738             return true;
25739         return false;
25740       }
25741
25742     case STMT_EXPR:
25743       /* Treat a GNU statement expression as dependent to avoid crashing
25744          under instantiate_non_dependent_expr; it can't be constant.  */
25745       return true;
25746
25747     default:
25748       /* A constant expression is value-dependent if any subexpression is
25749          value-dependent.  */
25750       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
25751         {
25752         case tcc_reference:
25753         case tcc_unary:
25754         case tcc_comparison:
25755         case tcc_binary:
25756         case tcc_expression:
25757         case tcc_vl_exp:
25758           {
25759             int i, len = cp_tree_operand_length (expression);
25760
25761             for (i = 0; i < len; i++)
25762               {
25763                 tree t = TREE_OPERAND (expression, i);
25764
25765                 /* In some cases, some of the operands may be missing.
25766                    (For example, in the case of PREDECREMENT_EXPR, the
25767                    amount to increment by may be missing.)  That doesn't
25768                    make the expression dependent.  */
25769                 if (t && value_dependent_expression_p (t))
25770                   return true;
25771               }
25772           }
25773           break;
25774         default:
25775           break;
25776         }
25777       break;
25778     }
25779
25780   /* The expression is not value-dependent.  */
25781   return false;
25782 }
25783
25784 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
25785    [temp.dep.expr].  Note that an expression with no type is
25786    considered dependent.  Other parts of the compiler arrange for an
25787    expression with type-dependent subexpressions to have no type, so
25788    this function doesn't have to be fully recursive.  */
25789
25790 bool
25791 type_dependent_expression_p (tree expression)
25792 {
25793   if (!processing_template_decl)
25794     return false;
25795
25796   if (expression == NULL_TREE || expression == error_mark_node)
25797     return false;
25798
25799   STRIP_ANY_LOCATION_WRAPPER (expression);
25800
25801   /* An unresolved name is always dependent.  */
25802   if (identifier_p (expression)
25803       || TREE_CODE (expression) == USING_DECL
25804       || TREE_CODE (expression) == WILDCARD_DECL)
25805     return true;
25806
25807   /* A lambda-expression in template context is dependent.  dependent_type_p is
25808      true for a lambda in the scope of a class or function template, but that
25809      doesn't cover all template contexts, like a default template argument.  */
25810   if (TREE_CODE (expression) == LAMBDA_EXPR)
25811     return true;
25812
25813   /* A fold expression is type-dependent. */
25814   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
25815       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
25816       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
25817       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
25818     return true;
25819
25820   /* Some expression forms are never type-dependent.  */
25821   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
25822       || TREE_CODE (expression) == SIZEOF_EXPR
25823       || TREE_CODE (expression) == ALIGNOF_EXPR
25824       || TREE_CODE (expression) == AT_ENCODE_EXPR
25825       || TREE_CODE (expression) == NOEXCEPT_EXPR
25826       || TREE_CODE (expression) == TRAIT_EXPR
25827       || TREE_CODE (expression) == TYPEID_EXPR
25828       || TREE_CODE (expression) == DELETE_EXPR
25829       || TREE_CODE (expression) == VEC_DELETE_EXPR
25830       || TREE_CODE (expression) == THROW_EXPR
25831       || TREE_CODE (expression) == REQUIRES_EXPR)
25832     return false;
25833
25834   /* The types of these expressions depends only on the type to which
25835      the cast occurs.  */
25836   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
25837       || TREE_CODE (expression) == STATIC_CAST_EXPR
25838       || TREE_CODE (expression) == CONST_CAST_EXPR
25839       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
25840       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
25841       || TREE_CODE (expression) == CAST_EXPR)
25842     return dependent_type_p (TREE_TYPE (expression));
25843
25844   /* The types of these expressions depends only on the type created
25845      by the expression.  */
25846   if (TREE_CODE (expression) == NEW_EXPR
25847       || TREE_CODE (expression) == VEC_NEW_EXPR)
25848     {
25849       /* For NEW_EXPR tree nodes created inside a template, either
25850          the object type itself or a TREE_LIST may appear as the
25851          operand 1.  */
25852       tree type = TREE_OPERAND (expression, 1);
25853       if (TREE_CODE (type) == TREE_LIST)
25854         /* This is an array type.  We need to check array dimensions
25855            as well.  */
25856         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
25857                || value_dependent_expression_p
25858                     (TREE_OPERAND (TREE_VALUE (type), 1));
25859       else
25860         return dependent_type_p (type);
25861     }
25862
25863   if (TREE_CODE (expression) == SCOPE_REF)
25864     {
25865       tree scope = TREE_OPERAND (expression, 0);
25866       tree name = TREE_OPERAND (expression, 1);
25867
25868       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25869          contains an identifier associated by name lookup with one or more
25870          declarations declared with a dependent type, or...a
25871          nested-name-specifier or qualified-id that names a member of an
25872          unknown specialization.  */
25873       return (type_dependent_expression_p (name)
25874               || dependent_scope_p (scope));
25875     }
25876
25877   if (TREE_CODE (expression) == TEMPLATE_DECL
25878       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25879     return uses_outer_template_parms (expression);
25880
25881   if (TREE_CODE (expression) == STMT_EXPR)
25882     expression = stmt_expr_value_expr (expression);
25883
25884   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25885     {
25886       tree elt;
25887       unsigned i;
25888
25889       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25890         {
25891           if (type_dependent_expression_p (elt))
25892             return true;
25893         }
25894       return false;
25895     }
25896
25897   /* A static data member of the current instantiation with incomplete
25898      array type is type-dependent, as the definition and specializations
25899      can have different bounds.  */
25900   if (VAR_P (expression)
25901       && DECL_CLASS_SCOPE_P (expression)
25902       && dependent_type_p (DECL_CONTEXT (expression))
25903       && VAR_HAD_UNKNOWN_BOUND (expression))
25904     return true;
25905
25906   /* An array of unknown bound depending on a variadic parameter, eg:
25907
25908      template<typename... Args>
25909        void foo (Args... args)
25910        {
25911          int arr[] = { args... };
25912        }
25913
25914      template<int... vals>
25915        void bar ()
25916        {
25917          int arr[] = { vals... };
25918        }
25919
25920      If the array has no length and has an initializer, it must be that
25921      we couldn't determine its length in cp_complete_array_type because
25922      it is dependent.  */
25923   if (VAR_P (expression)
25924       && TREE_TYPE (expression) != NULL_TREE
25925       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25926       && !TYPE_DOMAIN (TREE_TYPE (expression))
25927       && DECL_INITIAL (expression))
25928    return true;
25929
25930   /* A function or variable template-id is type-dependent if it has any
25931      dependent template arguments.  */
25932   if (VAR_OR_FUNCTION_DECL_P (expression)
25933       && DECL_LANG_SPECIFIC (expression)
25934       && DECL_TEMPLATE_INFO (expression))
25935     {
25936       /* Consider the innermost template arguments, since those are the ones
25937          that come from the template-id; the template arguments for the
25938          enclosing class do not make it type-dependent unless they are used in
25939          the type of the decl.  */
25940       if (instantiates_primary_template_p (expression)
25941           && (any_dependent_template_arguments_p
25942               (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25943         return true;
25944     }
25945
25946   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25947      type-dependent.  Checking this is important for functions with auto return
25948      type, which looks like a dependent type.  */
25949   if (TREE_CODE (expression) == FUNCTION_DECL
25950       && !(DECL_CLASS_SCOPE_P (expression)
25951            && dependent_type_p (DECL_CONTEXT (expression)))
25952       && !(DECL_LANG_SPECIFIC (expression)
25953            && DECL_FRIEND_P (expression)
25954            && (!DECL_FRIEND_CONTEXT (expression)
25955                || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25956       && !DECL_LOCAL_FUNCTION_P (expression))
25957     {
25958       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25959                   || undeduced_auto_decl (expression));
25960       return false;
25961     }
25962
25963   /* Always dependent, on the number of arguments if nothing else.  */
25964   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25965     return true;
25966
25967   if (TREE_TYPE (expression) == unknown_type_node)
25968     {
25969       if (TREE_CODE (expression) == ADDR_EXPR)
25970         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25971       if (TREE_CODE (expression) == COMPONENT_REF
25972           || TREE_CODE (expression) == OFFSET_REF)
25973         {
25974           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25975             return true;
25976           expression = TREE_OPERAND (expression, 1);
25977           if (identifier_p (expression))
25978             return false;
25979         }
25980       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
25981       if (TREE_CODE (expression) == SCOPE_REF)
25982         return false;
25983
25984       if (BASELINK_P (expression))
25985         {
25986           if (BASELINK_OPTYPE (expression)
25987               && dependent_type_p (BASELINK_OPTYPE (expression)))
25988             return true;
25989           expression = BASELINK_FUNCTIONS (expression);
25990         }
25991
25992       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25993         {
25994           if (any_dependent_template_arguments_p
25995               (TREE_OPERAND (expression, 1)))
25996             return true;
25997           expression = TREE_OPERAND (expression, 0);
25998           if (identifier_p (expression))
25999             return true;
26000         }
26001
26002       gcc_assert (OVL_P (expression));
26003
26004       for (lkp_iterator iter (expression); iter; ++iter)
26005         if (type_dependent_expression_p (*iter))
26006           return true;
26007
26008       return false;
26009     }
26010
26011   /* The type of a non-type template parm declared with a placeholder type
26012      depends on the corresponding template argument, even though
26013      placeholders are not normally considered dependent.  */
26014   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
26015       && is_auto (TREE_TYPE (expression)))
26016     return true;
26017
26018   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
26019
26020   /* Dependent type attributes might not have made it from the decl to
26021      the type yet.  */
26022   if (DECL_P (expression)
26023       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
26024     return true;
26025
26026   return (dependent_type_p (TREE_TYPE (expression)));
26027 }
26028
26029 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
26030    type-dependent if the expression refers to a member of the current
26031    instantiation and the type of the referenced member is dependent, or the
26032    class member access expression refers to a member of an unknown
26033    specialization.
26034
26035    This function returns true if the OBJECT in such a class member access
26036    expression is of an unknown specialization.  */
26037
26038 bool
26039 type_dependent_object_expression_p (tree object)
26040 {
26041   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
26042      dependent.  */
26043   if (TREE_CODE (object) == IDENTIFIER_NODE)
26044     return true;
26045   tree scope = TREE_TYPE (object);
26046   return (!scope || dependent_scope_p (scope));
26047 }
26048
26049 /* walk_tree callback function for instantiation_dependent_expression_p,
26050    below.  Returns non-zero if a dependent subexpression is found.  */
26051
26052 static tree
26053 instantiation_dependent_r (tree *tp, int *walk_subtrees,
26054                            void * /*data*/)
26055 {
26056   if (TYPE_P (*tp))
26057     {
26058       /* We don't have to worry about decltype currently because decltype
26059          of an instantiation-dependent expr is a dependent type.  This
26060          might change depending on the resolution of DR 1172.  */
26061       *walk_subtrees = false;
26062       return NULL_TREE;
26063     }
26064   enum tree_code code = TREE_CODE (*tp);
26065   switch (code)
26066     {
26067       /* Don't treat an argument list as dependent just because it has no
26068          TREE_TYPE.  */
26069     case TREE_LIST:
26070     case TREE_VEC:
26071     case NONTYPE_ARGUMENT_PACK:
26072       return NULL_TREE;
26073
26074     case TEMPLATE_PARM_INDEX:
26075       if (dependent_type_p (TREE_TYPE (*tp)))
26076         return *tp;
26077       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
26078         return *tp;
26079       /* We'll check value-dependence separately.  */
26080       return NULL_TREE;
26081
26082       /* Handle expressions with type operands.  */
26083     case SIZEOF_EXPR:
26084     case ALIGNOF_EXPR:
26085     case TYPEID_EXPR:
26086     case AT_ENCODE_EXPR:
26087       {
26088         tree op = TREE_OPERAND (*tp, 0);
26089         if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
26090           op = TREE_TYPE (op);
26091         if (TYPE_P (op))
26092           {
26093             if (dependent_type_p (op))
26094               return *tp;
26095             else
26096               {
26097                 *walk_subtrees = false;
26098                 return NULL_TREE;
26099               }
26100           }
26101         break;
26102       }
26103
26104     case COMPONENT_REF:
26105       if (identifier_p (TREE_OPERAND (*tp, 1)))
26106         /* In a template, finish_class_member_access_expr creates a
26107            COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
26108            type-dependent, so that we can check access control at
26109            instantiation time (PR 42277).  See also Core issue 1273.  */
26110         return *tp;
26111       break;
26112
26113     case SCOPE_REF:
26114       if (instantiation_dependent_scope_ref_p (*tp))
26115         return *tp;
26116       else
26117         break;
26118
26119       /* Treat statement-expressions as dependent.  */
26120     case BIND_EXPR:
26121       return *tp;
26122
26123       /* Treat requires-expressions as dependent. */
26124     case REQUIRES_EXPR:
26125       return *tp;
26126
26127     case CALL_EXPR:
26128       /* Treat calls to function concepts as dependent. */
26129       if (function_concept_check_p (*tp))
26130         return *tp;
26131       break;
26132
26133     case TEMPLATE_ID_EXPR:
26134       /* And variable concepts.  */
26135       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
26136         return *tp;
26137       break;
26138
26139     case CONSTRUCTOR:
26140       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
26141         return *tp;
26142       break;
26143
26144     default:
26145       break;
26146     }
26147
26148   if (type_dependent_expression_p (*tp))
26149     return *tp;
26150   else
26151     return NULL_TREE;
26152 }
26153
26154 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
26155    sense defined by the ABI:
26156
26157    "An expression is instantiation-dependent if it is type-dependent
26158    or value-dependent, or it has a subexpression that is type-dependent
26159    or value-dependent."
26160
26161    Except don't actually check value-dependence for unevaluated expressions,
26162    because in sizeof(i) we don't care about the value of i.  Checking
26163    type-dependence will in turn check value-dependence of array bounds/template
26164    arguments as needed.  */
26165
26166 bool
26167 instantiation_dependent_uneval_expression_p (tree expression)
26168 {
26169   tree result;
26170
26171   if (!processing_template_decl)
26172     return false;
26173
26174   if (expression == error_mark_node)
26175     return false;
26176
26177   result = cp_walk_tree_without_duplicates (&expression,
26178                                             instantiation_dependent_r, NULL);
26179   return result != NULL_TREE;
26180 }
26181
26182 /* As above, but also check value-dependence of the expression as a whole.  */
26183
26184 bool
26185 instantiation_dependent_expression_p (tree expression)
26186 {
26187   return (instantiation_dependent_uneval_expression_p (expression)
26188           || value_dependent_expression_p (expression));
26189 }
26190
26191 /* Like type_dependent_expression_p, but it also works while not processing
26192    a template definition, i.e. during substitution or mangling.  */
26193
26194 bool
26195 type_dependent_expression_p_push (tree expr)
26196 {
26197   bool b;
26198   ++processing_template_decl;
26199   b = type_dependent_expression_p (expr);
26200   --processing_template_decl;
26201   return b;
26202 }
26203
26204 /* Returns TRUE if ARGS contains a type-dependent expression.  */
26205
26206 bool
26207 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
26208 {
26209   unsigned int i;
26210   tree arg;
26211
26212   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
26213     {
26214       if (type_dependent_expression_p (arg))
26215         return true;
26216     }
26217   return false;
26218 }
26219
26220 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
26221    expressions) contains any type-dependent expressions.  */
26222
26223 bool
26224 any_type_dependent_elements_p (const_tree list)
26225 {
26226   for (; list; list = TREE_CHAIN (list))
26227     if (type_dependent_expression_p (TREE_VALUE (list)))
26228       return true;
26229
26230   return false;
26231 }
26232
26233 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
26234    expressions) contains any value-dependent expressions.  */
26235
26236 bool
26237 any_value_dependent_elements_p (const_tree list)
26238 {
26239   for (; list; list = TREE_CHAIN (list))
26240     if (value_dependent_expression_p (TREE_VALUE (list)))
26241       return true;
26242
26243   return false;
26244 }
26245
26246 /* Returns TRUE if the ARG (a template argument) is dependent.  */
26247
26248 bool
26249 dependent_template_arg_p (tree arg)
26250 {
26251   if (!processing_template_decl)
26252     return false;
26253
26254   /* Assume a template argument that was wrongly written by the user
26255      is dependent. This is consistent with what
26256      any_dependent_template_arguments_p [that calls this function]
26257      does.  */
26258   if (!arg || arg == error_mark_node)
26259     return true;
26260
26261   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
26262     arg = argument_pack_select_arg (arg);
26263
26264   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
26265     return true;
26266   if (TREE_CODE (arg) == TEMPLATE_DECL)
26267     {
26268       if (DECL_TEMPLATE_PARM_P (arg))
26269         return true;
26270       /* A member template of a dependent class is not necessarily
26271          type-dependent, but it is a dependent template argument because it
26272          will be a member of an unknown specialization to that template.  */
26273       tree scope = CP_DECL_CONTEXT (arg);
26274       return TYPE_P (scope) && dependent_type_p (scope);
26275     }
26276   else if (ARGUMENT_PACK_P (arg))
26277     {
26278       tree args = ARGUMENT_PACK_ARGS (arg);
26279       int i, len = TREE_VEC_LENGTH (args);
26280       for (i = 0; i < len; ++i)
26281         {
26282           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26283             return true;
26284         }
26285
26286       return false;
26287     }
26288   else if (TYPE_P (arg))
26289     return dependent_type_p (arg);
26290   else
26291     return (type_dependent_expression_p (arg)
26292             || value_dependent_expression_p (arg));
26293 }
26294
26295 /* Returns true if ARGS (a collection of template arguments) contains
26296    any types that require structural equality testing.  */
26297
26298 bool
26299 any_template_arguments_need_structural_equality_p (tree args)
26300 {
26301   int i;
26302   int j;
26303
26304   if (!args)
26305     return false;
26306   if (args == error_mark_node)
26307     return true;
26308
26309   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
26310     {
26311       tree level = TMPL_ARGS_LEVEL (args, i + 1);
26312       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
26313         {
26314           tree arg = TREE_VEC_ELT (level, j);
26315           tree packed_args = NULL_TREE;
26316           int k, len = 1;
26317
26318           if (ARGUMENT_PACK_P (arg))
26319             {
26320               /* Look inside the argument pack.  */
26321               packed_args = ARGUMENT_PACK_ARGS (arg);
26322               len = TREE_VEC_LENGTH (packed_args);
26323             }
26324
26325           for (k = 0; k < len; ++k)
26326             {
26327               if (packed_args)
26328                 arg = TREE_VEC_ELT (packed_args, k);
26329
26330               if (error_operand_p (arg))
26331                 return true;
26332               else if (TREE_CODE (arg) == TEMPLATE_DECL)
26333                 continue;
26334               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
26335                 return true;
26336               else if (!TYPE_P (arg) && TREE_TYPE (arg)
26337                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
26338                 return true;
26339             }
26340         }
26341     }
26342
26343   return false;
26344 }
26345
26346 /* Returns true if ARGS (a collection of template arguments) contains
26347    any dependent arguments.  */
26348
26349 bool
26350 any_dependent_template_arguments_p (const_tree args)
26351 {
26352   int i;
26353   int j;
26354
26355   if (!args)
26356     return false;
26357   if (args == error_mark_node)
26358     return true;
26359
26360   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
26361     {
26362       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
26363       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
26364         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
26365           return true;
26366     }
26367
26368   return false;
26369 }
26370
26371 /* Returns true if ARGS contains any errors.  */
26372
26373 bool
26374 any_erroneous_template_args_p (const_tree args)
26375 {
26376   int i;
26377   int j;
26378
26379   if (args == error_mark_node)
26380     return true;
26381
26382   if (args && TREE_CODE (args) != TREE_VEC)
26383     {
26384       if (tree ti = get_template_info (args))
26385         args = TI_ARGS (ti);
26386       else
26387         args = NULL_TREE;
26388     }
26389
26390   if (!args)
26391     return false;
26392
26393   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
26394     {
26395       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
26396       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
26397         if (error_operand_p (TREE_VEC_ELT (level, j)))
26398           return true;
26399     }
26400
26401   return false;
26402 }
26403
26404 /* Returns TRUE if the template TMPL is type-dependent.  */
26405
26406 bool
26407 dependent_template_p (tree tmpl)
26408 {
26409   if (TREE_CODE (tmpl) == OVERLOAD)
26410     {
26411       for (lkp_iterator iter (tmpl); iter; ++iter)
26412         if (dependent_template_p (*iter))
26413           return true;
26414       return false;
26415     }
26416
26417   /* Template template parameters are dependent.  */
26418   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
26419       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
26420     return true;
26421   /* So are names that have not been looked up.  */
26422   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
26423     return true;
26424   return false;
26425 }
26426
26427 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
26428
26429 bool
26430 dependent_template_id_p (tree tmpl, tree args)
26431 {
26432   return (dependent_template_p (tmpl)
26433           || any_dependent_template_arguments_p (args));
26434 }
26435
26436 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
26437    are dependent.  */
26438
26439 bool
26440 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
26441 {
26442   int i;
26443
26444   if (!processing_template_decl)
26445     return false;
26446
26447   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
26448     {
26449       tree decl = TREE_VEC_ELT (declv, i);
26450       tree init = TREE_VEC_ELT (initv, i);
26451       tree cond = TREE_VEC_ELT (condv, i);
26452       tree incr = TREE_VEC_ELT (incrv, i);
26453
26454       if (type_dependent_expression_p (decl)
26455           || TREE_CODE (decl) == SCOPE_REF)
26456         return true;
26457
26458       if (init && type_dependent_expression_p (init))
26459         return true;
26460
26461       if (cond == global_namespace)
26462         return true;
26463
26464       if (type_dependent_expression_p (cond))
26465         return true;
26466
26467       if (COMPARISON_CLASS_P (cond)
26468           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
26469               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
26470         return true;
26471
26472       if (TREE_CODE (incr) == MODOP_EXPR)
26473         {
26474           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
26475               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
26476             return true;
26477         }
26478       else if (type_dependent_expression_p (incr))
26479         return true;
26480       else if (TREE_CODE (incr) == MODIFY_EXPR)
26481         {
26482           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
26483             return true;
26484           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
26485             {
26486               tree t = TREE_OPERAND (incr, 1);
26487               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
26488                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
26489                 return true;
26490
26491               /* If this loop has a class iterator with != comparison
26492                  with increment other than i++/++i/i--/--i, make sure the
26493                  increment is constant.  */
26494               if (CLASS_TYPE_P (TREE_TYPE (decl))
26495                   && TREE_CODE (cond) == NE_EXPR)
26496                 {
26497                   if (TREE_OPERAND (t, 0) == decl)
26498                     t = TREE_OPERAND (t, 1);
26499                   else
26500                     t = TREE_OPERAND (t, 0);
26501                   if (TREE_CODE (t) != INTEGER_CST)
26502                     return true;
26503                 }
26504             }
26505         }
26506     }
26507
26508   return false;
26509 }
26510
26511 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
26512    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
26513    no such TYPE can be found.  Note that this function peers inside
26514    uninstantiated templates and therefore should be used only in
26515    extremely limited situations.  ONLY_CURRENT_P restricts this
26516    peering to the currently open classes hierarchy (which is required
26517    when comparing types).  */
26518
26519 tree
26520 resolve_typename_type (tree type, bool only_current_p)
26521 {
26522   tree scope;
26523   tree name;
26524   tree decl;
26525   int quals;
26526   tree pushed_scope;
26527   tree result;
26528
26529   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
26530
26531   scope = TYPE_CONTEXT (type);
26532   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
26533   gcc_checking_assert (uses_template_parms (scope));
26534
26535   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
26536      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
26537      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
26538      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
26539      identifier  of the TYPENAME_TYPE anymore.
26540      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
26541      TYPENAME_TYPE instead, we avoid messing up with a possible
26542      typedef variant case.  */
26543   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
26544
26545   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
26546      it first before we can figure out what NAME refers to.  */
26547   if (TREE_CODE (scope) == TYPENAME_TYPE)
26548     {
26549       if (TYPENAME_IS_RESOLVING_P (scope))
26550         /* Given a class template A with a dependent base with nested type C,
26551            typedef typename A::C::C C will land us here, as trying to resolve
26552            the initial A::C leads to the local C typedef, which leads back to
26553            A::C::C.  So we break the recursion now.  */
26554         return type;
26555       else
26556         scope = resolve_typename_type (scope, only_current_p);
26557     }
26558   /* If we don't know what SCOPE refers to, then we cannot resolve the
26559      TYPENAME_TYPE.  */
26560   if (!CLASS_TYPE_P (scope))
26561     return type;
26562   /* If this is a typedef, we don't want to look inside (c++/11987).  */
26563   if (typedef_variant_p (type))
26564     return type;
26565   /* If SCOPE isn't the template itself, it will not have a valid
26566      TYPE_FIELDS list.  */
26567   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
26568     /* scope is either the template itself or a compatible instantiation
26569        like X<T>, so look up the name in the original template.  */
26570     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
26571   /* If scope has no fields, it can't be a current instantiation.  Check this
26572      before currently_open_class to avoid infinite recursion (71515).  */
26573   if (!TYPE_FIELDS (scope))
26574     return type;
26575   /* If the SCOPE is not the current instantiation, there's no reason
26576      to look inside it.  */
26577   if (only_current_p && !currently_open_class (scope))
26578     return type;
26579   /* Enter the SCOPE so that name lookup will be resolved as if we
26580      were in the class definition.  In particular, SCOPE will no
26581      longer be considered a dependent type.  */
26582   pushed_scope = push_scope (scope);
26583   /* Look up the declaration.  */
26584   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
26585                         tf_warning_or_error);
26586
26587   result = NULL_TREE;
26588
26589   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
26590      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
26591   tree fullname = TYPENAME_TYPE_FULLNAME (type);
26592   if (!decl)
26593     /*nop*/;
26594   else if (identifier_p (fullname)
26595            && TREE_CODE (decl) == TYPE_DECL)
26596     {
26597       result = TREE_TYPE (decl);
26598       if (result == error_mark_node)
26599         result = NULL_TREE;
26600     }
26601   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
26602            && DECL_CLASS_TEMPLATE_P (decl))
26603     {
26604       /* Obtain the template and the arguments.  */
26605       tree tmpl = TREE_OPERAND (fullname, 0);
26606       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
26607         {
26608           /* We get here with a plain identifier because a previous tentative
26609              parse of the nested-name-specifier as part of a ptr-operator saw
26610              ::template X<A>.  The use of ::template is necessary in a
26611              ptr-operator, but wrong in a declarator-id.
26612
26613              [temp.names]: In a qualified-id of a declarator-id, the keyword
26614              template shall not appear at the top level.  */
26615           pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
26616                    "keyword %<template%> not allowed in declarator-id");
26617           tmpl = decl;
26618         }
26619       tree args = TREE_OPERAND (fullname, 1);
26620       /* Instantiate the template.  */
26621       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
26622                                       /*entering_scope=*/true,
26623                                       tf_error | tf_user);
26624       if (result == error_mark_node)
26625         result = NULL_TREE;
26626     }
26627
26628   /* Leave the SCOPE.  */
26629   if (pushed_scope)
26630     pop_scope (pushed_scope);
26631
26632   /* If we failed to resolve it, return the original typename.  */
26633   if (!result)
26634     return type;
26635
26636   /* If lookup found a typename type, resolve that too.  */
26637   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
26638     {
26639       /* Ill-formed programs can cause infinite recursion here, so we
26640          must catch that.  */
26641       TYPENAME_IS_RESOLVING_P (result) = 1;
26642       result = resolve_typename_type (result, only_current_p);
26643       TYPENAME_IS_RESOLVING_P (result) = 0;
26644     }
26645
26646   /* Qualify the resulting type.  */
26647   quals = cp_type_quals (type);
26648   if (quals)
26649     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
26650
26651   return result;
26652 }
26653
26654 /* EXPR is an expression which is not type-dependent.  Return a proxy
26655    for EXPR that can be used to compute the types of larger
26656    expressions containing EXPR.  */
26657
26658 tree
26659 build_non_dependent_expr (tree expr)
26660 {
26661   tree orig_expr = expr;
26662   tree inner_expr;
26663
26664   /* When checking, try to get a constant value for all non-dependent
26665      expressions in order to expose bugs in *_dependent_expression_p
26666      and constexpr.  This can affect code generation, see PR70704, so
26667      only do this for -fchecking=2.  */
26668   if (flag_checking > 1
26669       && cxx_dialect >= cxx11
26670       /* Don't do this during nsdmi parsing as it can lead to
26671          unexpected recursive instantiations.  */
26672       && !parsing_nsdmi ()
26673       /* Don't do this during concept expansion either and for
26674          the same reason.  */
26675       && !expanding_concept ())
26676     fold_non_dependent_expr (expr, tf_none);
26677
26678   STRIP_ANY_LOCATION_WRAPPER (expr);
26679
26680   /* Preserve OVERLOADs; the functions must be available to resolve
26681      types.  */
26682   inner_expr = expr;
26683   if (TREE_CODE (inner_expr) == STMT_EXPR)
26684     inner_expr = stmt_expr_value_expr (inner_expr);
26685   if (TREE_CODE (inner_expr) == ADDR_EXPR)
26686     inner_expr = TREE_OPERAND (inner_expr, 0);
26687   if (TREE_CODE (inner_expr) == COMPONENT_REF)
26688     inner_expr = TREE_OPERAND (inner_expr, 1);
26689   if (is_overloaded_fn (inner_expr)
26690       || TREE_CODE (inner_expr) == OFFSET_REF)
26691     return orig_expr;
26692   /* There is no need to return a proxy for a variable or enumerator.  */
26693   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
26694     return orig_expr;
26695   /* Preserve string constants; conversions from string constants to
26696      "char *" are allowed, even though normally a "const char *"
26697      cannot be used to initialize a "char *".  */
26698   if (TREE_CODE (expr) == STRING_CST)
26699     return orig_expr;
26700   /* Preserve void and arithmetic constants, as an optimization -- there is no
26701      reason to create a new node.  */
26702   if (TREE_CODE (expr) == VOID_CST
26703       || TREE_CODE (expr) == INTEGER_CST
26704       || TREE_CODE (expr) == REAL_CST)
26705     return orig_expr;
26706   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
26707      There is at least one place where we want to know that a
26708      particular expression is a throw-expression: when checking a ?:
26709      expression, there are special rules if the second or third
26710      argument is a throw-expression.  */
26711   if (TREE_CODE (expr) == THROW_EXPR)
26712     return orig_expr;
26713
26714   /* Don't wrap an initializer list, we need to be able to look inside.  */
26715   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
26716     return orig_expr;
26717
26718   /* Don't wrap a dummy object, we need to be able to test for it.  */
26719   if (is_dummy_object (expr))
26720     return orig_expr;
26721
26722   if (TREE_CODE (expr) == COND_EXPR)
26723     return build3 (COND_EXPR,
26724                    TREE_TYPE (expr),
26725                    TREE_OPERAND (expr, 0),
26726                    (TREE_OPERAND (expr, 1)
26727                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
26728                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
26729                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
26730   if (TREE_CODE (expr) == COMPOUND_EXPR
26731       && !COMPOUND_EXPR_OVERLOADED (expr))
26732     return build2 (COMPOUND_EXPR,
26733                    TREE_TYPE (expr),
26734                    TREE_OPERAND (expr, 0),
26735                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
26736
26737   /* If the type is unknown, it can't really be non-dependent */
26738   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
26739
26740   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
26741   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
26742                      TREE_TYPE (expr), expr);
26743 }
26744
26745 /* ARGS is a vector of expressions as arguments to a function call.
26746    Replace the arguments with equivalent non-dependent expressions.
26747    This modifies ARGS in place.  */
26748
26749 void
26750 make_args_non_dependent (vec<tree, va_gc> *args)
26751 {
26752   unsigned int ix;
26753   tree arg;
26754
26755   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
26756     {
26757       tree newarg = build_non_dependent_expr (arg);
26758       if (newarg != arg)
26759         (*args)[ix] = newarg;
26760     }
26761 }
26762
26763 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
26764    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
26765    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
26766
26767 static tree
26768 make_auto_1 (tree name, bool set_canonical)
26769 {
26770   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
26771   TYPE_NAME (au) = build_decl (input_location,
26772                                TYPE_DECL, name, au);
26773   TYPE_STUB_DECL (au) = TYPE_NAME (au);
26774   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
26775     (0, processing_template_decl + 1, processing_template_decl + 1,
26776      TYPE_NAME (au), NULL_TREE);
26777   if (set_canonical)
26778     TYPE_CANONICAL (au) = canonical_type_parameter (au);
26779   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
26780   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
26781
26782   return au;
26783 }
26784
26785 tree
26786 make_decltype_auto (void)
26787 {
26788   return make_auto_1 (decltype_auto_identifier, true);
26789 }
26790
26791 tree
26792 make_auto (void)
26793 {
26794   return make_auto_1 (auto_identifier, true);
26795 }
26796
26797 /* Return a C++17 deduction placeholder for class template TMPL.  */
26798
26799 tree
26800 make_template_placeholder (tree tmpl)
26801 {
26802   tree t = make_auto_1 (auto_identifier, false);
26803   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
26804   /* Our canonical type depends on the placeholder.  */
26805   TYPE_CANONICAL (t) = canonical_type_parameter (t);
26806   return t;
26807 }
26808
26809 /* True iff T is a C++17 class template deduction placeholder.  */
26810
26811 bool
26812 template_placeholder_p (tree t)
26813 {
26814   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
26815 }
26816
26817 /* Make a "constrained auto" type-specifier. This is an
26818    auto type with constraints that must be associated after
26819    deduction.  The constraint is formed from the given
26820    CONC and its optional sequence of arguments, which are
26821    non-null if written as partial-concept-id.  */
26822
26823 tree
26824 make_constrained_auto (tree con, tree args)
26825 {
26826   tree type = make_auto_1 (auto_identifier, false);
26827
26828   /* Build the constraint. */
26829   tree tmpl = DECL_TI_TEMPLATE (con);
26830   tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
26831   expr = build_concept_check (expr, type, args);
26832
26833   tree constr = normalize_expression (expr);
26834   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
26835
26836   /* Our canonical type depends on the constraint.  */
26837   TYPE_CANONICAL (type) = canonical_type_parameter (type);
26838
26839   /* Attach the constraint to the type declaration. */
26840   tree decl = TYPE_NAME (type);
26841   return decl;
26842 }
26843
26844 /* Given type ARG, return std::initializer_list<ARG>.  */
26845
26846 static tree
26847 listify (tree arg)
26848 {
26849   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
26850
26851   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
26852     {
26853       gcc_rich_location richloc (input_location);
26854       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
26855       error_at (&richloc,
26856                 "deducing from brace-enclosed initializer list"
26857                 " requires %<#include <initializer_list>%>");
26858
26859       return error_mark_node;
26860     }
26861   tree argvec = make_tree_vec (1);
26862   TREE_VEC_ELT (argvec, 0) = arg;
26863
26864   return lookup_template_class (std_init_list, argvec, NULL_TREE,
26865                                 NULL_TREE, 0, tf_warning_or_error);
26866 }
26867
26868 /* Replace auto in TYPE with std::initializer_list<auto>.  */
26869
26870 static tree
26871 listify_autos (tree type, tree auto_node)
26872 {
26873   tree init_auto = listify (strip_top_quals (auto_node));
26874   tree argvec = make_tree_vec (1);
26875   TREE_VEC_ELT (argvec, 0) = init_auto;
26876   if (processing_template_decl)
26877     argvec = add_to_template_args (current_template_args (), argvec);
26878   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
26879 }
26880
26881 /* Hash traits for hashing possibly constrained 'auto'
26882    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
26883
26884 struct auto_hash : default_hash_traits<tree>
26885 {
26886   static inline hashval_t hash (tree);
26887   static inline bool equal (tree, tree);
26888 };
26889
26890 /* Hash the 'auto' T.  */
26891
26892 inline hashval_t
26893 auto_hash::hash (tree t)
26894 {
26895   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
26896     /* Matching constrained-type-specifiers denote the same template
26897        parameter, so hash the constraint.  */
26898     return hash_placeholder_constraint (c);
26899   else
26900     /* But unconstrained autos are all separate, so just hash the pointer.  */
26901     return iterative_hash_object (t, 0);
26902 }
26903
26904 /* Compare two 'auto's.  */
26905
26906 inline bool
26907 auto_hash::equal (tree t1, tree t2)
26908 {
26909   if (t1 == t2)
26910     return true;
26911
26912   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26913   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26914
26915   /* Two unconstrained autos are distinct.  */
26916   if (!c1 || !c2)
26917     return false;
26918
26919   return equivalent_placeholder_constraints (c1, c2);
26920 }
26921
26922 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26923    constrained) auto, add it to the vector.  */
26924
26925 static int
26926 extract_autos_r (tree t, void *data)
26927 {
26928   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26929   if (is_auto (t))
26930     {
26931       /* All the autos were built with index 0; fix that up now.  */
26932       tree *p = hash.find_slot (t, INSERT);
26933       unsigned idx;
26934       if (*p)
26935         /* If this is a repeated constrained-type-specifier, use the index we
26936            chose before.  */
26937         idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26938       else
26939         {
26940           /* Otherwise this is new, so use the current count.  */
26941           *p = t;
26942           idx = hash.elements () - 1;
26943         }
26944       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26945     }
26946
26947   /* Always keep walking.  */
26948   return 0;
26949 }
26950
26951 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26952    says they can appear anywhere in the type.  */
26953
26954 static tree
26955 extract_autos (tree type)
26956 {
26957   hash_set<tree> visited;
26958   hash_table<auto_hash> hash (2);
26959
26960   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26961
26962   tree tree_vec = make_tree_vec (hash.elements());
26963   for (hash_table<auto_hash>::iterator iter = hash.begin();
26964        iter != hash.end(); ++iter)
26965     {
26966       tree elt = *iter;
26967       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26968       TREE_VEC_ELT (tree_vec, i)
26969         = build_tree_list (NULL_TREE, TYPE_NAME (elt));
26970     }
26971
26972   return tree_vec;
26973 }
26974
26975 /* The stem for deduction guide names.  */
26976 const char *const dguide_base = "__dguide_";
26977
26978 /* Return the name for a deduction guide for class template TMPL.  */
26979
26980 tree
26981 dguide_name (tree tmpl)
26982 {
26983   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26984   tree tname = TYPE_IDENTIFIER (type);
26985   char *buf = (char *) alloca (1 + strlen (dguide_base)
26986                                + IDENTIFIER_LENGTH (tname));
26987   memcpy (buf, dguide_base, strlen (dguide_base));
26988   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26989           IDENTIFIER_LENGTH (tname) + 1);
26990   tree dname = get_identifier (buf);
26991   TREE_TYPE (dname) = type;
26992   return dname;
26993 }
26994
26995 /* True if NAME is the name of a deduction guide.  */
26996
26997 bool
26998 dguide_name_p (tree name)
26999 {
27000   return (TREE_CODE (name) == IDENTIFIER_NODE
27001           && TREE_TYPE (name)
27002           && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
27003                        strlen (dguide_base)));
27004 }
27005
27006 /* True if FN is a deduction guide.  */
27007
27008 bool
27009 deduction_guide_p (const_tree fn)
27010 {
27011   if (DECL_P (fn))
27012     if (tree name = DECL_NAME (fn))
27013       return dguide_name_p (name);
27014   return false;
27015 }
27016
27017 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
27018
27019 bool
27020 copy_guide_p (const_tree fn)
27021 {
27022   gcc_assert (deduction_guide_p (fn));
27023   if (!DECL_ARTIFICIAL (fn))
27024     return false;
27025   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
27026   return (TREE_CHAIN (parms) == void_list_node
27027           && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
27028 }
27029
27030 /* True if FN is a guide generated from a constructor template.  */
27031
27032 bool
27033 template_guide_p (const_tree fn)
27034 {
27035   gcc_assert (deduction_guide_p (fn));
27036   if (!DECL_ARTIFICIAL (fn))
27037     return false;
27038   tree tmpl = DECL_TI_TEMPLATE (fn);
27039   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
27040     return PRIMARY_TEMPLATE_P (org);
27041   return false;
27042 }
27043
27044 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
27045    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
27046    template parameter types.  Note that the handling of template template
27047    parameters relies on current_template_parms being set appropriately for the
27048    new template.  */
27049
27050 static tree
27051 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
27052                        tree tsubst_args, tsubst_flags_t complain)
27053 {
27054   if (olddecl == error_mark_node)
27055     return error_mark_node;
27056
27057   tree oldidx = get_template_parm_index (olddecl);
27058
27059   tree newtype;
27060   if (TREE_CODE (olddecl) == TYPE_DECL
27061       || TREE_CODE (olddecl) == TEMPLATE_DECL)
27062     {
27063       tree oldtype = TREE_TYPE (olddecl);
27064       newtype = cxx_make_type (TREE_CODE (oldtype));
27065       TYPE_MAIN_VARIANT (newtype) = newtype;
27066       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
27067         TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
27068           = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
27069     }
27070   else
27071     {
27072       newtype = TREE_TYPE (olddecl);
27073       if (type_uses_auto (newtype))
27074         {
27075           // Substitute once to fix references to other template parameters.
27076           newtype = tsubst (newtype, tsubst_args,
27077                             complain|tf_partial, NULL_TREE);
27078           // Now substitute again to reduce the level of the auto.
27079           newtype = tsubst (newtype, current_template_args (),
27080                             complain, NULL_TREE);
27081         }
27082       else
27083         newtype = tsubst (newtype, tsubst_args,
27084                           complain, NULL_TREE);
27085     }
27086
27087   tree newdecl
27088     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
27089                   DECL_NAME (olddecl), newtype);
27090   SET_DECL_TEMPLATE_PARM_P (newdecl);
27091
27092   tree newidx;
27093   if (TREE_CODE (olddecl) == TYPE_DECL
27094       || TREE_CODE (olddecl) == TEMPLATE_DECL)
27095     {
27096       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
27097         = build_template_parm_index (index, level, level,
27098                                      newdecl, newtype);
27099       TEMPLATE_PARM_PARAMETER_PACK (newidx)
27100         = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
27101       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
27102       TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
27103
27104       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
27105         {
27106           DECL_TEMPLATE_RESULT (newdecl)
27107             = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
27108                           DECL_NAME (olddecl), newtype);
27109           DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
27110           // First create a copy (ttargs) of tsubst_args with an
27111           // additional level for the template template parameter's own
27112           // template parameters (ttparms).
27113           tree ttparms = (INNERMOST_TEMPLATE_PARMS
27114                           (DECL_TEMPLATE_PARMS (olddecl)));
27115           const int depth = TMPL_ARGS_DEPTH (tsubst_args);
27116           tree ttargs = make_tree_vec (depth + 1);
27117           for (int i = 0; i < depth; ++i)
27118             TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
27119           TREE_VEC_ELT (ttargs, depth)
27120             = template_parms_level_to_args (ttparms);
27121           // Substitute ttargs into ttparms to fix references to
27122           // other template parameters.
27123           ttparms = tsubst_template_parms_level (ttparms, ttargs,
27124                                                  complain|tf_partial);
27125           // Now substitute again with args based on tparms, to reduce
27126           // the level of the ttparms.
27127           ttargs = current_template_args ();
27128           ttparms = tsubst_template_parms_level (ttparms, ttargs,
27129                                                  complain);
27130           // Finally, tack the adjusted parms onto tparms.
27131           ttparms = tree_cons (size_int (depth), ttparms,
27132                                current_template_parms);
27133           DECL_TEMPLATE_PARMS (newdecl) = ttparms;
27134         }
27135     }
27136   else
27137     {
27138       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
27139       tree newconst
27140         = build_decl (DECL_SOURCE_LOCATION (oldconst),
27141                       TREE_CODE (oldconst),
27142                       DECL_NAME (oldconst), newtype);
27143       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
27144         = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
27145       SET_DECL_TEMPLATE_PARM_P (newconst);
27146       newidx = build_template_parm_index (index, level, level,
27147                                           newconst, newtype);
27148       TEMPLATE_PARM_PARAMETER_PACK (newidx)
27149         = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
27150       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
27151     }
27152
27153   return newdecl;
27154 }
27155
27156 /* Returns a C++17 class deduction guide template based on the constructor
27157    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
27158    guide, or REFERENCE_TYPE for an implicit copy/move guide.  */
27159
27160 static tree
27161 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
27162 {
27163   tree type, tparms, targs, fparms, fargs, ci;
27164   bool memtmpl = false;
27165   bool explicit_p;
27166   location_t loc;
27167   tree fn_tmpl = NULL_TREE;
27168
27169   if (TYPE_P (ctor))
27170     {
27171       type = ctor;
27172       bool copy_p = TYPE_REF_P (type);
27173       if (copy_p)
27174         {
27175           type = TREE_TYPE (type);
27176           fparms = tree_cons (NULL_TREE, type, void_list_node);
27177         }
27178       else
27179         fparms = void_list_node;
27180
27181       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
27182       tparms = DECL_TEMPLATE_PARMS (ctmpl);
27183       targs = CLASSTYPE_TI_ARGS (type);
27184       ci = NULL_TREE;
27185       fargs = NULL_TREE;
27186       loc = DECL_SOURCE_LOCATION (ctmpl);
27187       explicit_p = false;
27188     }
27189   else
27190     {
27191       ++processing_template_decl;
27192       bool ok = true;
27193
27194       fn_tmpl
27195         = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
27196            : DECL_TI_TEMPLATE (ctor));
27197       if (outer_args)
27198         fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
27199       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
27200
27201       type = DECL_CONTEXT (ctor);
27202
27203       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
27204       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
27205          fully specialized args for the enclosing class.  Strip those off, as
27206          the deduction guide won't have those template parameters.  */
27207       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
27208                                                 TMPL_PARMS_DEPTH (tparms));
27209       /* Discard the 'this' parameter.  */
27210       fparms = FUNCTION_ARG_CHAIN (ctor);
27211       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
27212       ci = get_constraints (ctor);
27213       loc = DECL_SOURCE_LOCATION (ctor);
27214       explicit_p = DECL_NONCONVERTING_P (ctor);
27215
27216       if (PRIMARY_TEMPLATE_P (fn_tmpl))
27217         {
27218           memtmpl = true;
27219
27220           /* For a member template constructor, we need to flatten the two
27221              template parameter lists into one, and then adjust the function
27222              signature accordingly.  This gets...complicated.  */
27223           tree save_parms = current_template_parms;
27224
27225           /* For a member template we should have two levels of parms/args, one
27226              for the class and one for the constructor.  We stripped
27227              specialized args for further enclosing classes above.  */
27228           const int depth = 2;
27229           gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
27230
27231           /* Template args for translating references to the two-level template
27232              parameters into references to the one-level template parameters we
27233              are creating.  */
27234           tree tsubst_args = copy_node (targs);
27235           TMPL_ARGS_LEVEL (tsubst_args, depth)
27236             = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
27237
27238           /* Template parms for the constructor template.  */
27239           tree ftparms = TREE_VALUE (tparms);
27240           unsigned flen = TREE_VEC_LENGTH (ftparms);
27241           /* Template parms for the class template.  */
27242           tparms = TREE_CHAIN (tparms);
27243           tree ctparms = TREE_VALUE (tparms);
27244           unsigned clen = TREE_VEC_LENGTH (ctparms);
27245           /* Template parms for the deduction guide start as a copy of the
27246              template parms for the class.  We set current_template_parms for
27247              lookup_template_class_1.  */
27248           current_template_parms = tparms = copy_node (tparms);
27249           tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
27250           for (unsigned i = 0; i < clen; ++i)
27251             TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
27252
27253           /* Now we need to rewrite the constructor parms to append them to the
27254              class parms.  */
27255           for (unsigned i = 0; i < flen; ++i)
27256             {
27257               unsigned index = i + clen;
27258               unsigned level = 1;
27259               tree oldelt = TREE_VEC_ELT (ftparms, i);
27260               tree olddecl = TREE_VALUE (oldelt);
27261               tree newdecl = rewrite_template_parm (olddecl, index, level,
27262                                                     tsubst_args, complain);
27263               if (newdecl == error_mark_node)
27264                 ok = false;
27265               tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
27266                                                  tsubst_args, complain, ctor);
27267               tree list = build_tree_list (newdef, newdecl);
27268               TEMPLATE_PARM_CONSTRAINTS (list)
27269                 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
27270                                           tsubst_args, complain, ctor);
27271               TREE_VEC_ELT (new_vec, index) = list;
27272               TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
27273             }
27274
27275           /* Now we have a final set of template parms to substitute into the
27276              function signature.  */
27277           targs = template_parms_to_args (tparms);
27278           fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
27279                                      complain, ctor);
27280           if (fparms == error_mark_node)
27281             ok = false;
27282           fargs = tsubst (fargs, tsubst_args, complain, ctor);
27283           if (ci)
27284             ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
27285
27286           current_template_parms = save_parms;
27287         }
27288
27289       --processing_template_decl;
27290       if (!ok)
27291         return error_mark_node;
27292     }
27293
27294   if (!memtmpl)
27295     {
27296       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
27297       tparms = copy_node (tparms);
27298       INNERMOST_TEMPLATE_PARMS (tparms)
27299         = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
27300     }
27301
27302   tree fntype = build_function_type (type, fparms);
27303   tree ded_fn = build_lang_decl_loc (loc,
27304                                      FUNCTION_DECL,
27305                                      dguide_name (type), fntype);
27306   DECL_ARGUMENTS (ded_fn) = fargs;
27307   DECL_ARTIFICIAL (ded_fn) = true;
27308   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
27309   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
27310   DECL_ARTIFICIAL (ded_tmpl) = true;
27311   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
27312   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
27313   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
27314   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
27315   if (DECL_P (ctor))
27316     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
27317   if (ci)
27318     set_constraints (ded_tmpl, ci);
27319
27320   return ded_tmpl;
27321 }
27322
27323 /* Deduce template arguments for the class template placeholder PTYPE for
27324    template TMPL based on the initializer INIT, and return the resulting
27325    type.  */
27326
27327 static tree
27328 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
27329                     tsubst_flags_t complain)
27330 {
27331   if (!DECL_CLASS_TEMPLATE_P (tmpl))
27332     {
27333       /* We should have handled this in the caller.  */
27334       if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
27335         return ptype;
27336       if (complain & tf_error)
27337         error ("non-class template %qT used without template arguments", tmpl);
27338       return error_mark_node;
27339     }
27340   if (init && TREE_TYPE (init) == ptype)
27341     /* Using the template parm as its own argument.  */
27342     return ptype;
27343
27344   tree type = TREE_TYPE (tmpl);
27345
27346   bool try_list_ctor = false;
27347
27348   releasing_vec rv_args = NULL;
27349   vec<tree,va_gc> *&args = *&rv_args;
27350   if (init == NULL_TREE
27351       || TREE_CODE (init) == TREE_LIST)
27352     args = make_tree_vector_from_list (init);
27353   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
27354     {
27355       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
27356       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
27357         {
27358           /* As an exception, the first phase in 16.3.1.7 (considering the
27359              initializer list as a single argument) is omitted if the
27360              initializer list consists of a single expression of type cv U,
27361              where U is a specialization of C or a class derived from a
27362              specialization of C.  */
27363           tree elt = CONSTRUCTOR_ELT (init, 0)->value;
27364           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
27365             {
27366               tree etype = TREE_TYPE (elt);
27367               tree tparms = (INNERMOST_TEMPLATE_PARMS
27368                              (DECL_TEMPLATE_PARMS (tmpl)));
27369               tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
27370               int err = unify (tparms, targs, type, etype,
27371                                UNIFY_ALLOW_DERIVED, /*explain*/false);
27372               if (err == 0)
27373                 try_list_ctor = false;
27374               ggc_free (targs);
27375             }
27376         }
27377       if (try_list_ctor || is_std_init_list (type))
27378         args = make_tree_vector_single (init);
27379       else
27380         args = make_tree_vector_from_ctor (init);
27381     }
27382   else
27383     args = make_tree_vector_single (init);
27384
27385   tree dname = dguide_name (tmpl);
27386   tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
27387                                       /*type*/false, /*complain*/false,
27388                                       /*hidden*/false);
27389   bool elided = false;
27390   if (cands == error_mark_node)
27391     cands = NULL_TREE;
27392
27393   /* Prune explicit deduction guides in copy-initialization context.  */
27394   if (flags & LOOKUP_ONLYCONVERTING)
27395     {
27396       for (lkp_iterator iter (cands); !elided && iter; ++iter)
27397         if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
27398           elided = true;
27399
27400       if (elided)
27401         {
27402           /* Found a nonconverting guide, prune the candidates.  */
27403           tree pruned = NULL_TREE;
27404           for (lkp_iterator iter (cands); iter; ++iter)
27405             if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
27406               pruned = lookup_add (*iter, pruned);
27407
27408           cands = pruned;
27409         }
27410     }
27411
27412   tree outer_args = NULL_TREE;
27413   if (DECL_CLASS_SCOPE_P (tmpl)
27414       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
27415     {
27416       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
27417       type = TREE_TYPE (most_general_template (tmpl));
27418     }
27419
27420   bool saw_ctor = false;
27421   // FIXME cache artificial deduction guides
27422   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
27423     {
27424       /* Skip inherited constructors.  */
27425       if (iter.using_p ())
27426         continue;
27427
27428       tree guide = build_deduction_guide (*iter, outer_args, complain);
27429       if (guide == error_mark_node)
27430         return error_mark_node;
27431       if ((flags & LOOKUP_ONLYCONVERTING)
27432           && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
27433         elided = true;
27434       else
27435         cands = lookup_add (guide, cands);
27436
27437       saw_ctor = true;
27438     }
27439
27440   tree call = error_mark_node;
27441
27442   /* If this is list-initialization and the class has a list constructor, first
27443      try deducing from the list as a single argument, as [over.match.list].  */
27444   tree list_cands = NULL_TREE;
27445   if (try_list_ctor && cands)
27446     for (lkp_iterator iter (cands); iter; ++iter)
27447       {
27448         tree dg = *iter;
27449         if (is_list_ctor (dg))
27450           list_cands = lookup_add (dg, list_cands);
27451       }
27452   if (list_cands)
27453     {
27454       ++cp_unevaluated_operand;
27455       call = build_new_function_call (list_cands, &args, tf_decltype);
27456       --cp_unevaluated_operand;
27457
27458       if (call == error_mark_node)
27459         {
27460           /* That didn't work, now try treating the list as a sequence of
27461              arguments.  */
27462           release_tree_vector (args);
27463           args = make_tree_vector_from_ctor (init);
27464         }
27465     }
27466
27467   /* Maybe generate an implicit deduction guide.  */
27468   if (call == error_mark_node && args->length () < 2)
27469     {
27470       tree gtype = NULL_TREE;
27471
27472       if (args->length () == 1)
27473         /* Generate a copy guide.  */
27474         gtype = build_reference_type (type);
27475       else if (!saw_ctor)
27476         /* Generate a default guide.  */
27477         gtype = type;
27478
27479       if (gtype)
27480         {
27481           tree guide = build_deduction_guide (gtype, outer_args, complain);
27482           if (guide == error_mark_node)
27483             return error_mark_node;
27484           cands = lookup_add (guide, cands);
27485         }
27486     }
27487
27488   if (elided && !cands)
27489     {
27490       error ("cannot deduce template arguments for copy-initialization"
27491              " of %qT, as it has no non-explicit deduction guides or "
27492              "user-declared constructors", type);
27493       return error_mark_node;
27494     }
27495   else if (!cands && call == error_mark_node)
27496     {
27497       error ("cannot deduce template arguments of %qT, as it has no viable "
27498              "deduction guides", type);
27499       return error_mark_node;
27500     }
27501
27502   if (call == error_mark_node)
27503     {
27504       ++cp_unevaluated_operand;
27505       call = build_new_function_call (cands, &args, tf_decltype);
27506       --cp_unevaluated_operand;
27507     }
27508
27509   if (call == error_mark_node && (complain & tf_warning_or_error))
27510     {
27511       error ("class template argument deduction failed:");
27512
27513       ++cp_unevaluated_operand;
27514       call = build_new_function_call (cands, &args, complain | tf_decltype);
27515       --cp_unevaluated_operand;
27516
27517       if (elided)
27518         inform (input_location, "explicit deduction guides not considered "
27519                 "for copy-initialization");
27520     }
27521
27522   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
27523 }
27524
27525 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
27526    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
27527    The CONTEXT determines the context in which auto deduction is performed
27528    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
27529    OUTER_TARGS are used during template argument deduction
27530    (context == adc_unify) to properly substitute the result, and is ignored
27531    in other contexts.
27532
27533    For partial-concept-ids, extra args may be appended to the list of deduced
27534    template arguments prior to determining constraint satisfaction.  */
27535
27536 tree
27537 do_auto_deduction (tree type, tree init, tree auto_node,
27538                    tsubst_flags_t complain, auto_deduction_context context,
27539                    tree outer_targs, int flags)
27540 {
27541   tree targs;
27542
27543   if (init == error_mark_node)
27544     return error_mark_node;
27545
27546   if (init && type_dependent_expression_p (init)
27547       && context != adc_unify)
27548     /* Defining a subset of type-dependent expressions that we can deduce
27549        from ahead of time isn't worth the trouble.  */
27550     return type;
27551
27552   /* Similarly, we can't deduce from another undeduced decl.  */
27553   if (init && undeduced_auto_decl (init))
27554     return type;
27555
27556   /* We may be doing a partial substitution, but we still want to replace
27557      auto_node.  */
27558   complain &= ~tf_partial;
27559
27560   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
27561     /* C++17 class template argument deduction.  */
27562     return do_class_deduction (type, tmpl, init, flags, complain);
27563
27564   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
27565     /* Nothing we can do with this, even in deduction context.  */
27566     return type;
27567
27568   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
27569      with either a new invented type template parameter U or, if the
27570      initializer is a braced-init-list (8.5.4), with
27571      std::initializer_list<U>.  */
27572   if (BRACE_ENCLOSED_INITIALIZER_P (init))
27573     {
27574       if (!DIRECT_LIST_INIT_P (init))
27575         type = listify_autos (type, auto_node);
27576       else if (CONSTRUCTOR_NELTS (init) == 1)
27577         init = CONSTRUCTOR_ELT (init, 0)->value;
27578       else
27579         {
27580           if (complain & tf_warning_or_error)
27581             {
27582               if (permerror (input_location, "direct-list-initialization of "
27583                              "%<auto%> requires exactly one element"))
27584                 inform (input_location,
27585                         "for deduction to %<std::initializer_list%>, use copy-"
27586                         "list-initialization (i.e. add %<=%> before the %<{%>)");
27587             }
27588           type = listify_autos (type, auto_node);
27589         }
27590     }
27591
27592   if (type == error_mark_node)
27593     return error_mark_node;
27594
27595   init = resolve_nondeduced_context (init, complain);
27596
27597   if (context == adc_decomp_type
27598       && auto_node == type
27599       && init != error_mark_node
27600       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
27601     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
27602        and initializer has array type, deduce cv-qualified array type.  */
27603     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
27604                                          complain);
27605   else if (AUTO_IS_DECLTYPE (auto_node))
27606     {
27607       tree stripped_init = tree_strip_any_location_wrapper (init);
27608       bool id = (DECL_P (stripped_init)
27609                  || ((TREE_CODE (init) == COMPONENT_REF
27610                       || TREE_CODE (init) == SCOPE_REF)
27611                      && !REF_PARENTHESIZED_P (init)));
27612       targs = make_tree_vec (1);
27613       TREE_VEC_ELT (targs, 0)
27614         = finish_decltype_type (init, id, tf_warning_or_error);
27615       if (type != auto_node)
27616         {
27617           if (complain & tf_error)
27618             error ("%qT as type rather than plain %<decltype(auto)%>", type);
27619           return error_mark_node;
27620         }
27621     }
27622   else
27623     {
27624       if (error_operand_p (init))
27625         return error_mark_node;
27626
27627       tree parms = build_tree_list (NULL_TREE, type);
27628       tree tparms;
27629
27630       if (flag_concepts)
27631         tparms = extract_autos (type);
27632       else
27633         {
27634           tparms = make_tree_vec (1);
27635           TREE_VEC_ELT (tparms, 0)
27636             = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
27637         }
27638
27639       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
27640       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
27641                                        DEDUCE_CALL,
27642                                        NULL, /*explain_p=*/false);
27643       if (val > 0)
27644         {
27645           if (processing_template_decl)
27646             /* Try again at instantiation time.  */
27647             return type;
27648           if (type && type != error_mark_node
27649               && (complain & tf_error))
27650             /* If type is error_mark_node a diagnostic must have been
27651                emitted by now.  Also, having a mention to '<type error>'
27652                in the diagnostic is not really useful to the user.  */
27653             {
27654               if (cfun
27655                   && FNDECL_USED_AUTO (current_function_decl)
27656                   && (auto_node
27657                       == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
27658                   && LAMBDA_FUNCTION_P (current_function_decl))
27659                 error ("unable to deduce lambda return type from %qE", init);
27660               else
27661                 error ("unable to deduce %qT from %qE", type, init);
27662               type_unification_real (tparms, targs, parms, &init, 1, 0,
27663                                      DEDUCE_CALL,
27664                                      NULL, /*explain_p=*/true);
27665             }
27666           return error_mark_node;
27667         }
27668     }
27669
27670   /* Check any placeholder constraints against the deduced type. */
27671   if (flag_concepts && !processing_template_decl)
27672     if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
27673       {
27674         /* Use the deduced type to check the associated constraints. If we
27675            have a partial-concept-id, rebuild the argument list so that
27676            we check using the extra arguments. */
27677         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
27678         tree cargs = CHECK_CONSTR_ARGS (constr);
27679         if (TREE_VEC_LENGTH (cargs) > 1)
27680           {
27681             cargs = copy_node (cargs);
27682             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
27683           }
27684         else
27685           cargs = targs;
27686         if (!constraints_satisfied_p (constr, cargs))
27687           {
27688             if (complain & tf_warning_or_error)
27689               {
27690                 auto_diagnostic_group d;
27691                 switch (context)
27692                   {
27693                   case adc_unspecified:
27694                   case adc_unify:
27695                     error("placeholder constraints not satisfied");
27696                     break;
27697                   case adc_variable_type:
27698                   case adc_decomp_type:
27699                     error ("deduced initializer does not satisfy "
27700                            "placeholder constraints");
27701                     break;
27702                   case adc_return_type:
27703                     error ("deduced return type does not satisfy "
27704                            "placeholder constraints");
27705                     break;
27706                   case adc_requirement:
27707                     error ("deduced expression type does not satisfy "
27708                            "placeholder constraints");
27709                     break;
27710                   }
27711                 diagnose_constraints (input_location, constr, targs);
27712               }
27713             return error_mark_node;
27714           }
27715       }
27716
27717   if (processing_template_decl && context != adc_unify)
27718     outer_targs = current_template_args ();
27719   targs = add_to_template_args (outer_targs, targs);
27720   return tsubst (type, targs, complain, NULL_TREE);
27721 }
27722
27723 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
27724    result.  */
27725
27726 tree
27727 splice_late_return_type (tree type, tree late_return_type)
27728 {
27729   if (is_auto (type))
27730     {
27731       if (late_return_type)
27732         return late_return_type;
27733
27734       tree idx = get_template_parm_index (type);
27735       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
27736         /* In an abbreviated function template we didn't know we were dealing
27737            with a function template when we saw the auto return type, so update
27738            it to have the correct level.  */
27739         return make_auto_1 (TYPE_IDENTIFIER (type), true);
27740     }
27741   return type;
27742 }
27743
27744 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
27745    'decltype(auto)' or a deduced class template.  */
27746
27747 bool
27748 is_auto (const_tree type)
27749 {
27750   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27751       && (TYPE_IDENTIFIER (type) == auto_identifier
27752           || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
27753     return true;
27754   else
27755     return false;
27756 }
27757
27758 /* for_each_template_parm callback for type_uses_auto.  */
27759
27760 int
27761 is_auto_r (tree tp, void */*data*/)
27762 {
27763   return is_auto (tp);
27764 }
27765
27766 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
27767    a use of `auto'.  Returns NULL_TREE otherwise.  */
27768
27769 tree
27770 type_uses_auto (tree type)
27771 {
27772   if (type == NULL_TREE)
27773     return NULL_TREE;
27774   else if (flag_concepts)
27775     {
27776       /* The Concepts TS allows multiple autos in one type-specifier; just
27777          return the first one we find, do_auto_deduction will collect all of
27778          them.  */
27779       if (uses_template_parms (type))
27780         return for_each_template_parm (type, is_auto_r, /*data*/NULL,
27781                                        /*visited*/NULL, /*nondeduced*/false);
27782       else
27783         return NULL_TREE;
27784     }
27785   else
27786     return find_type_usage (type, is_auto);
27787 }
27788
27789 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
27790    concepts are enabled, auto is acceptable in template arguments, but
27791    only when TEMPL identifies a template class.  Return TRUE if any
27792    such errors were reported.  */
27793
27794 bool
27795 check_auto_in_tmpl_args (tree tmpl, tree args)
27796 {
27797   /* If there were previous errors, nevermind.  */
27798   if (!args || TREE_CODE (args) != TREE_VEC)
27799     return false;
27800
27801   /* If TMPL is an identifier, we're parsing and we can't tell yet
27802      whether TMPL is supposed to be a type, a function or a variable.
27803      We'll only be able to tell during template substitution, so we
27804      expect to be called again then.  If concepts are enabled and we
27805      know we have a type, we're ok.  */
27806   if (flag_concepts
27807       && (identifier_p (tmpl)
27808           || (DECL_P (tmpl)
27809               &&  (DECL_TYPE_TEMPLATE_P (tmpl)
27810                    || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
27811     return false;
27812
27813   /* Quickly search for any occurrences of auto; usually there won't
27814      be any, and then we'll avoid allocating the vector.  */
27815   if (!type_uses_auto (args))
27816     return false;
27817
27818   bool errors = false;
27819
27820   tree vec = extract_autos (args);
27821   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
27822     {
27823       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
27824       error_at (DECL_SOURCE_LOCATION (xauto),
27825                 "invalid use of %qT in template argument", xauto);
27826       errors = true;
27827     }
27828
27829   return errors;
27830 }
27831
27832 /* For a given template T, return the vector of typedefs referenced
27833    in T for which access check is needed at T instantiation time.
27834    T is either  a FUNCTION_DECL or a RECORD_TYPE.
27835    Those typedefs were added to T by the function
27836    append_type_to_template_for_access_check.  */
27837
27838 vec<qualified_typedef_usage_t, va_gc> *
27839 get_types_needing_access_check (tree t)
27840 {
27841   tree ti;
27842   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
27843
27844   if (!t || t == error_mark_node)
27845     return NULL;
27846
27847   if (!(ti = get_template_info (t)))
27848     return NULL;
27849
27850   if (CLASS_TYPE_P (t)
27851       || TREE_CODE (t) == FUNCTION_DECL)
27852     {
27853       if (!TI_TEMPLATE (ti))
27854         return NULL;
27855
27856       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
27857     }
27858
27859   return result;
27860 }
27861
27862 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
27863    tied to T. That list of typedefs will be access checked at
27864    T instantiation time.
27865    T is either a FUNCTION_DECL or a RECORD_TYPE.
27866    TYPE_DECL is a TYPE_DECL node representing a typedef.
27867    SCOPE is the scope through which TYPE_DECL is accessed.
27868    LOCATION is the location of the usage point of TYPE_DECL.
27869
27870    This function is a subroutine of
27871    append_type_to_template_for_access_check.  */
27872
27873 static void
27874 append_type_to_template_for_access_check_1 (tree t,
27875                                             tree type_decl,
27876                                             tree scope,
27877                                             location_t location)
27878 {
27879   qualified_typedef_usage_t typedef_usage;
27880   tree ti;
27881
27882   if (!t || t == error_mark_node)
27883     return;
27884
27885   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
27886                || CLASS_TYPE_P (t))
27887               && type_decl
27888               && TREE_CODE (type_decl) == TYPE_DECL
27889               && scope);
27890
27891   if (!(ti = get_template_info (t)))
27892     return;
27893
27894   gcc_assert (TI_TEMPLATE (ti));
27895
27896   typedef_usage.typedef_decl = type_decl;
27897   typedef_usage.context = scope;
27898   typedef_usage.locus = location;
27899
27900   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
27901 }
27902
27903 /* Append TYPE_DECL to the template TEMPL.
27904    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
27905    At TEMPL instanciation time, TYPE_DECL will be checked to see
27906    if it can be accessed through SCOPE.
27907    LOCATION is the location of the usage point of TYPE_DECL.
27908
27909    e.g. consider the following code snippet:
27910
27911      class C
27912      {
27913        typedef int myint;
27914      };
27915
27916      template<class U> struct S
27917      {
27918        C::myint mi; // <-- usage point of the typedef C::myint
27919      };
27920
27921      S<char> s;
27922
27923    At S<char> instantiation time, we need to check the access of C::myint
27924    In other words, we need to check the access of the myint typedef through
27925    the C scope. For that purpose, this function will add the myint typedef
27926    and the scope C through which its being accessed to a list of typedefs
27927    tied to the template S. That list will be walked at template instantiation
27928    time and access check performed on each typedefs it contains.
27929    Note that this particular code snippet should yield an error because
27930    myint is private to C.  */
27931
27932 void
27933 append_type_to_template_for_access_check (tree templ,
27934                                           tree type_decl,
27935                                           tree scope,
27936                                           location_t location)
27937 {
27938   qualified_typedef_usage_t *iter;
27939   unsigned i;
27940
27941   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27942
27943   /* Make sure we don't append the type to the template twice.  */
27944   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27945     if (iter->typedef_decl == type_decl && scope == iter->context)
27946       return;
27947
27948   append_type_to_template_for_access_check_1 (templ, type_decl,
27949                                               scope, location);
27950 }
27951
27952 /* Convert the generic type parameters in PARM that match the types given in the
27953    range [START_IDX, END_IDX) from the current_template_parms into generic type
27954    packs.  */
27955
27956 tree
27957 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27958 {
27959   tree current = current_template_parms;
27960   int depth = TMPL_PARMS_DEPTH (current);
27961   current = INNERMOST_TEMPLATE_PARMS (current);
27962   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27963
27964   for (int i = 0; i < start_idx; ++i)
27965     TREE_VEC_ELT (replacement, i)
27966       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27967
27968   for (int i = start_idx; i < end_idx; ++i)
27969     {
27970       /* Create a distinct parameter pack type from the current parm and add it
27971          to the replacement args to tsubst below into the generic function
27972          parameter.  */
27973
27974       tree o = TREE_TYPE (TREE_VALUE
27975                           (TREE_VEC_ELT (current, i)));
27976       tree t = copy_type (o);
27977       TEMPLATE_TYPE_PARM_INDEX (t)
27978         = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27979                                       o, 0, 0, tf_none);
27980       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27981       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27982       TYPE_MAIN_VARIANT (t) = t;
27983       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27984       TYPE_CANONICAL (t) = canonical_type_parameter (t);
27985       TREE_VEC_ELT (replacement, i) = t;
27986       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27987     }
27988
27989   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27990     TREE_VEC_ELT (replacement, i)
27991       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27992
27993   /* If there are more levels then build up the replacement with the outer
27994      template parms.  */
27995   if (depth > 1)
27996     replacement = add_to_template_args (template_parms_to_args
27997                                         (TREE_CHAIN (current_template_parms)),
27998                                         replacement);
27999
28000   return tsubst (parm, replacement, tf_none, NULL_TREE);
28001 }
28002
28003 /* Entries in the decl_constraint hash table. */
28004 struct GTY((for_user)) constr_entry
28005 {
28006   tree decl;
28007   tree ci;
28008 };
28009
28010 /* Hashing function and equality for constraint entries. */
28011 struct constr_hasher : ggc_ptr_hash<constr_entry>
28012 {
28013   static hashval_t hash (constr_entry *e)
28014   {
28015     return (hashval_t)DECL_UID (e->decl);
28016   }
28017
28018   static bool equal (constr_entry *e1, constr_entry *e2)
28019   {
28020     return e1->decl == e2->decl;
28021   }
28022 };
28023
28024 /* A mapping from declarations to constraint information. Note that
28025    both templates and their underlying declarations are mapped to the
28026    same constraint information.
28027
28028    FIXME: This is defined in pt.c because garbage collection
28029    code is not being generated for constraint.cc. */
28030
28031 static GTY (()) hash_table<constr_hasher> *decl_constraints;
28032
28033 /* Returns the template constraints of declaration T. If T is not
28034    constrained, return NULL_TREE. Note that T must be non-null. */
28035
28036 tree
28037 get_constraints (tree t)
28038 {
28039   if (!flag_concepts)
28040     return NULL_TREE;
28041
28042   gcc_assert (DECL_P (t));
28043   if (TREE_CODE (t) == TEMPLATE_DECL)
28044     t = DECL_TEMPLATE_RESULT (t);
28045   constr_entry elt = { t, NULL_TREE };
28046   constr_entry* found = decl_constraints->find (&elt);
28047   if (found)
28048     return found->ci;
28049   else
28050     return NULL_TREE;
28051 }
28052
28053 /* Associate the given constraint information CI with the declaration
28054    T. If T is a template, then the constraints are associated with
28055    its underlying declaration. Don't build associations if CI is
28056    NULL_TREE.  */
28057
28058 void
28059 set_constraints (tree t, tree ci)
28060 {
28061   if (!ci)
28062     return;
28063   gcc_assert (t && flag_concepts);
28064   if (TREE_CODE (t) == TEMPLATE_DECL)
28065     t = DECL_TEMPLATE_RESULT (t);
28066   gcc_assert (!get_constraints (t));
28067   constr_entry elt = {t, ci};
28068   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
28069   constr_entry* entry = ggc_alloc<constr_entry> ();
28070   *entry = elt;
28071   *slot = entry;
28072 }
28073
28074 /* Remove the associated constraints of the declaration T.  */
28075
28076 void
28077 remove_constraints (tree t)
28078 {
28079   gcc_assert (DECL_P (t));
28080   if (TREE_CODE (t) == TEMPLATE_DECL)
28081     t = DECL_TEMPLATE_RESULT (t);
28082
28083   constr_entry elt = {t, NULL_TREE};
28084   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
28085   if (slot)
28086     decl_constraints->clear_slot (slot);
28087 }
28088
28089 /* Memoized satisfaction results for declarations. This
28090    maps the pair (constraint_info, arguments) to the result computed
28091    by constraints_satisfied_p.  */
28092
28093 struct GTY((for_user)) constraint_sat_entry
28094 {
28095   tree ci;
28096   tree args;
28097   tree result;
28098 };
28099
28100 /* Hashing function and equality for constraint entries. */
28101
28102 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
28103 {
28104   static hashval_t hash (constraint_sat_entry *e)
28105   {
28106     hashval_t val = iterative_hash_object(e->ci, 0);
28107     return iterative_hash_template_arg (e->args, val);
28108   }
28109
28110   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
28111   {
28112     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
28113   }
28114 };
28115
28116 /* Memoized satisfaction results for concept checks. */
28117
28118 struct GTY((for_user)) concept_spec_entry
28119 {
28120   tree tmpl;
28121   tree args;
28122   tree result;
28123 };
28124
28125 /* Hashing function and equality for constraint entries.  */
28126
28127 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
28128 {
28129   static hashval_t hash (concept_spec_entry *e)
28130   {
28131     return hash_tmpl_and_args (e->tmpl, e->args);
28132   }
28133
28134   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
28135   {
28136     ++comparing_specializations;
28137     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
28138     --comparing_specializations;
28139     return eq;
28140   }
28141 };
28142
28143 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
28144 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
28145
28146 /* Search for a memoized satisfaction result. Returns one of the
28147    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
28148
28149 tree
28150 lookup_constraint_satisfaction (tree ci, tree args)
28151 {
28152   constraint_sat_entry elt = { ci, args, NULL_TREE };
28153   constraint_sat_entry* found = constraint_memos->find (&elt);
28154   if (found)
28155     return found->result;
28156   else
28157     return NULL_TREE;
28158 }
28159
28160 /* Memoize the result of a satisfication test. Returns the saved result.  */
28161
28162 tree
28163 memoize_constraint_satisfaction (tree ci, tree args, tree result)
28164 {
28165   constraint_sat_entry elt = {ci, args, result};
28166   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
28167   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
28168   *entry = elt;
28169   *slot = entry;
28170   return result;
28171 }
28172
28173 /* Search for a memoized satisfaction result for a concept. */
28174
28175 tree
28176 lookup_concept_satisfaction (tree tmpl, tree args)
28177 {
28178   concept_spec_entry elt = { tmpl, args, NULL_TREE };
28179   concept_spec_entry* found = concept_memos->find (&elt);
28180   if (found)
28181     return found->result;
28182   else
28183     return NULL_TREE;
28184 }
28185
28186 /* Memoize the result of a concept check. Returns the saved result.  */
28187
28188 tree
28189 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
28190 {
28191   concept_spec_entry elt = {tmpl, args, result};
28192   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
28193   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
28194   *entry = elt;
28195   *slot = entry;
28196   return result;
28197 }
28198
28199 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
28200
28201 /* Returns a prior concept specialization. This returns the substituted
28202    and normalized constraints defined by the concept.  */
28203
28204 tree
28205 get_concept_expansion (tree tmpl, tree args)
28206 {
28207   concept_spec_entry elt = { tmpl, args, NULL_TREE };
28208   concept_spec_entry* found = concept_expansions->find (&elt);
28209   if (found)
28210     return found->result;
28211   else
28212     return NULL_TREE;
28213 }
28214
28215 /* Save a concept expansion for later.  */
28216
28217 tree
28218 save_concept_expansion (tree tmpl, tree args, tree def)
28219 {
28220   concept_spec_entry elt = {tmpl, args, def};
28221   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
28222   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
28223   *entry = elt;
28224   *slot = entry;
28225   return def;
28226 }
28227
28228 static hashval_t
28229 hash_subsumption_args (tree t1, tree t2)
28230 {
28231   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
28232   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
28233   int val = 0;
28234   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
28235   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
28236   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
28237   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
28238   return val;
28239 }
28240
28241 /* Compare the constraints of two subsumption entries.  The LEFT1 and
28242    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
28243    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
28244
28245 static bool
28246 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
28247 {
28248   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
28249     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
28250       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
28251                              CHECK_CONSTR_ARGS (right1)))
28252         return comp_template_args (CHECK_CONSTR_ARGS (left2),
28253                                   CHECK_CONSTR_ARGS (right2));
28254   return false;
28255 }
28256
28257 /* Key/value pair for learning and memoizing subsumption results. This
28258    associates a pair of check constraints (including arguments) with
28259    a boolean value indicating the result.  */
28260
28261 struct GTY((for_user)) subsumption_entry
28262 {
28263   tree t1;
28264   tree t2;
28265   bool result;
28266 };
28267
28268 /* Hashing function and equality for constraint entries.  */
28269
28270 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
28271 {
28272   static hashval_t hash (subsumption_entry *e)
28273   {
28274     return hash_subsumption_args (e->t1, e->t2);
28275   }
28276
28277   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
28278   {
28279     ++comparing_specializations;
28280     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
28281     --comparing_specializations;
28282     return eq;
28283   }
28284 };
28285
28286 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
28287
28288 /* Search for a previously cached subsumption result. */
28289
28290 bool*
28291 lookup_subsumption_result (tree t1, tree t2)
28292 {
28293   subsumption_entry elt = { t1, t2, false };
28294   subsumption_entry* found = subsumption_table->find (&elt);
28295   if (found)
28296     return &found->result;
28297   else
28298     return 0;
28299 }
28300
28301 /* Save a subsumption result. */
28302
28303 bool
28304 save_subsumption_result (tree t1, tree t2, bool result)
28305 {
28306   subsumption_entry elt = {t1, t2, result};
28307   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
28308   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
28309   *entry = elt;
28310   *slot = entry;
28311   return result;
28312 }
28313
28314 /* Set up the hash table for constraint association. */
28315
28316 void
28317 init_constraint_processing (void)
28318 {
28319   if (!flag_concepts)
28320     return;
28321
28322   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
28323   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
28324   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
28325   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
28326   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
28327 }
28328
28329 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
28330    0..N-1.  */
28331
28332 void
28333 declare_integer_pack (void)
28334 {
28335   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
28336                                build_function_type_list (integer_type_node,
28337                                                          integer_type_node,
28338                                                          NULL_TREE),
28339                                NULL_TREE, ECF_CONST);
28340   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
28341   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
28342                               CP_BUILT_IN_INTEGER_PACK);
28343 }
28344
28345 /* Set up the hash tables for template instantiations.  */
28346
28347 void
28348 init_template_processing (void)
28349 {
28350   /* FIXME: enable sanitization (PR87847) */
28351   decl_specializations = hash_table<spec_hasher>::create_ggc (37, false);
28352   type_specializations = hash_table<spec_hasher>::create_ggc (37, false);
28353
28354   if (cxx_dialect >= cxx11)
28355     declare_integer_pack ();
28356 }
28357
28358 /* Print stats about the template hash tables for -fstats.  */
28359
28360 void
28361 print_template_statistics (void)
28362 {
28363   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
28364            "%f collisions\n", (long) decl_specializations->size (),
28365            (long) decl_specializations->elements (),
28366            decl_specializations->collisions ());
28367   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
28368            "%f collisions\n", (long) type_specializations->size (),
28369            (long) type_specializations->elements (),
28370            type_specializations->collisions ());
28371 }
28372
28373 #if CHECKING_P
28374
28375 namespace selftest {
28376
28377 /* Verify that build_non_dependent_expr () works, for various expressions,
28378    and that location wrappers don't affect the results.  */
28379
28380 static void
28381 test_build_non_dependent_expr ()
28382 {
28383   location_t loc = BUILTINS_LOCATION;
28384
28385   /* Verify constants, without and with location wrappers.  */
28386   tree int_cst = build_int_cst (integer_type_node, 42);
28387   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
28388
28389   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
28390   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
28391   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
28392
28393   tree string_lit = build_string (4, "foo");
28394   TREE_TYPE (string_lit) = char_array_type_node;
28395   string_lit = fix_string_type (string_lit);
28396   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
28397
28398   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
28399   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
28400   ASSERT_EQ (wrapped_string_lit,
28401              build_non_dependent_expr (wrapped_string_lit));
28402 }
28403
28404 /* Verify that type_dependent_expression_p () works correctly, even
28405    in the presence of location wrapper nodes.  */
28406
28407 static void
28408 test_type_dependent_expression_p ()
28409 {
28410   location_t loc = BUILTINS_LOCATION;
28411
28412   tree name = get_identifier ("foo");
28413
28414   /* If no templates are involved, nothing is type-dependent.  */
28415   gcc_assert (!processing_template_decl);
28416   ASSERT_FALSE (type_dependent_expression_p (name));
28417
28418   ++processing_template_decl;
28419
28420   /* Within a template, an unresolved name is always type-dependent.  */
28421   ASSERT_TRUE (type_dependent_expression_p (name));
28422
28423   /* Ensure it copes with NULL_TREE and errors.  */
28424   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
28425   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
28426
28427   /* A USING_DECL in a template should be type-dependent, even if wrapped
28428      with a location wrapper (PR c++/83799).  */
28429   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
28430   TREE_TYPE (using_decl) = integer_type_node;
28431   ASSERT_TRUE (type_dependent_expression_p (using_decl));
28432   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
28433   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
28434   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
28435
28436   --processing_template_decl;
28437 }
28438
28439 /* Run all of the selftests within this file.  */
28440
28441 void
28442 cp_pt_c_tests ()
28443 {
28444   test_build_non_dependent_expr ();
28445   test_type_dependent_expression_p ();
28446 }
28447
28448 } // namespace selftest
28449
28450 #endif /* #if CHECKING_P */
28451
28452 #include "gt-cp-pt.h"